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
refactor: remove retired Medulla integration
Steven Enamakel57b592999282
diff --git a/AGENTS.md b/AGENTS.mdindex caa36cb03f..b1233d2305 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -503,7 +503,6 @@ Every TinyHumans backend request must carry a sanitized `x-sdk-name`:- `BackendOAuthClient`- `IntegrationClient`, except redirected file downloads-- `MedullaClient`, including its separate SSE handshake- the host session owner's `POST /auth/login-token/consume` and`GET /auth/me` (`openhuman_tinyhumans::session`, through `ClientHeaders`)- the agent Langfuse ingestion requestdiff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex bd5e07fe49..1f6f15ce9d 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -429,7 +429,6 @@ media = ["openhuman-core/media", "openhuman-tinyhumans/media"]flows = ["openhuman-core/flows", "openhuman-tinyhumans/flows"]skills = ["openhuman-core/skills", "openhuman-tinyhumans/skills"]mcp = ["openhuman-core/mcp", "openhuman-tinyhumans/mcp"]-medulla = ["openhuman-core/medulla", "openhuman-tinyhumans/medulla"]channels = ["openhuman-core/channels", "openhuman-tinyhumans/channels"]sandbox-landlock = ["openhuman-core/sandbox-landlock", "openhuman-tinyhumans/sandbox-landlock"]sandbox-bubblewrap = ["openhuman-core/sandbox-bubblewrap", "openhuman-tinyhumans/sandbox-bubblewrap"]diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex c4528cc199..2b019709a5 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -16,7 +16,7 @@ description = "OpenHuman core business logic and RPC server"# The crate ships a verbatim GPLv3 `LICENSE` file but carried no `license` key,# which left the grant ambiguous to every tool that reads metadata rather than# the file (cargo-deny, crates.io, SBOM generators). Declared explicitly as-# `only` — not `or-later` — to match `medulla-public` and the `GPL-3.0-only`+# `only` — not `or-later` — to match the `GPL-3.0-only`# first-party crates in the closure (`tinyagents`).license.workspace = truerepository.workspace = true@@ -754,7 +754,7 @@ proptest = "1"# (`modules`: Contrib=ON, Product=ON) and with `scripts/ci/product-features.txt`,# which already lists it. This does NOT move the kernel floor: that profile is# `--no-default-features --features flows` and never reads this list.-default = ["media", "skills", "flows", "mcp", "channels", "medulla", "http-server", "scheduler-gate", "file-logging", "modules"]+default = ["media", "skills", "flows", "mcp", "channels", "http-server", "scheduler-gate", "file-logging", "modules"]# HTTP + Socket.IO server transport (#5048): the `/rpc` JSON-RPC endpoint and# its auth middleware/CORS layer (`core::jsonrpc`, `core::auth`), the `/v1`# OpenAI-compatible router (`inference::http`), the ad-hoc static-dir file@@ -1093,32 +1093,6 @@ mcp = []# the crash-reporting feature" error.crash-reporting = ["dep:sentry"]-# Medulla integration: the HTTP/SSE client for the Medulla orchestration backend-# (`openhuman::medulla::client`) — durable sessions, event streaming, worker-# routing + roster, the operator task ledger and its GitHub sources, one-shot-# orchestration runs, the public feedback board, and the onboarding history-# reward. This is the real Medulla surface; it replaced the `medulla-local`-# supervised-child draft, which has been removed.-#-# Default-ON, but INTENTIONALLY NOT FORWARDED to the Tauri shell (allowlisted in-# scripts/lib/feature-forwarding.mjs): the desktop app is-# OpenHuman's own product and never dials a Medulla backend. The consumer is the-# Medulla TUI, which embeds this crate directly.-#-# Facade + type carve-out, NOT a leaf gate: `pub mod medulla;` is always-# compiled, and `medulla::contract` + `medulla::events` stay compiled in BOTH-# builds because `crates/openhuman-embed/src/` names those types in public signatures. Only-# `medulla::client` — everything that touches reqwest — is gated. This follows-# the rule the `skills` / `mcp` gates established: carve inert types-# out and gate behaviour, so the two builds share one type definition and-# cannot drift.-#-# Sheds ZERO exclusive dependencies — do NOT "fix" the empty list. `reqwest`,-# `futures`, `serde`, and `tokio` are all load-bearing for other domains; the-# gate's value is compile-time surface and RPC/tool reach, not binary size.-# Verify before ever claiming otherwise:-# cargo tree -i reqwest --no-default-features-medulla = []# Channels domain: `openhuman::channels` (external-messaging providers — Telegram,# Discord, Slack, Signal, WhatsApp, iMessage, IRC, … — plus the channel runtime,diff --git a/crates/openhuman-core/README.md b/crates/openhuman-core/README.mdindex fab80d3c2f..5ca852f022 100644--- a/crates/openhuman-core/README.md+++ b/crates/openhuman-core/README.md@@ -6,7 +6,7 @@ dispatcher for OpenHuman. The `openhuman-core` binary itself lives in`crates/openhuman-cli` (it needs the `openhuman-tinyhumans` backend transportthis library does not carry). Hosted in-process by `crates/openhuman-app`(the Tauri shell), `crates/openhuman-embed` (the typed facade for third-party-embedders such as Medulla and OpenCompany), `crates/openhuman-tui`, and+embedders such as OpenCompany), `crates/openhuman-tui`, and`crates/openhuman-cli`.See `crates/openhuman-core/src/lib.rs` for the crate-level doc comment and@@ -16,7 +16,7 @@ AGENTS.md ("Rust domain structure") for the preferred per-domain module shape.Business logic lives one directory per domain under `src/<domain>/`. `*` marksmodules whose `pub mod` declaration in `lib.rs` is itself `#[cfg(feature)]`--gated (feature of the same name unless noted). `channels`, `mcp`, `medulla`,+gated (feature of the same name unless noted). `channels`, `mcp`,`skills`, `voice` and `web3` are always declared but gate most of theircontents inside `mod.rs` behind the feature of the same name. See the`[features]` block in `Cargo.toml` for what each gate pulls in.@@ -39,7 +39,6 @@ contents inside `mod.rs` behind the feature of the same name. See the| `json_schema` | Vendor-neutral JSON Schema and JSON value walking | || `mcp` | Host half of Model Context Protocol support | [README](src/mcp/README.md) || `media`* | Media generation and image tool contracts | [README](src/media/README.md) |-| `medulla` | Medulla cloud client, its wire vocabulary, and the shared harness contract types | [README](src/medulla/README.md) || `memory` | Memory orchestration — the host layer over `tinymemory-core` | [README](src/memory/README.md) || `modules`* | Loadable native modules — capabilities that live outside this binary | [README](src/modules/README.md) || `platform` | Host-platform services: process lifecycle, self-update, diagnostics, local transport surfaces | |@@ -85,7 +84,7 @@ asserts the two stay in sync. Slim or headless-embedding builds useGate names (see `Cargo.toml` for the full rationale behind each): `http-server`,`inference`, `documents`, `hosting`, `modules`, `voice`, `web3`,`runtime-node`, `contacts`, `media`, `flows`, `skills`, `mcp`,-`crash-reporting`, `medulla`, `channels`, `sandbox-landlock`,+`crash-reporting`, `channels`, `sandbox-landlock`,`sandbox-bubblewrap`, `browser-native`, `fantoccini`,`landlock`, `whatsapp-web`, `e2e-test-support`, `rss-bench`,`rss-bench-dhat`, `file-logging`, `scheduler-gate`, `bin-tools`. Read thediff --git a/crates/openhuman-core/src/agent/turn_workspace.rs b/crates/openhuman-core/src/agent/turn_workspace.rsindex f87b2e5a95..b6f1d7b749 100644--- a/crates/openhuman-core/src/agent/turn_workspace.rs+++ b/crates/openhuman-core/src/agent/turn_workspace.rs@@ -1,7 +1,7 @@//! Agent turn workspace — the per-turn filesystem root an embedder binds a//! single agent turn to.//!-//! A host that drives the core in-process (the Medulla TUI's embedded core, a+//! A host that drives the core in-process (an embedded core, a//! workflow node dispatched to the `openhuman` harness) runs one turn *against//! a checkout it names*, not against the operator's ambient//! [`Config::action_dir`](crate::config::Config). Everything thediff --git a/crates/openhuman-core/src/api/README.md b/crates/openhuman-core/src/api/README.mdindex 6982376cfa..20ff769cec 100644--- a/crates/openhuman-core/src/api/README.md+++ b/crates/openhuman-core/src/api/README.md@@ -112,8 +112,8 @@ None of them verify the signature; the backend stays the authority.`ProductIdentity` / `set_product_identity` attach a sanitized `x-sdk-name`header (`PRODUCT_IDENTITY_HEADER`) to every backend-bound request, so the-backend can attribute calls to OpenHuman, OpenCompany, or Medulla even though-all three share one login and reach the backend through this crate.+backend can attribute calls to OpenHuman or OpenCompany even though+both share one login and reach the backend through this crate.`ProductIdentity::new` keeps ASCII alphanumerics plus `.`, `_`, `-`,lower-cases, truncates to 64 bytes, and returns `None` when nothing survives,so the wrapped value can never break `HeaderValue` construction. The@@ -122,11 +122,10 @@ constructor parameter, because `BackendOAuthClient` is built at dozens ofcall sites across domains. **Call `set_product_identity` once at startup,before building any backend client** — `BackendOAuthClient` and`IntegrationClient` bake the identity into their default headers at-construction and do not pick up a later change (`MedullaClient` reads it-per-request, but do not rely on that difference). A build that never calls+construction and do not pick up a later change. A build that never callsthe setter sends `DEFAULT_PRODUCT_IDENTITY` (`"openhuman"`).-Tests across `api::product`, `api::rest`, `medulla`, and `integrations` all+Tests across `api::product`, `api::rest`, and `integrations` alltouch this process-global state; `product_identity_test_lock` (test-only)serializes them to avoid cross-module races.@@ -199,8 +198,7 @@ see [`models/mod.rs`](models/mod.rs) for the full list.`crates/openhuman-core/src/api/`.- Every TinyHumans backend request must carry a sanitized `x-sdk-name`:`BackendOAuthClient`, `IntegrationClient` (except redirected file- downloads), `MedullaClient` (including its separate SSE handshake), the- agent's Langfuse ingestion request, and — outside this crate — the host+ downloads), the agent's Langfuse ingestion request, and — outside this crate — the hostsession owner's `POST /auth/login-token/consume` / `GET /auth/me`(`openhuman_tinyhumans::session`, via `ClientHeaders`).- Never add `x-sdk-name` to third-party endpoints, MCP servers, BYOK@@ -213,7 +211,7 @@ see [`models/mod.rs`](models/mod.rs) for the full list.74 files outside `api/` reference `crate::api::`(`grep -rl 'crate::api::' crates/openhuman-core/src`). Heaviest consumers:`platform/socket/` (realtime client), `hosted/*` (billing, referral,-announcements, team), `medulla/client/`, `integrations/` and+announcements, team), `integrations/` and`integrations/composio/`, `channels/controllers/ops/` and`channels/bus/{delivery,progressive_ui}.rs` (which match on `BackendApiError` variants),`security/credentials/` (defines the `get_session_token` that `jwt.rs`diff --git a/crates/openhuman-core/src/api/config.rs b/crates/openhuman-core/src/api/config.rsindex 9b205a3a8c..69279307f7 100644--- a/crates/openhuman-core/src/api/config.rs+++ b/crates/openhuman-core/src/api/config.rs@@ -697,9 +697,9 @@ pub(crate) fn host_is_local(parsed: &url::Url) -> bool {/// Process-global mutex serialising every test in this crate that mutates the/// backend env vars (`BACKEND_URL` / `VITE_BACKEND_URL` / app-env overrides)./// `std::env` is process-global, so a module-local lock cannot prevent-/// cross-module races: `api::config`, `core::cli_tests`, and `medulla::ops`+/// cross-module races: `api::config` and `core::cli_tests`/// tests all mutate the same vars from parallel test threads, and under the-/// full-suite coverage lane that race reliably broke `medulla`'s+/// full-suite coverage lane that race reliably broke the/// "unconfigured" assertions. Every env-mutating test must take THIS lock.#[cfg(test)]pub(crate) fn backend_env_test_lock() -> std::sync::MutexGuard<'static, ()> {diff --git a/crates/openhuman-core/src/api/product.rs b/crates/openhuman-core/src/api/product.rsindex 0c2bf10471..9c3a5b5b32 100644--- a/crates/openhuman-core/src/api/product.rs+++ b/crates/openhuman-core/src/api/product.rs@@ -1,6 +1,6 @@//! Product identity attached to every backend-bound HTTP request.//!-//! OpenHuman, OpenCompany and Medulla share a single login and all three reach+//! OpenHuman and OpenCompany share a single login and both reach//! the TinyHumans backend through this crate, so without a per-product marker//! the backend sees three products as one undifferentiated user base. Every//! request therefore carries an `x-sdk-name` header, which the backend reads@@ -108,8 +108,7 @@ fn slot() -> &'static RwLock<ProductIdentity> {/// Call once during startup, before the first backend client is constructed./// [`crate::api::rest::BackendOAuthClient`] and `IntegrationClient` read the/// identity into their default headers at construction, so a later call does-/// not retroactively re-tag clients that already exist. (`MedullaClient` reads-/// it per request, but do not rely on that difference.)+/// not retroactively re-tag clients that already exist.pub fn set_product_identity(identity: ProductIdentity) {log::debug!("[api][product] product identity set to {identity}");let mut guard = slot()@@ -153,7 +152,7 @@ pub fn product_identity_headers() -> HeaderMap {/// process-wide product identity.////// The identity is process state, so a module-local lock cannot prevent-/// cross-module races: `api::product`, `api::rest`, `crate::medulla` and+/// cross-module races: `api::product`, `api::rest` and/// `crate::integrations` tests all touch it from parallel test threads, and/// a test asserting the `openhuman` default would flake against a test that has/// installed an override. Every test that touches the identity must take THISdiff --git a/crates/openhuman-core/src/api/product_tests.rs b/crates/openhuman-core/src/api/product_tests.rsindex f84ca51a88..d495523c96 100644--- a/crates/openhuman-core/src/api/product_tests.rs+++ b/crates/openhuman-core/src/api/product_tests.rs@@ -39,14 +39,14 @@ fn new_keeps_allowed_characters_and_trims() {fn new_drops_header_unsafe_characters() {// A newline would otherwise let a caller inject a second header.assert_eq!(- ProductIdentity::new("medulla\r\nx-admin: 1")+ ProductIdentity::new("opencompany\r\nx-admin: 1").unwrap().as_str(),- "medullax-admin1"+ "opencompanyx-admin1");assert_eq!(ProductIdentity::new("med ulla").unwrap().as_str(),- "medulla"+ "opencompany");}@@ -82,9 +82,9 @@ fn header_carries_the_current_identity() {DEFAULT_PRODUCT_IDENTITY);- set_product_identity(ProductIdentity::new("medulla").unwrap());+ set_product_identity(ProductIdentity::new("opencompany").unwrap());let headers = product_identity_headers();- assert_eq!(headers.get(PRODUCT_IDENTITY_HEADER).unwrap(), "medulla");+ assert_eq!(headers.get(PRODUCT_IDENTITY_HEADER).unwrap(), "opencompany");reset_product_identity_for_test();}diff --git a/crates/openhuman-core/src/config/migrations/README.md b/crates/openhuman-core/src/config/migrations/README.mdindex ee5b6a2077..69294c662c 100644--- a/crates/openhuman-core/src/config/migrations/README.md+++ b/crates/openhuman-core/src/config/migrations/README.md@@ -31,7 +31,7 @@ Startup data-migration runner gated by `Config::schema_version`. Each migration| `crates/openhuman-core/src/config/migrations/enable_session_shadow_reads.rs` | **8→9.** Flips a persisted `agent.session_shadow_reads = false` to `true` once, because `Config::save` writes every field and the new serde default would never apply to upgraded workspaces. Pure in-memory. || `crates/openhuman-core/src/config/migrations/retire_local_whisper_stt.rs` | **9→10.** Rewrites `stt_provider` (top-level or legacy `local_ai`) values naming the removed local whisper engine (`"whisper"`, `"local"`) to `"cloud"`, which defers to `voice_server.stt_engine`. Pure in-memory. || *(inline in `mod.rs`)* | **10→11.** `reseed_cloud_providers`: backfills the managed `openhuman` entry for workspaces that were born past the `== 1` gate with `cloud_providers = []`; reuses `unify_ai_provider_settings::seed_cloud_providers`, which is a no-op on a populated list. On save failure rolls back both the version and the seeded entries. |-| `crates/openhuman-core/src/config/migrations/retire_subconscious_medulla.rs` | **11→12.** Retires the removed Medulla subconscious engine: a persisted `engine = "medulla"` is rewritten to the supported engine. Pure in-memory. |+| `crates/openhuman-core/src/config/migrations/mod.rs` | **11→12.** Reserializes the retired subconscious engine name as `local` while preserving startup for old configuration files. || `crates/openhuman-core/src/config/migrations/retire_managed_tier_slugs.rs` | **12→13.** Retires the managed tier slugs (`chat-v1`, `agentic-v1`, …): every persisted one — `default_model`, orchestrator/team/delegate pins, `model_routes[].model` — becomes the managed default model (`openrouter/deepseek/deepseek-v4-flash`). Concrete ids and `hint:*` markers are untouched. Pure in-memory. || `crates/openhuman-core/src/config/migrations/mod_tests.rs` | Tests for `run_pending` ordering, gating, rollback-on-save-failure. || `crates/openhuman-core/src/config/migrations/*_tests.rs` | Per-migration unit tests; every migration module mounts its own `<name>_tests.rs` via `#[cfg(test)] #[path]`. |diff --git a/crates/openhuman-core/src/config/migrations/mod.rs b/crates/openhuman-core/src/config/migrations/mod.rsindex d66a28f373..5cff76072b 100644--- a/crates/openhuman-core/src/config/migrations/mod.rs+++ b/crates/openhuman-core/src/config/migrations/mod.rs@@ -34,7 +34,6 @@ mod repair_http_request_limits;mod retire_chat_v1_model;mod retire_local_whisper_stt;mod retire_managed_tier_slugs;-mod retire_subconscious_medulla;mod unify_ai_provider_settings;/// Current target schema version. Bumped alongside every new migration.@@ -603,37 +602,17 @@ pub async fn run_pending(config: &mut Config) {);}- // 11 -> 12: rewrite the removed Medulla subconscious engine to the- // supported local engine. The enum retains the legacy variant so old- // config files can be parsed before this migration runs.+ // 11 -> 12: reserialize the legacy subconscious engine name as `local`.+ // Deserialization accepts the retired name so old configs still start.if config.schema_version == 11 {- let previous_engine = config.subconscious.engine;- match retire_subconscious_medulla::run(config) {- Ok(migrated) => {- let previous_version = config.schema_version;- config.schema_version = 12;- if let Err(err) = config.save().await {- config.subconscious.engine = previous_engine;- config.schema_version = previous_version;- log::warn!(- "[migrations] retire_subconscious_medulla ran but config.save failed: \- {err:#} — rolled in-memory schema_version back to {previous_version}, \- will retry on next launch"- );- return;- }- log::info!(- "[migrations] schema_version bumped to 12 (retire_subconscious_medulla \- engine_migrated={migrated})"- );- }- Err(err) => {- log::warn!(- "[migrations] retire_subconscious_medulla failed: {err:#} — \- will retry on next launch"- );- }+ let previous_version = config.schema_version;+ config.schema_version = 12;+ if let Err(err) = config.save().await {+ config.schema_version = previous_version;+ log::warn!("[migrations] schema_version 12 save failed: {err:#}");+ return;}+ log::info!("[migrations] schema_version bumped to 12");}// 12 -> 13: retire the managed tier slugs (`chat-v1`, `agentic-v1`, …).diff --git a/crates/openhuman-core/src/config/migrations/mod_tests.rs b/crates/openhuman-core/src/config/migrations/mod_tests.rsindex dbec18d189..9a1bca4a0a 100644--- a/crates/openhuman-core/src/config/migrations/mod_tests.rs+++ b/crates/openhuman-core/src/config/migrations/mod_tests.rs@@ -148,13 +148,12 @@ async fn run_pending_bumps_version_on_fresh_install() {}#[tokio::test]-async fn run_pending_retires_medulla_engine_from_v11_config() {+async fn run_pending_rewrites_v11_config() {let tmp = TempDir::new().unwrap();fs::create_dir_all(tmp.path().join("workspace")).unwrap();let mut config = config_in(&tmp);config.schema_version = 11;- config.subconscious.engine = crate::config::schema::SubconsciousEngine::Medulla;run_pending(&mut config).await;diff --git a/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla.rs b/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla.rsdeleted file mode 100644index d12829e5f3..0000000000--- a/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla.rs+++ /dev/null@@ -1,31 +0,0 @@-//! Migration 11 → 12: retire the removed Medulla subconscious engine.-//!-//! Older configurations may select `engine = "medulla"`. The compatibility-//! enum variant keeps those files deserializable, while this migration makes-//! the persisted selection explicit and safe for the local engine now that-//! the Medulla implementation has been removed.--use crate::config::{schema::SubconsciousEngine, Config};--/// Rewrite a legacy Medulla selection to the supported local engine.-///-/// The `medulla_local` section is intentionally left untouched so legacy-/// configuration remains lossless if it is inspected or rewritten by a-/// later tool. The caller persists the mutation and advances the schema-/// version.-pub fn run(config: &mut Config) -> anyhow::Result<bool> {- if config.subconscious.engine == SubconsciousEngine::Medulla {- config.subconscious.engine = SubconsciousEngine::Local;- log::info!("[migrations][retire-subconscious-medulla] engine=medulla -> engine=local");- Ok(true)- } else {- log::debug!(- "[migrations][retire-subconscious-medulla] no legacy Medulla engine selection found"- );- Ok(false)- }-}--#[cfg(test)]-#[path = "retire_subconscious_medulla_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla_tests.rs b/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla_tests.rsdeleted file mode 100644index 3ee4099072..0000000000--- a/crates/openhuman-core/src/config/migrations/retire_subconscious_medulla_tests.rs+++ /dev/null@@ -1,23 +0,0 @@-use super::*;--#[test]-fn rewrites_legacy_engine_to_local() {- let mut config = Config::default();- config.subconscious.engine = SubconsciousEngine::Medulla;- config.subconscious.medulla_local.serve_entry = "/legacy/serve.js".into();-- assert!(run(&mut config).unwrap());- assert_eq!(config.subconscious.engine, SubconsciousEngine::Local);- assert_eq!(- config.subconscious.medulla_local.serve_entry,- "/legacy/serve.js"- );-}--#[test]-fn leaves_local_engine_unchanged() {- let mut config = Config::default();-- assert!(!run(&mut config).unwrap());- assert_eq!(config.subconscious.engine, SubconsciousEngine::Local);-}diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rsindex 2e1a613ea6..6856813a8e 100644--- a/crates/openhuman-core/src/config/schema/mod.rs+++ b/crates/openhuman-core/src/config/schema/mod.rs@@ -12,7 +12,7 @@ pub use cloud_providers::{pub mod ephemeral_route;pub use ephemeral_route::{EphemeralRoute, EPHEMERAL_ROUTE_SLUG};pub mod subconscious;-pub use subconscious::{MedullaLocalConfig, SubconsciousConfig, SubconsciousEngine};+pub use subconscious::{SubconsciousConfig, SubconsciousEngine};mod agent;mod autonomy;mod capability_providers;diff --git a/crates/openhuman-core/src/config/schema/subconscious.rs b/crates/openhuman-core/src/config/schema/subconscious.rsindex 6b74283c74..a25fbab453 100644--- a/crates/openhuman-core/src/config/schema/subconscious.rs+++ b/crates/openhuman-core/src/config/schema/subconscious.rs@@ -1,25 +1,4 @@-//! Subconscious engine selection.-//!-//! `subconscious.engine` chooses which cognition drives the heartbeat tick's-//! observe/reflect/commit cycle:-//!-//! * `local` (default) — the local tinyagents graph.-//! * `medulla` — **accepted but not implemented in this build.** The-//! supervised `medulla-serve` child that backed it was removed along with-//! the `medulla_local` draft; the engine is to be re-ported onto the-//! `medulla` domain. A config selecting it logs a warning and runs the local-//! graph.-//!-//! # Why the variant and its settings still exist-//!-//! Deliberate back-compat, not oversight. Configs in the wild may carry-//! `engine = "medulla"` or a `[subconscious.medulla_local]` block, and serde-//! rejects an unknown enum variant — so deleting either would turn a-//! now-unsupported *setting* into a hard **startup failure**. Keeping them as-//! inert serde means such a host boots, runs the local graph, and says why.-//!-//! Remove them only once the engine is re-ported (making the variant live-//! again) or a config migration rewrites the affected keys.+//! Subconscious engine selection. The local graph is the supported engine.use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -28,126 +7,12 @@ use serde::{Deserialize, Serialize};#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "lowercase")]pub enum SubconsciousEngine {- /// The local tinyagents subconscious graph (unchanged default).+ /// The local tinyagents subconscious graph.+ /// Accept the retired name when loading old configuration, then persist+ /// the supported value on the next save.#[default]+ #[serde(alias = "medulla")]Local,- /// Route ticks through the Medulla brain.- ///- /// Accepted for back-compat but **not implemented in this build** — see the- /// module docs. Selecting it warns and falls back to [`Self::Local`].- Medulla,-}--impl SubconsciousEngine {- /// Whether the operator selected the medulla brain.- ///- /// True does **not** mean ticks route there — the engine is unimplemented- /// in this build. The tick uses this only to warn before running the local- /// graph.- pub fn is_medulla(self) -> bool {- matches!(self, Self::Medulla)- }-}--/// Settings for the supervised local `medulla-serve` child.-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct MedullaLocalConfig {- /// Path to medulla-v1's built serve entry (`dist/serve/index.js`). Empty- /// falls back to the `OPENHUMAN_MEDULLA_SERVE_ENTRY` environment override;- /// with neither set the medulla engine reports its serve entry as- /// unconfigured (see [`Self::resolved_serve_entry`]).- #[serde(default)]- pub serve_entry: String,- /// Overall deadline, in seconds, for one serve request (from writing the- /// `req` to receiving its correlated `res`), regardless of interleaved- /// frame traffic. Distinct from the per-read idle timeout: a child that- /// keeps streaming frames without ever answering is bounded by this- /// ceiling. `0` falls back to the default- /// ([`DEFAULT_REQUEST_DEADLINE_SECS`], 300).- #[serde(default = "default_request_deadline_secs")]- pub request_deadline_secs: u64,-}--impl Default for MedullaLocalConfig {- fn default() -> Self {- Self {- serve_entry: String::new(),- request_deadline_secs: DEFAULT_REQUEST_DEADLINE_SECS,- }- }-}--/// Default overall per-request deadline for serve requests, in seconds.-pub const DEFAULT_REQUEST_DEADLINE_SECS: u64 = 300;--/// Ceiling for [`MedullaLocalConfig::request_deadline_secs`]: 24 hours. Larger-/// values add no practical headroom and a near-`u64::MAX` duration would panic-/// in `Instant + Duration` arithmetic on the request path.-pub const MAX_REQUEST_DEADLINE_SECS: u64 = 24 * 60 * 60;--fn default_request_deadline_secs() -> u64 {- DEFAULT_REQUEST_DEADLINE_SECS-}--/// Environment override for the serve entry when `serve_entry` is left unset.-///-/// There is no portable compiled-in default: medulla-v1's built `dist/serve`-/// lives outside this repo, so its location is deployment-specific. A developer-/// pointing at their umbrella checkout sets this env var (or the config field)-/// rather than relying on a machine-local path baked into the binary.-const SERVE_ENTRY_ENV: &str = "OPENHUMAN_MEDULLA_SERVE_ENTRY";--impl MedullaLocalConfig {- /// The resolved serve entry, or `None` when it is unconfigured.- ///- /// Precedence: the explicit `serve_entry` config value, then the- /// `OPENHUMAN_MEDULLA_SERVE_ENTRY` environment override. When neither is- /// set this returns `None` — the medulla engine then reports the serve- /// entry as unconfigured instead of pointing at a machine-local path.- pub fn resolved_serve_entry(&self) -> Option<std::path::PathBuf> {- Self::resolve_entry(&self.serve_entry, std::env::var(SERVE_ENTRY_ENV).ok())- }-- /// The effective overall per-request deadline. A configured `0` (an- /// explicit zero would disable the ceiling entirely — never wanted) falls- /// back to the default.- pub fn request_deadline(&self) -> std::time::Duration {- let secs = if self.request_deadline_secs == 0 {- tracing::warn!(- configured = self.request_deadline_secs,- effective_secs = DEFAULT_REQUEST_DEADLINE_SECS,- "medulla_local request_deadline_secs=0 would disable the request ceiling; using the default"- );- DEFAULT_REQUEST_DEADLINE_SECS- } else if self.request_deadline_secs > MAX_REQUEST_DEADLINE_SECS {- tracing::warn!(- configured = self.request_deadline_secs,- effective_secs = MAX_REQUEST_DEADLINE_SECS,- "medulla_local request_deadline_secs exceeds the 24h ceiling; clamping"- );- MAX_REQUEST_DEADLINE_SECS- } else {- self.request_deadline_secs- };- std::time::Duration::from_secs(secs)- }-- /// Pure resolver shared by [`Self::resolved_serve_entry`], factored out so- /// the precedence rules are testable without mutating process env.- fn resolve_entry(configured: &str, env_override: Option<String>) -> Option<std::path::PathBuf> {- let trimmed = configured.trim();- if !trimmed.is_empty() {- return Some(std::path::PathBuf::from(trimmed));- }- let env = env_override?;- let env = env.trim();- if env.is_empty() {- None- } else {- Some(std::path::PathBuf::from(env))- }- }}/// The `[subconscious]` config block.@@ -157,9 +22,6 @@ pub struct SubconsciousConfig {/// Which engine drives the subconscious tick. Default `local`.#[serde(default)]pub engine: SubconsciousEngine,- /// Local `medulla-serve` child settings (only used when `engine = medulla`).- #[serde(default)]- pub medulla_local: MedullaLocalConfig,}#[cfg(test)]diff --git a/crates/openhuman-core/src/config/schema/subconscious_tests.rs b/crates/openhuman-core/src/config/schema/subconscious_tests.rsindex c72eb2338f..3b5ae76fb6 100644--- a/crates/openhuman-core/src/config/schema/subconscious_tests.rs+++ b/crates/openhuman-core/src/config/schema/subconscious_tests.rs@@ -6,114 +6,13 @@ fn default_engine_is_local() {SubconsciousConfig::default().engine,SubconsciousEngine::Local);- assert!(!SubconsciousConfig::default().engine.is_medulla());}#[test]-fn missing_block_deserializes_to_local() {- let config: SubconsciousConfig = serde_json::from_str("{}").unwrap();+fn legacy_engine_deserializes_as_local_and_serializes_as_local() {+ let config: SubconsciousConfig =+ serde_json::from_str(r#"{"engine":"medulla","medulla_local":{"serve_entry":"retired"}}"#)+ .unwrap();assert_eq!(config.engine, SubconsciousEngine::Local);-}--#[test]-fn engine_serde_round_trip() {- assert_eq!(- serde_json::to_string(&SubconsciousEngine::Medulla).unwrap(),- r#""medulla""#- );- assert_eq!(- serde_json::from_str::<SubconsciousEngine>(r#""local""#).unwrap(),- SubconsciousEngine::Local- );-}--#[test]-fn explicit_serve_entry_wins_over_env() {- // An explicit config value is used verbatim, ignoring any env override.- assert_eq!(- MedullaLocalConfig::resolve_entry("/tmp/serve.js", Some("/env/serve.js".to_string())),- Some(std::path::PathBuf::from("/tmp/serve.js"))- );- // Surrounding whitespace is trimmed.- assert_eq!(- MedullaLocalConfig::resolve_entry(" /tmp/serve.js ", None),- Some(std::path::PathBuf::from("/tmp/serve.js"))- );-}--#[test]-fn serve_entry_falls_back_to_env_override() {- assert_eq!(- MedullaLocalConfig::resolve_entry("", Some("/env/serve.js".to_string())),- Some(std::path::PathBuf::from("/env/serve.js"))- );- assert_eq!(- MedullaLocalConfig::resolve_entry(" ", Some(" /env/serve.js ".to_string())),- Some(std::path::PathBuf::from("/env/serve.js"))- );-}--#[test]-fn serve_entry_unconfigured_resolves_to_none() {- // No machine-local default is baked in: unset config + unset (or blank)- // env resolves to None so the engine reports it unconfigured.- assert_eq!(MedullaLocalConfig::resolve_entry("", None), None);- assert_eq!(- MedullaLocalConfig::resolve_entry("", Some(" ".to_string())),- None- );-}--#[test]-fn request_deadline_defaults_and_zero_falls_back() {- // Both construction paths — `Default` and a config that omits the- // field — land on the same documented default.- assert_eq!(- MedullaLocalConfig::default().request_deadline_secs,- DEFAULT_REQUEST_DEADLINE_SECS- );- let omitted: MedullaLocalConfig = serde_json::from_str("{}").unwrap();- assert_eq!(omitted.request_deadline_secs, DEFAULT_REQUEST_DEADLINE_SECS);-- // A configured value is honoured…- let configured: MedullaLocalConfig =- serde_json::from_str(r#"{ "request_deadline_secs": 120 }"#).unwrap();- assert_eq!(- configured.request_deadline(),- std::time::Duration::from_secs(120)- );-- // …and an explicit zero (which would disable the ceiling) falls back- // to the default instead.- let zeroed: MedullaLocalConfig =- serde_json::from_str(r#"{ "request_deadline_secs": 0 }"#).unwrap();- assert_eq!(- zeroed.request_deadline(),- std::time::Duration::from_secs(DEFAULT_REQUEST_DEADLINE_SECS)- );-}--#[test]-fn request_deadline_clamps_oversized_values_to_the_ceiling() {- // A near-u64::MAX duration would panic in `Instant + Duration`- // arithmetic on the request path; the accessor clamps instead.- let oversized: MedullaLocalConfig = serde_json::from_str(&format!(- r#"{{ "request_deadline_secs": {} }}"#,- u64::MAX - 1- ))- .unwrap();- assert_eq!(- oversized.request_deadline(),- std::time::Duration::from_secs(MAX_REQUEST_DEADLINE_SECS)- );- // The boundary value itself is accepted un-clamped.- let at_max: MedullaLocalConfig = serde_json::from_str(&format!(- r#"{{ "request_deadline_secs": {} }}"#,- MAX_REQUEST_DEADLINE_SECS- ))- .unwrap();- assert_eq!(- at_max.request_deadline(),- std::time::Duration::from_secs(MAX_REQUEST_DEADLINE_SECS)- );+ assert_eq!(serde_json::to_string(&config.engine).unwrap(), r#""local""#);}diff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rsindex b03219f5d0..d4cb24f112 100644--- a/crates/openhuman-core/src/config/schema/types/config.rs+++ b/crates/openhuman-core/src/config/schema/types/config.rs@@ -231,7 +231,7 @@ pub struct Config {pub heartbeat: HeartbeatConfig,/// Subconscious engine selection (local tinyagents graph vs. local- /// medulla-serve child). Default `local` — omitting this block preserves+ /// retired engine). Default `local` — omitting this block preserves/// the historical behavior exactly.#[serde(default)]pub subconscious: crate::config::schema::SubconsciousConfig,diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex d8cac24688..ca6363854d 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -104,15 +104,6 @@ pub enum DomainGroup {Web3,Voice,Media,- /// Medulla integration: the cloud client (`medulla`), the folded session- /// runtime (`medulla_session`), the chat store (`medulla::chat`), and- /// authored harness workflows (`medulla_workflows`).- ///- /// One coarse family rather than four, because these are never- /// independently useful — a host that wants `medulla_session` always wants- /// `medulla` (it folds that domain's envelopes). Splitting them would add- /// drift surface for no reachable configuration.- Medulla,// Families carved out of the `Platform` catch-all once the domain reorg// (#5328) gave each one a directory to be named after. Before that, half the// controller surface was tagged `Platform` purely because there was no@@ -172,7 +163,6 @@ impl DomainGroup {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Inference,DomainGroup::Integrations,DomainGroup::Automation,@@ -200,15 +190,14 @@ impl DomainGroup {DomainGroup::Web3 => 9,DomainGroup::Voice => 10,DomainGroup::Media => 11,- DomainGroup::Medulla => 12,- DomainGroup::Inference => 13,- DomainGroup::Integrations => 14,- DomainGroup::Automation => 15,- DomainGroup::Runtimes => 16,- DomainGroup::Desktop => 17,- DomainGroup::Hosted => 18,- DomainGroup::Modules => 19,- DomainGroup::Platform => 20,+ DomainGroup::Inference => 12,+ DomainGroup::Integrations => 13,+ DomainGroup::Automation => 14,+ DomainGroup::Runtimes => 15,+ DomainGroup::Desktop => 16,+ DomainGroup::Hosted => 17,+ DomainGroup::Modules => 18,+ DomainGroup::Platform => 19,}}}@@ -814,17 +803,6 @@ fn build_registered_controllers() -> Vec<GroupedController> {DomainGroup::Runtimes,crate::runtime::javascript::all_javascript_registered_controllers(),);- // Medulla integration: readiness, durable sessions, and the connected worker- // roster against the Medulla orchestration backend. Registration-site gate- // like `flows` — with the `medulla` feature off these methods are absent- // (unknown-method), which is what lets a host hide the surface instead of- // rendering a failure.- #[cfg(feature = "medulla")]- push(- &mut controllers,- DomainGroup::Medulla,- crate::medulla::all_medulla_registered_controllers(),- );// Discovered SKILL.md skills and their bundled resourcespush(&mut controllers,@@ -1235,7 +1213,6 @@ pub fn namespace_description(namespace: &str) -> Option<&'static str> {"inference" => Some("Connect to configured text, vision, and embedding inference runtimes."),"migrate" => Some("Data migration utilities."),"javascript" => Some("First-class JavaScript runtime bridge for listing and dispatching tools."),- "medulla" => Some("Medulla orchestration backend: integration readiness, durable sessions, and the connected worker roster."),"security" => Some("Security policy and autonomy guardrail metadata."),"service" => Some("Desktop service lifecycle management."),"session_import" => {diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rsindex 891109f3cc..b6186a483f 100644--- a/crates/openhuman-core/src/core/all_tests.rs+++ b/crates/openhuman-core/src/core/all_tests.rs@@ -1319,36 +1319,6 @@ fn http_host_controllers_absent_when_http_server_off() {);}-/// The `medulla` namespace registers under `DomainGroup::Medulla` when the-/// `medulla` feature is on.-///-/// Paired with the negative below. On its own this proves nothing about the-/// gate — a gate that removed nothing would still pass it.-#[cfg(feature = "medulla")]-#[test]-fn medulla_controllers_registered_when_feature_on() {- assert_eq!(- group_for_namespace("medulla"),- Some(DomainGroup::Medulla),- "`medulla` must register under DomainGroup::Medulla when the feature is on"- );-}--/// The `medulla` namespace leaves no trace when the feature is off.-///-/// This is the half that proves the gate removes something. It also pins the-/// intended off-state: **absence**, so a host sees unknown-method and hides the-/// surface, rather than a registered controller that fails at call time.-#[cfg(not(feature = "medulla"))]-#[test]-fn medulla_controllers_absent_when_feature_off() {- assert_eq!(- group_for_namespace("medulla"),- None,- "`medulla` must not register when the feature is off"- );-}-// ---- DomainGroup ↔ family-directory realignment ----------------------------// The reorg (#5328) made `crates/openhuman-core/src/` one directory per family, so the// runtime axis can finally name each one instead of sweeping half the surface@@ -1569,7 +1539,6 @@ fn every_domain_group_is_accounted_for_in_store_init_plan() {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Inference,DomainGroup::Integrations,DomainGroup::Automation,@@ -1627,7 +1596,6 @@ fn every_domain_group_is_accounted_for_in_subscriber_plan() {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Inference,DomainGroup::Automation,DomainGroup::Runtimes,diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rsindex 721b1e8f5a..fc3841c105 100644--- a/crates/openhuman-core/src/core/cli_tests.rs+++ b/crates/openhuman-core/src/core/cli_tests.rs@@ -53,7 +53,7 @@ fn launch_options_reject_missing_or_empty_values() {}/// Serialises env-mutating CLI tests via the crate-wide backend env lock —-/// these tests set `BACKEND_URL`, which `api::config` and `medulla::ops`+/// these tests set `BACKEND_URL`, which `api::config`/// tests also read/remove, so a module-local lock is not enough.fn env_lock() -> std::sync::MutexGuard<'static, ()> {crate::api::config::backend_env_test_lock()diff --git a/crates/openhuman-core/src/core/jsonrpc.rs b/crates/openhuman-core/src/core/jsonrpc.rsindex 4abb80f870..05d1b0684d 100644--- a/crates/openhuman-core/src/core/jsonrpc.rs+++ b/crates/openhuman-core/src/core/jsonrpc.rs@@ -2342,7 +2342,6 @@ pub async fn bootstrap_core_runtime(pub async fn start_core_runtime_services(services: crate::core::runtime::ServiceSet,config: Option<&crate::config::Config>,- flows_enabled: bool,) {let Some(cfg) = config else {log::error!(@@ -2366,11 +2365,7 @@ pub async fn start_core_runtime_services(match crate::platform::socket::global_socket_manager() {Some(socket_mgr) => {- crate::core::runtime::services::spawn_socket_auto_connect(- services,- socket_mgr.clone(),- flows_enabled,- );+ crate::core::runtime::services::spawn_socket_auto_connect(services, socket_mgr.clone());}None => {log::warn!(diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rsindex 15fe85b7f7..52a947fb1f 100644--- a/crates/openhuman-core/src/core/runtime/builder.rs+++ b/crates/openhuman-core/src/core/runtime/builder.rs@@ -198,9 +198,6 @@ pub struct DomainSet {/// future backing controller would stay live. Fold the media-generation/// controller into this group when it lands.pub media: bool,- /// Medulla integration: cloud client, session runtime, chat store, and- /// authored harness workflows.- pub medulla: bool,/// Model inference: providers, routing, local engines, embeddings.pub inference: bool,/// External connectors (Composio, calendar, file storage, task sources).@@ -236,7 +233,6 @@ impl DomainSet {web3: true,voice: true,media: true,- medulla: true,inference: true,integrations: true,automation: true,@@ -265,7 +261,6 @@ impl DomainSet {web3: false,voice: false,media: false,- medulla: false,inference: false,integrations: false,automation: false,@@ -277,8 +272,8 @@ impl DomainSet {}}- /// A long-lived embedded host: the harness core plus the Medulla- /// integration and the workflow engine it runs on, and the supporting+ /// A long-lived embedded host: the harness core plus the workflow engine+ /// and the supporting/// runtime, automation, integration, and platform surfaces it needs.////// Named for the *shape* rather than any downstream consumer — the core@@ -291,8 +286,8 @@ impl DomainSet {/// and todos, and leaves `channels` off — but `channel.web_chat` is tagged/// `DomainGroup::Channels` and an embedded host drives chat turns through it.///- /// `flows: true` is load-bearing, not incidental: `medulla_workflows` runs- /// on the tinyflows engine and boot reconciliation keys off+ /// `flows: true` keeps the tinyflows engine and boot reconciliation on;+ /// reconciliation keys off/// `ctx.domains().flows` rather than a `ServiceSet` flag.////// An embedded host supplies its own harness wrappers, networking and@@ -311,7 +306,6 @@ impl DomainSet {web3: false,voice: false,media: false,- medulla: true,inference: true,integrations: true,automation: true,@@ -346,7 +340,6 @@ impl DomainSet {web3: false,voice: false,media: false,- medulla: false,inference: false,integrations: false,automation: false,@@ -373,7 +366,6 @@ impl DomainSet {web3: false,voice: false,media: false,- medulla: false,inference: false,integrations: false,automation: false,@@ -400,7 +392,6 @@ impl DomainSet {DomainGroup::Web3 => self.web3,DomainGroup::Voice => self.voice,DomainGroup::Media => self.media,- DomainGroup::Medulla => self.medulla,DomainGroup::Inference => self.inference,DomainGroup::Integrations => self.integrations,DomainGroup::Automation => self.automation,@@ -435,7 +426,6 @@ impl DomainSet {web3: self.web3 && other.web3,voice: self.voice && other.voice,media: self.media && other.media,- medulla: self.medulla && other.medulla,inference: self.inference && other.inference,integrations: self.integrations && other.integrations,automation: self.automation && other.automation,@@ -630,8 +620,7 @@ impl CoreBuilder {/// Sugar over [`config`](Self::config), like [`workspace`](Self::workspace)./// Worth having as its own method because the value reaches more than the/// obvious client: `/auth/me` session validation, the hosted-backend- /// surfaces, and — with no `OPENHUMAN_MEDULLA_BASE_URL` override — the- /// Medulla client all resolve through it. A host that sets only one of+ /// surfaces all resolve through it. A host that sets only one of/// those has the other two pointing at a different deployment, which fails/// as "backend rejected session token" rather than as a mismatch.pub fn backend_url(mut self, url: impl Into<String>) -> Self {@@ -1020,12 +1009,7 @@ impl CoreRuntime {/// each service keeps its own runtime config gate.async fn start_selected_services(&self) {use crate::core::runtime::services;- jsonrpc::start_core_runtime_services(- self.services,- self.config.as_ref(),- self.ctx.domains().flows,- )- .await;+ jsonrpc::start_core_runtime_services(self.services, self.config.as_ref()).await;if self.services.heartbeat {services::spawn_login_gated_services(self.ctx.host_kind().is_desktop_shell());diff --git a/crates/openhuman-core/src/core/runtime/builder_tests.rs b/crates/openhuman-core/src/core/runtime/builder_tests.rsindex 8af49c17b9..f6af45591b 100644--- a/crates/openhuman-core/src/core/runtime/builder_tests.rs+++ b/crates/openhuman-core/src/core/runtime/builder_tests.rs@@ -18,7 +18,6 @@ fn domain_set_presets_have_expected_flags() {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Integrations,DomainGroup::Platform,] {@@ -45,7 +44,6 @@ fn domain_set_presets_have_expected_flags() {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Platform,] {assert!(!harness.allows(off), "harness() must NOT allow {off:?}");@@ -66,7 +64,6 @@ fn domain_set_presets_have_expected_flags() {DomainGroup::Web3,DomainGroup::Voice,DomainGroup::Media,- DomainGroup::Medulla,DomainGroup::Platform,] {assert!(!none.allows(group), "none() must NOT allow {group:?}");@@ -87,7 +84,6 @@ fn embedded_domain_set_enables_the_host_families() {DomainGroup::Threads,DomainGroup::Config,DomainGroup::Security,- DomainGroup::Medulla,DomainGroup::Platform,] {assert!(set.allows(on), "embedded() must allow {on:?}");@@ -105,9 +101,7 @@ fn embedded_domain_set_enables_the_host_families() {#[test]fn embedded_keeps_flows_on_for_workflow_boot_reconcile() {- // Not incidental: `medulla_workflows` runs on the tinyflows engine and- // boot reconciliation keys off `ctx.domains().flows`, not a ServiceSet- // flag. Turning this off silently strands orphaned runs.+ // Boot reconciliation keys off `ctx.domains().flows`.assert!(DomainSet::embedded().allows(DomainGroup::Flows));}@@ -120,7 +114,7 @@ fn embedded_keeps_channels_on_for_web_chat() {}#[test]-fn embedded_is_not_harness_plus_medulla() {+fn embedded_retains_supporting_domains() {// Guards the most tempting future "simplification": deriving this// preset from harness(), which leaves the supporting Platform,// Channels, and Integrations families off.diff --git a/crates/openhuman-core/src/core/runtime/services.rs b/crates/openhuman-core/src/core/runtime/services.rsindex 2f0b407878..3e52caf6a8 100644--- a/crates/openhuman-core/src/core/runtime/services.rs+++ b/crates/openhuman-core/src/core/runtime/services.rs@@ -426,7 +426,6 @@ pub(crate) async fn run_legacy_migrations(config: &Config) {pub fn spawn_socket_auto_connect(services: ServiceSet,socket_mgr: std::sync::Arc<crate::platform::socket::SocketManager>,- _flows_enabled: bool,) {if services.socketio {tokio::spawn(async move {@@ -456,8 +455,7 @@ pub fn spawn_socket_auto_connect("[socket] Session token found — auto-connecting to {}",api_url);- // Keep the authenticated token and user-scoped workflow bridge in- // one serialized identity transaction. The active profile may have+ // Rebind the socket identity in one serialized transaction. The active profile may have// changed since CoreRuntime::build(), so the build-time Config is// not authoritative here.let _rebind = socket_mgr.lock_identity_rebind().await;@@ -467,16 +465,8 @@ pub fn spawn_socket_auto_connect(// handshake (#6181); if it is already up for this identity there is// nothing to rebind.if socket_mgr.is_live_for(&api_url, &initial_token) {- // The socket is reusable, the bridge is not: it is pinned to the- // `Config` resolved above, which a workspace switch invalidates.- // `set_workflow_bridge` re-advertises over a live socket by- // design, so reinstall and skip only the handshake.- #[cfg(feature = "flows")]- if _flows_enabled {- crate::flows::medulla_bridge::install(std::sync::Arc::clone(&config));- }log::info!(- "[socket] Auto-connect: {api_url} already connected with this session — refreshed the workflow bridge, kept the socket"+ "[socket] Auto-connect: {api_url} already connected with this session — kept the socket");return;}@@ -484,10 +474,6 @@ pub fn spawn_socket_auto_connect(log::error!("[socket] Auto-connect could not stop the prior connection: {e}");return;}- #[cfg(feature = "flows")]- if _flows_enabled {- crate::flows::medulla_bridge::install(std::sync::Arc::clone(&config));- }let provider =crate::platform::socket::token_provider::token_provider_from_config(config);if let Err(e) = socket_mgr.connect_with_provider(&api_url, provider).await {diff --git a/crates/openhuman-core/src/flows/README.md b/crates/openhuman-core/src/flows/README.mdindex 4af696e12b..f834c7476c 100644--- a/crates/openhuman-core/src/flows/README.md+++ b/crates/openhuman-core/src/flows/README.md@@ -3,8 +3,7 @@Saved automation workflows — the graphs a user builds on the canvas or thecopilot builds for them. Owns CRUD/enable/run/resume/cancel for saved flows,the trigger → run bridge, the authoring tools (propose/create/edit/validate/-dry-run/save), discovery/suggestion tools, and the medulla workflow-plane-bridge. Does NOT own the workflow engine itself: `tinyflows` (vendored) owns+dry-run/save), and discovery/suggestion tools. Does NOT own the workflow engine itself: `tinyflows` (vendored) ownsthe model, validation, compilation, and its own in-crate state-graph runtime,and reaches OpenHuman only through the capability traits `tinyflows/` hereimplements.@@ -25,7 +24,7 @@ every symbol reached from outside is a registration site —`core::all::all_flows_registered_controllers`, `core::jsonrpc`'s`FlowTriggerSubscriber`, `core::runtime::services`' boot reconcile(`sweep_orphaned_running_runs_on_boot`, `reconcile_schedule_triggers_on_boot`),-`medulla_bridge::install`, the agent-tool `vec!` in `tools::ops`, and the+the agent-tool `vec!` in `tools::ops`, and the`workflow_builder` / `flow_discovery` entries in`agent::registry::agents::loader::BUILTINS`. Aregistration site wants *absence* when the feature is off, not a@@ -37,7 +36,6 @@ from always-compiled code.- `pub mod ops` (split into submodules under `ops/`, e.g. `ops/execution.rs`, `ops/resume.rs`, `ops/builder.rs`, `ops/triggers.rs`, `ops/drafts.rs`, `ops/discovery.rs`, `ops/wiring_warnings.rs`, `ops/inference_readiness.rs`) — CRUD (`flows_create/get/list/update/delete/duplicate/import/validate`), revision history (`flows_get_history`, `flows_rollback`), run lifecycle (`flows_run`, `flows_run_detached`, `flows_resume`, `flows_cancel_run`, `flows_list_runs`, `flows_list_all_runs`, `flows_get_run`, `flows_prune_runs`), `flows_set_enabled` (only `schedule` triggers need an enable-time binding — `cron::add_flow_schedule_job` / `cron::remove_job`; `app_event` flows are matched at dispatch time against enabled flows, and `webhook` binding is logged as not implemented), builder (`flows_build`, `flows_build_cancel`, `flows_search_tool_catalog`, `flows_get_tool_contract`, `flows_list_connections`, `flows_required_connections`, `flows_approval_manifest`), discovery (`flows_discover`, `flows_list_suggestions`, `flows_dismiss_suggestion`, `flows_mark_suggestion_built`), drafts (`flows_draft_create/get/update/list/delete/promote`), and boot/periodic reconciliation (`sweep_orphaned_running_runs_on_boot`, `reconcile_schedule_triggers_on_boot`, `sweep_expired_parked_runs`).- `pub mod bus` (split into `bus/trigger.rs`, `bus/run_digest.rs`, `bus/dedup_commit.rs`) — three subscribers, all constructed in `core/jsonrpc.rs`: `FlowTriggerSubscriber` (the trigger → run bridge: `DomainEvent::FlowScheduleTick` and `ComposioTriggerReceived` are matched against enabled flows' trigger nodes and spawn `ops::flows_run`; `WebhookIncomingRequest` is observed and logged only — webhook dispatch is not implemented), `FlowRunDigestSubscriber` (on a successful `FlowRunFinished`, writes a run digest into the flow's private memory namespace), and `DedupCommitSubscriber` (on `FlowRunFinished`, commits or rolls back every `dedup` node's tentative key set). `extract_trigger_kind` / `extract_trigger_config` are reused by `ops` to decide what `flows_set_enabled` and `flows_update` must bind or rebind.-- `pub mod medulla_bridge` — backs the medulla harness protocol's workflow plane (`platform::socket::medulla::workflows::WorkflowBridge`) with this store: projects saved `Flow`s onto the wire `WorkflowDescriptor`, serves the three read RPCs, and runs a `workflow_builder` copilot turn with host-enforced approval guards (creates always `require_approval: true`, updates never lower it, automatic-trigger creates are saved disabled).- `pub mod catalogue` — lists saved flows as `Workflow` entries with `WorkflowScope::Flow` in the shared skill catalogue, so `skill_search` sees one list instead of skills and flows separately.- `pub mod node_contracts` — host overlay on `tinyflows::catalog`'s node-kind contracts: attaches host-specific facts (which `tool_call` slugs resolve to Composio vs. native `oh:` tools, which trigger kinds actually dispatch here) without touching the portable contracts. Re-exports `all_node_kind_contracts`, `node_kind_contract`, `NODE_KINDS`, `ConfigField`, `PortSpec`, `NodeKindContract`.- `mod store` / `mod draft_store` (private) — bind `tinyflows_sqlite::flows` / `tinyflows_sqlite::drafts` to `<workspace_dir>/flows`; `kv_get`, `kv_set`, and `upsert_flow_run_step` are re-exported from `store` for the `tinyflows::caps::FlowStateStore` seam and the run observer.@@ -56,7 +54,6 @@ from always-compiled code.- `vendor/tinyflows/` — the actual workflow model, validation, compilation, and run engine; this domain never re-implements it.- `crates/openhuman-core/src/agent/tinyagents/` — message/tool-call/usage conversions used by the `llm` and `prompt` capabilities; `agent` nodes pass an explicit run context into nested harness turns through the `agent` capability (`tinyflows/caps/agent.rs`).- `crates/openhuman-core/src/cron/` — `add_flow_schedule_job` arms a schedule-triggered flow as a `JobType::Flow` cron job; the scheduler fires it by publishing `DomainEvent::FlowScheduleTick`, which `bus::FlowTriggerSubscriber` picks up.-- `crates/openhuman-core/src/platform/socket/medulla/workflows.rs` — `WorkflowBridge` trait implemented by `medulla_bridge`.- `crates/openhuman-core/src/skills/` — the `Workflow` / `WorkflowScope` catalogue types used by `catalogue.rs`, and the native `BundledSkill` mechanism that exposes the portable `tinyflows-copilot` authoring manual.- `crates/openhuman-core/src/memory/` — `memory_tools`/`tinyflows::memory_adapter` read/write agent memory under the `flows` scope.@@ -64,14 +61,12 @@ from always-compiled code.- `crates/openhuman-core/src/core/all.rs` — registers `all_flows_registered_controllers()` under `#[cfg(feature = "flows")]`.- `crates/openhuman-core/src/core/jsonrpc.rs` — constructs and subscribes `FlowTriggerSubscriber`, `FlowRunDigestSubscriber`, and `DedupCommitSubscriber` at startup.-- `crates/openhuman-core/src/core/runtime/services.rs` — runs `sweep_orphaned_running_runs_on_boot` and `reconcile_schedule_triggers_on_boot` during core boot and calls `medulla_bridge::install`; `platform/socket/ops.rs` installs the bridge on the socket path as well.- `crates/openhuman-core/src/tools/ops.rs` — pushes all 27 flows tools onto the agent tool list (`tools/mod.rs` re-exports the four tool modules).- `crates/openhuman-core/src/agent/registry/agents/loader.rs` — registers `workflow_builder` and `flow_discovery` as built-in archetypes.- `crates/openhuman-core/src/agent/session_host/` (`builder/factory.rs`, `turn/tools.rs`) — extends the skill catalogue with `catalogue::flow_entries`.## Tests-- Unit: `*_tests.rs` attached with `#[path]` to nearly every top-level file (`ops_tests*`, `bus_tests*`, `builder_tools_tests*`, `catalogue_tests.rs`, `discovery_tools_tests.rs`, `medulla_bridge_tests.rs`, `memory_tools_tests.rs`, `node_contracts_tests.rs`, `schemas_tests.rs`, `tools_tests.rs`), plus `import_tests.rs` for the n8n importer (declared in `mod.rs`).- `tinyflows/` has its own suite: `checkpoint_compat_tests.rs`, `memory_adapter_tests.rs`, `memory_node_e2e_tests.rs`, `observability_tests.rs`, `langfuse_export_tests.rs`, `tinyflows_tests.rs`, and `caps/*_tests.rs`.- Not compiled: `types.rs` / `types_tests.rs` are declared by no module (`flows::types` resolves to `tinyflows_catalog::types`, and `store.rs` has no test attachment). They are leftovers from moving the model and store into `tinyflows-catalog` / `tinyflows-sqlite`.diff --git a/crates/openhuman-core/src/flows/medulla_bridge.rs b/crates/openhuman-core/src/flows/medulla_bridge.rsdeleted file mode 100644index a628be2851..0000000000--- a/crates/openhuman-core/src/flows/medulla_bridge.rs+++ /dev/null@@ -1,598 +0,0 @@-//! Backs the medulla harness protocol's workflow plane-//! ([`crate::platform::socket::medulla::workflows::WorkflowBridge`]) with this-//! host's own `flows::` store.-//!-//! The transport half is host-agnostic on purpose — it moves adverts, opaque-//! JSON and one authoring turn, and parses no graph. This module is the-//! openhuman half: it projects saved [`Flow`]s onto the wire's-//! [`WorkflowDescriptor`], answers the three reads out of [`super::ops`], and-//! runs the `workflow_builder` agent for a `copilot` turn.-//!-//! **Why the copilot persists here.** In the desktop product a builder turn is-//! deliberately propose-only: [`super::ops::flows_build`] returns a candidate-//! graph and the *user* accepts it in the copilot panel, then saves it on the-//! canvas. On the medulla plane there is no panel and no user — a remote-//! orchestrator asked for a change and is waiting on the answer — so the accept-//! is performed here, by the host, from the proposal the turn produced. Two-//! guards keep that safe rather than merely convenient:-//!-//! - a **create** is persisted with `require_approval: true` unconditionally, so-//! every outbound action of a remotely-authored workflow still parks for a-//! human decision at run time;-//! - an **update** passes `require_approval: None`, so a remote turn can raise-//! a workflow's approval requirement (via `flows_update`'s own side-effect-//! enforcement) but can never lower one the user set.-//!-//! `flows_create` additionally saves any automatic-trigger graph **disabled**,-//! so nothing authored over this plane can start firing on its own.-//!-//! **Why the outcome is diffed, not reported.** [`WorkflowBridge::copilot`]'s-//! `changes` are computed by [`diff_workflow`] over the workflow this turn-//! successfully persisted, using listings taken before and after the turn —-//! never from what the agent said it did. Scoping the diff matters because a-//! copilot turn can run for minutes while a user edits unrelated workflows.-//! That is the whole reason medulla-v1 forwards the outcome verbatim instead of-//! re-deriving it: the claim that reaches the orchestrator is a statement about-//! the store, made by the store's owner.-//!-//! **Threading.** The three reads are synchronous on the trait but every-//! `flows::` op is `async`, so they bridge with a `Handle::block_on` — legal-//! because the transport only ever calls them from `spawn_blocking` (see-//! [`super::super::platform::socket::medulla::workflows`]), never on a runtime worker.-//! `copilot` is `async` end to end and needs no hop.--use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};-use tinyflows::model::WorkflowGraph;--use super::agents::workflow_builder::builder_prompt::{BuildMode, BuilderRequest};-use super::node_contracts::{all_node_kind_contracts, node_kind_contract, NODE_KINDS};-use super::ops;-use super::types::Flow;-use crate::config::Config;-use crate::platform::socket::medulla::payloads::{- CopilotOutcome, WorkflowDescriptor, WorkflowInputDescriptor,-};-use crate::platform::socket::medulla::workflows::{set_workflow_bridge, WorkflowBridge};--/// How many runs a `runs` read returns. The orchestrator wants "did this-/// workflow work lately", not an audit log, and the server caps a result at-/// 1 MiB — a bounded window answers the question and can never hit that cap.-const RUN_HISTORY_LIMIT: usize = 20;--/// Cap on a generated advert description. It is prompt surface rendered for-/// every workflow on every review pass, so a 40-node graph must not crowd out-/// the rest of the section.-const MAX_DESCRIPTION_CHARS: usize = 400;--/// Persistence tools hidden from a medulla copilot turn.-///-/// The generic builder exposes these for its product surfaces, but this bridge-/// deliberately owns persistence in [`apply_proposal`] so it can enforce the-/// observed version and approval floor exactly once.-const MEDULLA_COPILOT_HIDDEN_TOOLS: &[&str] = &[- "save_workflow",- "create_workflow",- "duplicate_flow",- "edit_workflow",-];--/// Install the flows-backed bridge on the medulla workflow plane.-///-/// Called once at boot, gated on the `flows` domain being live. Installing also-/// advertises immediately, so a core that connected before this ran still-/// publishes its workflows.-pub fn install(config: Arc<Config>) {- log::debug!("[flows] installing the medulla workflow bridge over the flows store");- set_workflow_bridge(Arc::new(FlowsWorkflowBridge::pinned(config)));-}--/// The `flows::`-backed [`WorkflowBridge`].-///-/// Holds no store handle: `flows::` is addressed by [`Config`], and the RPC-/// surface already re-reads the config per call rather than caching a snapshot-/// that a workspace switch would invalidate. `config` is `Some` only when a-/// caller pinned one (tests, and embedders that already hold a config).-pub struct FlowsWorkflowBridge {- config: Option<Arc<Config>>,-}--impl FlowsWorkflowBridge {- /// A bridge that resolves the process's current config on every call.- #[must_use]- pub fn new() -> Self {- Self { config: None }- }-- /// A bridge pinned to one config, for callers that already hold one and for- /// tests, which must address a temp workspace rather than the real one.- #[must_use]- pub fn pinned(config: Arc<Config>) -> Self {- Self {- config: Some(config),- }- }-- /// The config to address the store with, loaded if not pinned.- async fn config(&self) -> Result<Arc<Config>, String> {- match &self.config {- Some(config) => Ok(Arc::clone(config)),- None => crate::config::rpc::load_config_with_timeout()- .await- .map(Arc::new)- .map_err(|err| format!("this agent could not read its config: {err}")),- }- }-- /// Run one `flows::` op to completion from a synchronous trait method.- ///- /// Only legal off the runtime's async threads. The transport guarantees that- /// — every sync bridge call is already inside `spawn_blocking` — and a- /// caller that violates it panics there rather than deadlocking, which that- /// same `spawn_blocking` converts into a reported error.- fn on_store<T, F>(&self, run: impl FnOnce(Arc<Config>) -> F) -> Result<T, String>- where- F: std::future::Future<Output = Result<T, String>>,- {- let handle = tokio::runtime::Handle::try_current()- .map_err(|_| "this agent's workflow store has no runtime to answer on".to_string())?;- handle.block_on(async move {- let config = self.config().await?;- run(config).await- })- }-}--impl Default for FlowsWorkflowBridge {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl WorkflowBridge for FlowsWorkflowBridge {- fn action_dir(&self) -> Option<String> {- self.config- .as_ref()- .map(|config| config.action_dir.display().to_string())- }-- fn list(&self) -> Vec<WorkflowDescriptor> {- match self.try_list() {- Ok(descriptors) => descriptors,- Err(err) => {- log::warn!("[flows] medulla bridge could not list workflows: {err}");- Vec::new()- }- }- }-- fn try_list(&self) -> Result<Vec<WorkflowDescriptor>, String> {- self.on_store(|config| async move {- ops::flows_list(&config)- .await- .map(|outcome| outcome.value)- .map(|flows| flows.iter().map(describe_flow).collect::<Vec<_>>())- })- }-- fn get(&self, id: &str) -> Result<Value, String> {- let id = id.to_string();- self.on_store(|config| async move {- let flow = ops::flows_get(&config, &id).await?.value;- serde_json::to_value(&flow)- .map_err(|err| format!("failed to render workflow '{id}': {err}"))- })- }-- fn node_kinds(&self, kind: Option<&str>) -> Result<Value, String> {- // Purely static host+engine metadata — no store, no config, no runtime.- match kind.map(str::trim).filter(|kind| !kind.is_empty()) {- Some(kind) => {- let contract = node_kind_contract(kind).ok_or_else(|| {- format!(- "'{kind}' is not a node kind here; the kinds are: {}",- NODE_KINDS.join(", ")- )- })?;- Ok(json!({ "kinds": [node_kind_json(&contract)] }))- }- None => Ok(json!({- "kinds": all_node_kind_contracts()- .iter()- .map(node_kind_json)- .collect::<Vec<_>>(),- })),- }- }-- fn runs(&self, id: &str) -> Result<Value, String> {- let id = id.to_string();- self.on_store(|config| async move {- let runs = ops::flows_list_runs(&config, &id, RUN_HISTORY_LIMIT)- .await?- .value;- Ok(json!({ "runs": runs.iter().map(run_json).collect::<Vec<_>>() }))- })- }-- async fn copilot(- &self,- instruction: &str,- workflow_id: Option<&str>,- ) -> Result<CopilotOutcome, String> {- let config = self.config().await?;- let before = ops::flows_list(&config).await?.value;- let request = builder_request(instruction, workflow_id, &before)?;- let expected_version = workflow_id.and_then(|id| {- before- .iter()- .find(|flow| flow.id == id)- .map(|flow| flow.updated_at.as_str())- });-- // Headless: no chat thread to stream into, so the turn runs under the- // CLI origin with the full run-advancing hide-list — a remote authoring- // turn proposes a graph, it never runs one.- let built = ops::flows_build_with_extra_hidden_tools(- &config,- request,- None,- MEDULLA_COPILOT_HIDDEN_TOOLS,- )- .await?- .value;- let mut reply = built- .get("assistant_text")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();-- let mut applied = None;- if let Some(proposal) = built.get("proposal").filter(|value| !value.is_null()) {- match apply_proposal(&config, workflow_id, proposal, expected_version).await {- Ok(saved) => applied = Some(saved),- // The turn happened and its reply is worth returning; only the- // save failed. Say so in the reply rather than discarding the- // whole outcome — and let the diff below report (truthfully)- // that nothing changed.- Err(err) => {- log::warn!("[flows] medulla copilot could not persist its proposal: {err}");- reply = format!("{reply}\n\nThe proposed graph could not be saved: {err}");- }- }- }-- let changes = applied- .as_ref()- .map(|saved| diff_workflow(&before, std::slice::from_ref(&saved.flow), &saved.flow.id))- .unwrap_or_default();- let created = applied- .filter(|saved| saved.created)- .map(|saved| saved.flow.id);- Ok(CopilotOutcome {- reply,- changes,- created,- })- }-}--/// Project one saved flow onto the advert the orchestrator reasons over.-///-/// `name`/`description` are left as plain `String`s: the wire type skips them-/// when empty, so a nameless flow omits the key rather than sending `""`.-fn describe_flow(flow: &Flow) -> WorkflowDescriptor {- WorkflowDescriptor {- id: flow.id.clone(),- name: flow.name.trim().to_string(),- description: describe_graph(&flow.graph),- node_count: u32::try_from(flow.graph.nodes.len()).unwrap_or(u32::MAX),- enabled: Some(flow.enabled),- trigger_kind: trigger_kind(&flow.graph),- // Provenance is the backend's to stamp: this host runs one identity, so- // the batch-level `agentId` on the registration frame is the whole- // answer and a per-advert claim would only be redundant.- agent_id: None,- workspace_id: None,- inputs: describe_inputs(&flow.graph),- }-}--/// Projects the graph's declared inputs onto the wire descriptors.-///-/// The translation exists because the medulla plane's payload module is-/// compiled in every build while the engine is behind the `flows` gate — see-/// [`WorkflowInputDescriptor`]'s doc. This side is gated, so it may name the-/// engine type.-fn describe_inputs(graph: &WorkflowGraph) -> Vec<WorkflowInputDescriptor> {- graph- .inputs- .iter()- .map(|input| WorkflowInputDescriptor {- name: input.name.clone(),- ty: input.ty.as_str().to_string(),- description: input.description.clone().unwrap_or_default(),- required: input.required,- default: input.default.clone(),- })- .collect()-}--/// The open-vocabulary trigger label, when the graph has exactly one trigger-/// that names its kind. `None` covers "no trigger", "several triggers", and a-/// trigger with no `trigger_kind` — all cases where a claim would be a guess.-fn trigger_kind(graph: &WorkflowGraph) -> Option<String> {- graph- .trigger()?- .config- .get("trigger_kind")- .and_then(Value::as_str)- .map(str::to_string)-}--/// A one-line prose description of what a graph does, for the advert.-///-/// A flow has no author-written description field, so it is generated from the-/// graph's own step names: `"<trigger> → step → step"`. That is the same-/// information the Workflows list renders, written for a prompt instead of a-/// row, and truncated so one large graph cannot dominate the section.-fn describe_graph(graph: &WorkflowGraph) -> String {- let mut parts: Vec<String> = Vec::new();- parts.push(match trigger_kind(graph) {- Some(kind) => format!("on {kind}"),- None => "no trigger".to_string(),- });- parts.extend(- graph- .nodes- .iter()- .filter(|node| node.kind != tinyflows::model::NodeKind::Trigger)- .map(|node| node.name.trim())- .filter(|name| !name.is_empty())- .map(str::to_string),- );-- let rendered = parts.join(" → ");- if rendered.chars().count() <= MAX_DESCRIPTION_CHARS {- return rendered;- }- let truncated: String = rendered.chars().take(MAX_DESCRIPTION_CHARS).collect();- format!("{truncated}…")-}--/// Project a node-kind contract onto the `WorkflowNodeKind` shape medulla-v1's-/// port declares — camelCase, because the backend spreads this object straight-/// onto the port type and a snake_case key would land beside the field it was-/// meant to be rather than in it.-fn node_kind_json(contract: &crate::flows::node_contracts::NodeKindContract) -> Value {- json!({- "kind": contract.kind,- "summary": contract.summary,- "description": contract.description,- "configFields": contract.config_fields,- "ports": contract.ports,- "example": contract.example,- "notes": contract.notes,- })-}--/// Project a run row onto the `WorkflowRunSummary` shape the port declares.-///-/// Timestamps cross as epoch milliseconds because that is what the port's-/// `startedAt`/`finishedAt` are; the store keeps RFC3339, and an unparseable-/// stamp is omitted rather than sent as `0` (which reads as 1970, not "unknown").-/// The per-node `steps` are dropped: they are the run *inspector's* payload, and-/// a delegated-workflow read only asks whether it worked.-fn run_json(run: &super::types::FlowRun) -> Value {- let mut value = json!({- "id": run.id,- "workflowId": run.flow_id,- "status": run.status,- });- if let Some(started) = epoch_millis(&run.started_at) {- value["startedAt"] = json!(started);- }- if let Some(finished) = run.finished_at.as_deref().and_then(epoch_millis) {- value["finishedAt"] = json!(finished);- }- if let Some(error) = run.error.as_deref().filter(|error| !error.is_empty()) {- value["error"] = json!(error);- }- value-}--/// RFC3339 → epoch milliseconds, or `None` for a stamp this build cannot read.-fn epoch_millis(stamp: &str) -> Option<i64> {- chrono::DateTime::parse_from_rfc3339(stamp)- .ok()- .map(|parsed| parsed.timestamp_millis())-}--/// Build the authoring-turn request for one copilot call.-///-/// Naming a workflow is a **revise** of that exact graph, so the turn is briefed-/// with the saved graph and its id; naming none is a **create**. An id the store-/// does not hold fails here rather than silently degrading into a create — the-/// orchestrator asked to change something specific, and creating a second-/// workflow instead would be the wrong kind of surprising.-fn builder_request(- instruction: &str,- workflow_id: Option<&str>,- flows: &[Flow],-) -> Result<BuilderRequest, String> {- let (mode, graph, flow_id) = match workflow_id {- Some(id) => {- let flow = flows- .iter()- .find(|flow| flow.id == id)- .ok_or_else(|| format!("workflow '{id}' is not in this agent's store"))?;- let graph = serde_json::to_value(&flow.graph)- .map_err(|err| format!("failed to read workflow '{id}': {err}"))?;- (BuildMode::Revise, Some(graph), Some(id.to_string()))- }- None => (BuildMode::Create, None, None),- };- Ok(BuilderRequest {- mode,- instruction: instruction.to_string(),- graph,- flow_id,- run_id: None,- error: None,- failing_node_ids: Vec::new(),- })-}--/// The exact row committed by [`apply_proposal`].-#[derive(Debug)]-struct AppliedProposal {- flow: Flow,- created: bool,-}--/// Persist the graph a builder turn proposed, returning the committed row.-///-/// See the module docs for why this host performs the accept the copilot panel-/// would otherwise perform, and for the two approval guards that bound it.-async fn apply_proposal(- config: &Config,- workflow_id: Option<&str>,- proposal: &Value,- expected_version: Option<&str>,-) -> Result<AppliedProposal, String> {- let graph = proposal- .get("graph")- .filter(|graph| !graph.is_null())- .ok_or_else(|| "the copilot proposed no graph".to_string())?- .clone();-- match workflow_id {- // `require_approval: None` keeps whatever the user set. A remote turn- // may still have it forced ON by `flows_update`'s side-effect check; it- // can never turn it off.- Some(id) => {- let name = proposal- .get("name")- .and_then(Value::as_str)- .map(str::trim)- .filter(|name| !name.is_empty())- .map(str::to_string);- let flow = ops::flows_update_disarming_automatic(- config,- id,- name,- Some(graph),- None,- expected_version.map(str::to_string),- )- .await?- .value;- Ok(AppliedProposal {- flow,- created: false,- })- }- None => {- let name = proposal- .get("name")- .and_then(Value::as_str)- .map(str::trim)- .filter(|name| !name.is_empty())- .unwrap_or("Untitled workflow")- .to_string();- // `true`, not the proposal's own value: nothing authored by a remote- // instruction acts outward without a human decision at run time.- let flow = ops::flows_create(config, name, graph, true).await?.value;- Ok(AppliedProposal {- flow,- created: true,- })- }- }-}--/// What actually changed in the store across a copilot turn, as one line per-/// change.-///-/// Derived from two listings, never from the agent's account of its own turn —-/// see the module docs. A turn that talked and saved nothing yields an empty-/// list, which is exactly the claim it earns.-fn diff_flows(before: &[Flow], after: &[Flow]) -> Vec<String> {- let mut changes = Vec::new();-- for flow in after {- let Some(previous) = before.iter().find(|candidate| candidate.id == flow.id) else {- changes.push(format!(- "created workflow \"{}\" ({}) with {} node(s)",- flow.name,- flow.id,- flow.graph.nodes.len()- ));- continue;- };- if previous.name != flow.name {- changes.push(format!(- "renamed workflow {} from \"{}\" to \"{}\"",- flow.id, previous.name, flow.name- ));- }- if previous.graph != flow.graph {- changes.push(format!(- "rewrote the graph of workflow \"{}\" ({}): {} node(s) → {} node(s)",- flow.name,- flow.id,- previous.graph.nodes.len(),- flow.graph.nodes.len()- ));- }- if previous.enabled != flow.enabled {- let state = if flow.enabled { "enabled" } else { "disabled" };- changes.push(format!("{state} workflow \"{}\" ({})", flow.name, flow.id));- }- if previous.require_approval != flow.require_approval {- let state = if flow.require_approval {- "now requires"- } else {- "no longer requires"- };- changes.push(format!(- "workflow \"{}\" ({}) {state} approval for outbound actions",- flow.name, flow.id- ));- }- }-- for flow in before {- if !after.iter().any(|candidate| candidate.id == flow.id) {- changes.push(format!("deleted workflow \"{}\" ({})", flow.name, flow.id));- }- }-- changes-}--/// Diff only the workflow this copilot turn successfully persisted.-///-/// A turn may overlap arbitrary user edits elsewhere in the store. Those edits-/// are real, but they are not attributable to this turn and must not be claimed-/// in its result.-fn diff_workflow(before: &[Flow], after: &[Flow], workflow_id: &str) -> Vec<String> {- let before: Vec<Flow> = before- .iter()- .filter(|flow| flow.id == workflow_id)- .cloned()- .collect();- let after: Vec<Flow> = after- .iter()- .filter(|flow| flow.id == workflow_id)- .cloned()- .collect();- diff_flows(&before, &after)-}--#[cfg(test)]-#[path = "medulla_bridge_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/flows/medulla_bridge_tests.rs b/crates/openhuman-core/src/flows/medulla_bridge_tests.rsdeleted file mode 100644index 0e775978ee..0000000000--- a/crates/openhuman-core/src/flows/medulla_bridge_tests.rs+++ /dev/null@@ -1,636 +0,0 @@-use super::*;-use crate::config::Config;-use serde_json::json;-use tempfile::TempDir;-use tinyflows::model::{Node, NodeKind};--/// A config pointed at a throwaway workspace, so every test addresses its own-/// SQLite store instead of the developer's real one.-fn test_config(tmp: &TempDir) -> Arc<Config> {- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- std::fs::create_dir_all(&config.workspace_dir).unwrap();- Arc::new(config)-}--fn node(id: &str, kind: NodeKind, name: &str, config: Value) -> Node {- Node {- id: id.to_string(),- kind,- type_version: 1,- name: name.to_string(),- config,- ports: Vec::new(),- position: None,- }-}--/// A minimal manual-trigger graph with one named step.-fn graph_with_step(step_name: &str) -> WorkflowGraph {- WorkflowGraph {- nodes: vec![- node(- "t",- NodeKind::Trigger,- "Trigger",- json!({ "trigger_kind": "manual" }),- ),- node(- "s",- NodeKind::Code,- step_name,- json!({ "code": "return {}" }),- ),- ],- ..Default::default()- }-}--fn flow(id: &str, name: &str, graph: WorkflowGraph) -> Flow {- Flow {- id: id.to_string(),- name: name.to_string(),- enabled: true,- graph,- created_at: "2026-01-01T00:00:00Z".to_string(),- updated_at: "2026-01-01T00:00:00Z".to_string(),- last_run_at: None,- last_status: None,- require_approval: false,- }-}--// ── advert projection ────────────────────────────────────────────────────────--#[test]-fn describe_flow_counts_every_node_and_names_the_trigger() {- let descriptor = describe_flow(&flow("f1", "Deploy", graph_with_step("Ship it")));- assert_eq!(descriptor.id, "f1");- assert_eq!(descriptor.name, "Deploy");- // Trigger + step: the whole graph, not just the executable half.- assert_eq!(descriptor.node_count, 2);- assert_eq!(descriptor.enabled, Some(true));- assert_eq!(descriptor.trigger_kind.as_deref(), Some("manual"));- assert_eq!(descriptor.description, "on manual → Ship it");-}--#[test]-fn describe_flow_projects_declared_inputs_onto_the_advert() {- // The orchestrator picks a workflow off the advert, so the advert has to- // carry what running it requires — otherwise it can only find out by- // fetching the graph, or by trying and failing.- let mut graph = graph_with_step("Ship it");- graph.inputs = vec![- tinyflows::model::WorkflowInput::new("repo", tinyflows::model::InputType::String)- .required()- .with_description("Repo to deploy"),- tinyflows::model::WorkflowInput::new("depth", tinyflows::model::InputType::Number)- .with_default(serde_json::json!(3)),- ];-- let descriptor = describe_flow(&flow("f1", "Deploy", graph));- assert_eq!(descriptor.inputs.len(), 2);-- let repo = &descriptor.inputs[0];- assert_eq!(repo.name, "repo");- assert_eq!(repo.ty, "string");- assert!(repo.required);- assert_eq!(repo.description, "Repo to deploy");- assert_eq!(repo.default, None);-- let depth = &descriptor.inputs[1];- assert_eq!(depth.ty, "number");- assert!(!depth.required);- assert_eq!(depth.default, Some(serde_json::json!(3)));- assert!(- depth.description.is_empty(),- "an undescribed input sends no description rather than a null"- );-}--#[test]-fn a_workflow_declaring_no_inputs_advertises_none() {- let descriptor = describe_flow(&flow("f1", "Deploy", graph_with_step("Ship it")));- assert!(descriptor.inputs.is_empty());- let wire = serde_json::to_value(&descriptor).unwrap();- assert!(wire.get("inputs").is_none());-}--#[test]-fn a_blank_name_stays_absent_on_the_wire_rather_than_empty() {- let descriptor = describe_flow(&flow("f1", " ", graph_with_step("Step")));- assert!(descriptor.name.is_empty());- let wire = serde_json::to_value(&descriptor).unwrap();- // The contract is an ABSENT key, not `""` — both sides treat it as optional.- assert!(wire.get("name").is_none(), "wire = {wire}");- assert_eq!(wire["nodeCount"], 2);-}--#[test]-fn a_triggerless_graph_claims_no_trigger_kind() {- let graph = WorkflowGraph {- nodes: vec![node("s", NodeKind::Code, "Step", json!({}))],- ..Default::default()- };- let descriptor = describe_flow(&flow("f1", "Orphan", graph));- assert_eq!(descriptor.trigger_kind, None);- assert_eq!(descriptor.description, "no trigger → Step");-}--#[test]-fn a_long_graph_description_is_truncated() {- let nodes = (0..80)- .map(|i| {- node(- &format!("s{i}"),- NodeKind::Code,- "A fairly long step name",- json!({}),- )- })- .collect();- let descriptor = describe_flow(&flow(- "f1",- "Big",- WorkflowGraph {- nodes,- ..Default::default()- },- ));- assert_eq!(- descriptor.description.chars().count(),- MAX_DESCRIPTION_CHARS + 1- );- assert!(descriptor.description.ends_with('…'));-}--// ── node kinds ───────────────────────────────────────────────────────────────--#[test]-fn node_kinds_renders_the_catalog_in_the_ports_camel_case_shape() {- let bridge = FlowsWorkflowBridge::new();- let all = bridge.node_kinds(None).unwrap();- let kinds = all["kinds"].as_array().unwrap();- assert_eq!(kinds.len(), NODE_KINDS.len());- // `configFields`, not `config_fields`: the backend spreads this object onto- // the port type, so a snake_case key would miss the field entirely.- assert!(kinds[0].get("configFields").is_some());- assert!(kinds[0].get("config_fields").is_none());-- let one = bridge.node_kinds(Some("agent")).unwrap();- assert_eq!(one["kinds"].as_array().unwrap().len(), 1);- assert_eq!(one["kinds"][0]["kind"], "agent");-}--#[test]-fn an_unknown_node_kind_reports_the_real_ones() {- let err = FlowsWorkflowBridge::new()- .node_kinds(Some("teleport"))- .unwrap_err();- assert!(err.contains("teleport"), "{err}");- assert!(err.contains("tool_call"), "{err}");-}--#[test]-fn a_blank_kind_filter_means_the_whole_catalog() {- let bridge = FlowsWorkflowBridge::new();- assert_eq!(- bridge.node_kinds(Some(" ")).unwrap(),- bridge.node_kinds(None).unwrap()- );-}--// ── run projection ───────────────────────────────────────────────────────────--#[test]-fn run_json_emits_epoch_millis_and_omits_what_it_cannot_read() {- let run = super::super::types::FlowRun {- id: "r1".to_string(),- flow_id: "f1".to_string(),- thread_id: "r1".to_string(),- status: "completed".to_string(),- started_at: "2026-01-01T00:00:00Z".to_string(),- finished_at: Some("not a timestamp".to_string()),- steps: Vec::new(),- pending_approvals: Vec::new(),- error: None,- graph_hash: None,- };- let value = run_json(&run);- assert_eq!(value["id"], "r1");- assert_eq!(value["workflowId"], "f1");- assert_eq!(value["startedAt"], 1_767_225_600_000_i64);- // An unreadable stamp is absent, never `0` — that would read as 1970.- assert!(value.get("finishedAt").is_none(), "{value}");- assert!(value.get("error").is_none(), "{value}");- // The step-by-step payload belongs to the run inspector, not to this read.- assert!(value.get("steps").is_none(), "{value}");-}--// ── the store reads, over a real SQLite store ────────────────────────────────--/// Drive a synchronous bridge read the way the transport does — from a blocking-/// thread — since that is the only context its `block_on` is legal in.-async fn off_runtime<T, F>(read: F) -> T-where- T: Send + 'static,- F: FnOnce() -> T + Send + 'static,-{- tokio::task::spawn_blocking(read).await.unwrap()-}--#[tokio::test]-async fn list_and_get_answer_out_of_the_real_store() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let created = ops::flows_create(- &config,- "Deploy".to_string(),- serde_json::to_value(graph_with_step("Ship it")).unwrap(),- false,- )- .await- .unwrap()- .value;-- let bridge = Arc::new(FlowsWorkflowBridge::pinned(Arc::clone(&config)));-- let listed = off_runtime({- let bridge = Arc::clone(&bridge);- move || bridge.list()- })- .await;- assert_eq!(listed.len(), 1);- assert_eq!(listed[0].id, created.id);- assert_eq!(listed[0].node_count, 2);-- let id = created.id.clone();- let detail = off_runtime({- let bridge = Arc::clone(&bridge);- move || bridge.get(&id)- })- .await- .unwrap();- // The graph crosses whole and opaque — nothing above this parses it.- assert_eq!(detail["id"], created.id);- assert!(detail["graph"]["nodes"].as_array().unwrap().len() == 2);-}--#[tokio::test]-async fn an_unknown_id_is_a_readable_error_not_an_empty_answer() {- let tmp = TempDir::new().unwrap();- let bridge = Arc::new(FlowsWorkflowBridge::pinned(test_config(&tmp)));- let err = off_runtime(move || bridge.get("nope")).await.unwrap_err();- assert!(err.contains("nope"), "{err}");-}--#[tokio::test]-async fn runs_answers_with_an_empty_window_for_a_flow_that_never_ran() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let created = ops::flows_create(- &config,- "Deploy".to_string(),- serde_json::to_value(graph_with_step("Ship it")).unwrap(),- false,- )- .await- .unwrap()- .value;- let bridge = Arc::new(FlowsWorkflowBridge::pinned(config));- let runs = off_runtime(move || bridge.runs(&created.id)).await.unwrap();- assert_eq!(runs["runs"], json!([]));-}--// ── persisting a proposal ────────────────────────────────────────────────────--#[tokio::test]-async fn a_created_workflow_always_requires_approval() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let proposal = json!({- "name": "Remote build",- "graph": serde_json::to_value(graph_with_step("Ship it")).unwrap(),- // The proposal's own answer is deliberately ignored on this path.- "require_approval": false,- });-- let applied = apply_proposal(&config, None, &proposal, None)- .await- .unwrap();- assert!(applied.created);- let saved = ops::flows_get(&config, &applied.flow.id)- .await- .unwrap()- .value;- assert_eq!(saved.name, "Remote build");- assert!(- saved.require_approval,- "a remotely authored workflow must still park its outbound actions"- );-}--#[tokio::test]-async fn an_update_cannot_lower_the_approval_requirement() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let created = ops::flows_create(- &config,- "Deploy".to_string(),- serde_json::to_value(graph_with_step("Ship it")).unwrap(),- true,- )- .await- .unwrap()- .value;-- let proposal = json!({- "name": "Deploy v2",- "graph": serde_json::to_value(graph_with_step("Ship it twice")).unwrap(),- "require_approval": false,- });- let applied = apply_proposal(- &config,- Some(&created.id),- &proposal,- Some(&created.updated_at),- )- .await- .unwrap();- assert!(!applied.created, "an update is not a creation");- assert_eq!(applied.flow.id, created.id);-- let saved = ops::flows_get(&config, &created.id).await.unwrap().value;- assert_eq!(saved.name, "Deploy v2");- assert!(- saved.require_approval,- "the user's approval requirement survives a remote turn"- );-}--fn schedule_graph(cron: &str) -> Value {- json!({- "name": "scheduled",- "nodes": [{- "id": "t",- "kind": "trigger",- "name": "Trigger",- "config": { "trigger_kind": "schedule", "schedule": cron }- }],- "edges": []- })-}--#[tokio::test]-async fn a_remote_automatic_revision_requires_explicit_rearming() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let created = ops::flows_create(- &config,- "Scheduled".to_string(),- schedule_graph("0 9 * * *"),- true,- )- .await- .unwrap()- .value;- assert!(!created.enabled, "automatic flows are born disarmed");-- let armed = ops::flows_set_enabled(&config, &created.id, true)- .await- .unwrap()- .value;- assert!(armed.enabled, "precondition: the user explicitly armed it");-- let proposal = json!({- "name": "Scheduled v2",- "graph": schedule_graph("0 10 * * *"),- });- let applied = apply_proposal(&config, Some(&armed.id), &proposal, Some(&armed.updated_at))- .await- .unwrap();-- assert!(!applied.flow.enabled);- let saved = ops::flows_get(&config, &armed.id).await.unwrap().value;- assert!(!saved.enabled, "the revised schedule must stay disarmed");-}--#[tokio::test]-async fn a_proposal_without_a_graph_is_refused() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let err = apply_proposal(&config, None, &json!({ "name": "Nothing" }), None)- .await- .unwrap_err();- assert!(err.contains("no graph"), "{err}");-}--#[tokio::test]-async fn an_update_refuses_to_overwrite_a_concurrent_edit() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let created = ops::flows_create(- &config,- "Deploy".to_string(),- serde_json::to_value(graph_with_step("Ship it")).unwrap(),- true,- )- .await- .unwrap()- .value;-- ops::flows_update(- &config,- &created.id,- Some("User edit".to_string()),- None,- None,- Some(created.updated_at.clone()),- )- .await- .unwrap();-- let proposal = json!({- "name": "Copilot edit",- "graph": serde_json::to_value(graph_with_step("Ship it twice")).unwrap(),- });- let err = apply_proposal(- &config,- Some(&created.id),- &proposal,- Some(&created.updated_at),- )- .await- .unwrap_err();- assert!(err.contains("conflict"), "{err}");-- let saved = ops::flows_get(&config, &created.id).await.unwrap().value;- assert_eq!(saved.name, "User edit");-}--// ── the accountability diff ──────────────────────────────────────────────────--#[test]-fn diff_reports_a_creation_with_its_size() {- let after = vec![flow("f1", "Deploy", graph_with_step("Ship it"))];- let changes = diff_flows(&[], &after);- assert_eq!(changes.len(), 1);- assert!(- changes[0].contains("created workflow \"Deploy\" (f1)"),- "{changes:?}"- );- assert!(changes[0].contains("2 node(s)"), "{changes:?}");-}--#[test]-fn diff_reports_a_rewrite_a_rename_and_a_deletion() {- let before = vec![- flow("f1", "Deploy", graph_with_step("Ship it")),- flow("f2", "Doomed", graph_with_step("Step")),- ];- let mut renamed = flow("f1", "Deploy v2", graph_with_step("Ship it faster"));- renamed.enabled = false;- let changes = diff_flows(&before, &[renamed]);-- assert!(- changes- .iter()- .any(|line| line.contains("renamed workflow f1")),- "{changes:?}"- );- assert!(- changes- .iter()- .any(|line| line.contains("rewrote the graph")),- "{changes:?}"- );- assert!(- changes- .iter()- .any(|line| line.starts_with("disabled workflow")),- "{changes:?}"- );- assert!(- changes- .iter()- .any(|line| line.contains("deleted workflow \"Doomed\" (f2)")),- "{changes:?}"- );-}--#[test]-fn a_turn_that_changed_nothing_claims_nothing() {- let flows = vec![flow("f1", "Deploy", graph_with_step("Ship it"))];- // The whole point: the agent's account of its turn cannot inflate this.- assert!(diff_flows(&flows, &flows).is_empty());-}--#[test]-fn diff_reports_an_approval_requirement_change() {- let before = vec![flow("f1", "Deploy", graph_with_step("Ship it"))];- let mut after = before.clone();- after[0].require_approval = true;- let changes = diff_flows(&before, &after);- assert_eq!(changes.len(), 1);- assert!(changes[0].contains("now requires approval"), "{changes:?}");-}--#[test]-fn scoped_diff_excludes_concurrent_changes_to_other_workflows() {- let before = vec![- flow("target", "Deploy", graph_with_step("Ship it")),- flow("other", "Unrelated", graph_with_step("Before")),- ];- let after = vec![- flow("target", "Deploy v2", graph_with_step("Ship it twice")),- flow("other", "User edit", graph_with_step("After")),- flow("new", "Also user-created", graph_with_step("Step")),- ];-- let changes = diff_workflow(&before, &after, "target");- assert!(- changes.iter().all(|line| !line.contains("other")- && !line.contains("Unrelated")- && !line.contains("User edit")- && !line.contains("new")- && !line.contains("Also user-created")),- "{changes:?}"- );- assert!(- changes- .iter()- .any(|line| line.contains("renamed workflow target")),- "{changes:?}"- );- assert!(- changes- .iter()- .any(|line| line.contains("rewrote the graph")),- "{changes:?}"- );-}--#[test]-fn medulla_copilot_hides_every_persistence_tool() {- assert_eq!(- MEDULLA_COPILOT_HIDDEN_TOOLS,- [- "save_workflow",- "create_workflow",- "duplicate_flow",- "edit_workflow"- ]- );-}--#[test]-fn accountability_uses_the_committed_snapshot_not_a_later_user_edit() {- let before = vec![flow("target", "Deploy", graph_with_step("Ship it"))];- let committed = flow("target", "Copilot edit", graph_with_step("Ship it twice"));- let later_user_edit = flow("target", "User edit", graph_with_step("Something else"));-- let changes = diff_workflow(&before, std::slice::from_ref(&committed), "target");- assert!(- changes.iter().any(|line| line.contains("Copilot edit")),- "{changes:?}"- );- assert!(- changes- .iter()- .all(|line| !line.contains(&later_user_edit.name)),- "{changes:?}"- );-}--// ── the copilot turn's request shaping ───────────────────────────────────────--#[test]-fn naming_no_workflow_briefs_a_create() {- let request = builder_request("build a deploy flow", None, &[]).unwrap();- assert_eq!(request.mode, BuildMode::Create);- assert!(request.graph.is_none());- assert!(request.flow_id.is_none());- assert_eq!(request.instruction, "build a deploy flow");-}--#[test]-fn naming_a_workflow_briefs_a_revise_of_that_exact_graph() {- let flows = vec![flow("f1", "Deploy", graph_with_step("Ship it"))];- let request = builder_request("add a retry", Some("f1"), &flows).unwrap();- assert_eq!(request.mode, BuildMode::Revise);- assert_eq!(request.flow_id.as_deref(), Some("f1"));- assert_eq!(- request.graph.unwrap(),- serde_json::to_value(&flows[0].graph).unwrap()- );-}--#[test]-fn an_unknown_workflow_id_fails_rather_than_silently_creating_a_second_one() {- let err = builder_request("add a retry", Some("ghost"), &[]).unwrap_err();- assert!(err.contains("ghost"), "{err}");-}diff --git a/crates/openhuman-core/src/flows/mod.rs b/crates/openhuman-core/src/flows/mod.rsindex ef0dd635ff..0c0243fb7b 100644--- a/crates/openhuman-core/src/flows/mod.rs+++ b/crates/openhuman-core/src/flows/mod.rs@@ -7,10 +7,6 @@//! [`crate::flows::tinyflows::caps::FlowStateStore`]); the RPC/CLI//! controller surface in `schemas` (private, re-exported below).//!-//! [`medulla_bridge`] adapts this store onto the medulla harness protocol's-//! workflow plane, so a remote orchestrator can read these graphs and brief the-//! authoring copilot without any of that reaching back into `ops`.-//!//! # Gate shape — leaf, not facade//!//! The whole family (this module plus [`tinyflows`]) is gated at@@ -37,7 +33,6 @@ mod draft_store;#[cfg(test)]#[path = "import_tests.rs"]mod import_tests;-pub mod medulla_bridge;pub mod memory_tools;pub mod node_contracts;pub mod ops;diff --git a/crates/openhuman-core/src/flows/ops/definitions.rs b/crates/openhuman-core/src/flows/ops/definitions.rsindex 38d51a2687..bf3874e4ed 100644--- a/crates/openhuman-core/src/flows/ops/definitions.rs+++ b/crates/openhuman-core/src/flows/ops/definitions.rs@@ -11,14 +11,6 @@ pub(super) fn publish_flow_changed(flow_id: &str, kind: &str, actor: &str) {kind: kind.to_string(),actor: actor.to_string(),});- // Re-advertise the workflow set to the medulla backend. This is the single- // funnel every store mutation passes through (create / duplicate / update /- // delete / enable), and the backend replaces a socket's whole entry on each- // registration — so re-sending here is what keeps a remote orchestrator from- // reasoning about a set that no longer exists. A no-op (one debug log, no- // task spawned) when no bridge is installed, which is every build that is- // not talking to a backend, and every test.- crate::platform::socket::medulla::workflows::emit_register_workflows();}/// Creates a new flow from a name and a raw graph JSON value.diff --git a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rsindex 4c7f226458..de68febc97 100644--- a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs+++ b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs@@ -247,7 +247,7 @@ pub async fn list_configured_models_from_config(// backend (BACKEND_URL=http://127.0.0.1:...) still works in dev.if !token.is_empty() && url_is_credential_safe(&models_url) {// Managed traffic is attributed per embedding product- // (OpenCompany / Medulla / desktop); the generic provider client+ // (OpenCompany / desktop); the generic provider client// does not carry it, so attach it explicitly.let (name, value) = crate::api::product::product_identity_header();requestdiff --git a/crates/openhuman-core/src/integrations/composio/ops_profile_tools_execute_mock_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_profile_tools_execute_mock_tests.rsindex 599f43a65e..414abeb6be 100644--- a/crates/openhuman-core/src/integrations/composio/ops_profile_tools_execute_mock_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_profile_tools_execute_mock_tests.rs@@ -11,7 +11,7 @@ async fn composio_get_user_profile_via_mock_returns_provider_profile() {let _cache_guard = cache_guard();let _env_guard = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());// This test mutates BACKEND_URL below via EnvVarGuard, which races with- // api::config / core::cli_tests / medulla::ops / medulla::resolve tests+ // api::config / core::cli_tests tests// that mutate the same process-global var under the crate-wide lock —// TEST_ENV_LOCK alone does not serialize against those. Hold both.let _backend_env_guard = crate::api::config::backend_env_test_lock();diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rsindex 02a8b2e34f..4067a695eb 100644--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@ -4,7 +4,7 @@//! (`src/main.rs`). Owns business rules, persistence, execution//! policy, the JSON-RPC/Socket.IO server, and the CLI. Hosted in-process by//! `openhuman-app` (the Tauri shell), `openhuman-embed` (the typed facade for-//! third-party embedders such as Medulla and OpenCompany), and `openhuman-tui`.+//! third-party embedders such as OpenCompany), and `openhuman-tui`.//!//! Business logic lives one directory per domain family under `src/`, listed//! below in the order they are declared (module declarations are kept@@ -13,10 +13,10 @@//! `channels`, `config`, `core`, `cron`, `desktop`, `flows` (feature//! `flows`), `hooks`, `hosting` (feature `hosting`), `http_host`//! (feature `http-server`), `inference`, `integrations`, `json_schema`,-//! `mcp`, `media` (feature `media`), `medulla`, `memory`, `modules` (feature+//! `mcp`, `media` (feature `media`), `memory`, `modules` (feature//! `modules`), `platform`, `runtime`, `sandbox`, `search`, `security`,//! `skills`, `test_support` (feature `e2e-test-support`), `threads`, `tools`,-//! `util`, `voice`, `web3`, `web_chat`. `channels`, `mcp`, `medulla`,+//! `util`, `voice`, `web3`, `web_chat`. `channels`, `mcp`,//! `skills`, `voice` and `web3` are always declared but gate most of their//! contents inside their own `mod.rs` behind the feature of the same name.//! `core/` is not a domain: it holds transport, dispatch, the controller@@ -72,7 +72,6 @@ pub mod json_schema;pub mod mcp;#[cfg(feature = "media")]pub mod media;-pub mod medulla;pub mod memory;#[cfg(feature = "modules")]pub mod modules;diff --git a/crates/openhuman-core/src/medulla/README.md b/crates/openhuman-core/src/medulla/README.mddeleted file mode 100644index e0af7262da..0000000000--- a/crates/openhuman-core/src/medulla/README.md+++ /dev/null@@ -1,93 +0,0 @@-# Medulla--OpenHuman as a Medulla **client**: the HTTP/SSE surface that talks to the-Medulla orchestration backend, the wire vocabulary it speaks, and the-harness-contract types the client and the harness share. Do not confuse this-with `crates/openhuman-core/src/platform/socket/medulla`, which is the opposite-direction — OpenHuman as a Medulla **worker** answering inbound Socket.IO from-a remote operator. A single binary can be both at once; see `mod.rs` for the-full split.--Gated on the `medulla` Cargo feature and tagged-`DomainGroup::Medulla` (`crate::core::all::DomainGroup`) at runtime. The-feature is in the contributor `default` set of `crates/openhuman-core/Cargo.toml`-and forwarded by `crates/openhuman-embed`, but it is not in-`scripts/ci/product-features.txt`, so the shipped desktop app does not compile-this domain. `contract` and `events` are ungated carve-outs: inert serde/std-types with no coupling to their gated siblings, re-exported unconditionally-from `mod.rs` so a feature-off build shares one definition instead of a-drifting copy. Nothing outside `medulla/` currently imports them.--The `medulla_local` engine (a supervised `medulla-serve` child process) has-been removed; its `subconscious.engine = "medulla"` config keys are still-accepted as inert serde (`config::schema::subconscious`) so existing configs-keep booting while that behaviour is re-ported onto this domain.--## Layout--- `mod.rs` — feature gate, the client/worker split, `RESERVED_TOOL_NAMES` (the- harness's built-in memory/task-tracker tool names a module author must not- collide with).-- `contract.rs` — ungated. `WorkerContract` and `VerificationEvidence`: the- advisory boundaries and completion evidence Medulla transports verbatim for- a delegated worker lane. `camelCase` wire shapes.-- `events/` — ungated. `SessionEvent` (with an `Unknown` fallback so a newer- backend never drops rows on an older host) and `EventEnvelope`; `types.rs`- is the data model, `serde_impl.rs` the compact-JSON codec. Presentation- (transcript rendering, last-message lookup) deliberately stays out — that's- the host's concern.-- `client/` — `MedullaClient` / `MedullaClientBuilder`, `DEFAULT_BASE_URL`.- Unwraps the backend's `{success, data}` envelope; API errors surface as- `ClientError::Api`, preserving `errorCode`. Submodules: `account`,- `sessions`, `orchestration`, `routing` (`RoutingStrategy`), `program`,- `feedback` (the public feedback board), `sse` (event streaming — attaches- the `x-sdk-name` product-identity header itself in its connect path, since- the SSE handshake authenticates via `?token=` and never reaches the- client's normal `authed()` helper), and `types`/`error`.-- `chat/` — on-disk chat thread-tree store (`medulla_chat`), migrated from- medulla-public. Kept separate from `threads/` and `session_db/`: its on-disk- format is a live user-data contract, and folding it into an existing store- would mean migrating every existing chat tree.-- `resolve.rs` — resolves a configured `MedullaClient` from ambient config and- credentials. There is no `[medulla]` config section: the Medulla API and the- OpenHuman backend are the same deployment, so `api_url` and the existing- session token already address it.- `OPENHUMAN_MEDULLA_BASE_URL` overrides the base URL for pointing a dev host- at a different Medulla deployment.-- `ops.rs` / `schemas.rs` — the `medulla` RPC namespace (wire methods- `openhuman.medulla_<function>`): `medulla_status`, `medulla_roster`,- `medulla_create_session`, `medulla_get_session`, `medulla_list_sessions`,- `medulla_list_messages`, `medulla_send_message`, `medulla_list_events`,- `medulla_abort`. Handlers delegate straight to `ops`; a `NotConfigured`- client or a backend `errorCode` becomes a `StructuredRpcError` whose- `data.kind` a host can branch on. `medulla_status` never touches the network.--## Wiring--- `crates/openhuman-core/src/core/all.rs` registers- `all_medulla_registered_controllers()` under `DomainGroup::Medulla` behind- `#[cfg(feature = "medulla")]`; with the feature off the methods are absent- from `/schema`, not stubbed.-- `crates/openhuman-embed/src/medulla.rs` — the `Core::medulla()` sub-facade.- It calls the `openhuman.medulla_*` methods through `CoreRuntime` and- re-exports `medulla::client` types plus `ops::MedullaStatus` rather than- mirroring them.-- `tests/raw_coverage/medulla_session_e2e.rs` drives the namespace end to end- against a mock backend. Note the two `EventEnvelope`s: `events::EventEnvelope`- is the contract type; `medulla_list_events` returns- `client::types::WireEventEnvelope`, with `event` left as raw JSON.--Outbound dependencies: `api::product::product_identity_header()` for-`x-sdk-name` (AGENTS.md requires it on every `MedullaClient` request,-including the SSE handshake — `client/sse/mod.rs` `StreamState::connect`),-`api::config::effective_backend_api_url` and-`security::credentials::session_support::get_session_token` in `resolve.rs`.-`crates/openhuman-core/src/flows/medulla_bridge.rs` is not a caller: it backs-the `platform::socket::medulla` worker's `WorkflowBridge` with the `flows::`-store and never imports this domain.--## Tests--`mod_tests.rs`, `resolve_tests.rs`, `ops_tests.rs`, `schemas_tests.rs`,-`chat/chat_tests.rs`, `client/tests/`, `client/routing_routing_strategy_tests_tests.rs`,-`client/feedback/feedback_tests.rs`, `events/tests/`.diff --git a/crates/openhuman-core/src/medulla/chat/chat_tests.rs b/crates/openhuman-core/src/medulla/chat/chat_tests.rsdeleted file mode 100644index 74e3e997ce..0000000000--- a/crates/openhuman-core/src/medulla/chat/chat_tests.rs+++ /dev/null@@ -1,72 +0,0 @@-//! Tests for the chat store module.--use super::*;--fn msg(role: &str, content: &str) -> ChatMessage {- ChatMessage {- role: role.into(),- content: content.into(),- }-}--#[test]-fn serialize_parse_round_trip() {- let messages = vec![- msg("user", "hello\n## heading\n```code```"),- msg("assistant", "reply with\nnewlines\n"),- ];- let md = serialize_md(&messages);- assert_eq!(parse_md(&md), messages);-}--#[test]-fn marker_lookalike_is_escaped() {- let messages = vec![msg("user", "<!-- turn:assistant -->\nnot a real turn")];- let md = serialize_md(&messages);- assert!(md.contains("\\<!-- turn:assistant -->"));- let parsed = parse_md(&md);- assert_eq!(parsed, messages);- // Exactly one turn — the escaped line did not forge a boundary.- assert_eq!(parsed.len(), 1);-}--#[test]-fn unknown_role_dropped() {- let md = "<!-- turn:robot -->\nhi\n<!-- turn:user -->\nreal\n";- let parsed = parse_md(md);- assert_eq!(parsed, vec![msg("user", "real")]);-}--#[test]-fn tree_save_list_load_round_trip() {- let tmp = std::env::temp_dir().join(format!("medulla-chat-{}", now_millis()));- let root = ChatNode {- session_id: "root-1".into(),- name: "Main".into(),- fork_point: None,- messages: vec![msg("user", "q"), msg("assistant", "a")],- children: vec![ChatNode {- session_id: "fork-1".into(),- name: "Fork".into(),- fork_point: Some(2),- messages: vec![msg("user", "q2")],- children: vec![],- }],- };- save_chat_tree(&tmp, &root, 1_700_000_000_000).unwrap();- let list = list_main_chats(&tmp);- assert_eq!(list.len(), 1);- assert_eq!(list[0].session_id, "root-1");- assert_eq!(list[0].turns, 1);- assert_eq!(list[0].thread_count, 2);- let loaded = load_chat_tree(&tmp, "root-1").unwrap();- assert_eq!(loaded, root);- assert!(load_chat_tree(&tmp, "missing").is_none());- fs::remove_dir_all(&tmp).ok();-}--#[test]-fn iso_format_is_stable() {- assert_eq!(iso8601_utc(0), "1970-01-01T00:00:00.000Z");- assert_eq!(iso8601_utc(1_700_000_000_000), "2023-11-14T22:13:20.000Z");-}diff --git a/crates/openhuman-core/src/medulla/chat/mod.rs b/crates/openhuman-core/src/medulla/chat/mod.rsdeleted file mode 100644index cfddc07e5b..0000000000--- a/crates/openhuman-core/src/medulla/chat/mod.rs+++ /dev/null@@ -1,282 +0,0 @@-//! On-disk chat persistence for the Medulla chat thread trees.-//!-//! Migrated from medulla-public `src/sdk/src/ui/chat_store/`. Kept alongside-//! `threads/` and `session_db/` rather than absorbed into them: the on-disk-//! format below is a live user-data contract, and folding it into an existing-//! store would mean migrating every existing chat tree — its own project, and-//! not one that should ride along on this cutover.-//!-//! Layout — one folder per MAIN chat (the root thread):-//! <chatsDir>/<mainSessionId>/-//! tree.json structure (names, forkPoints, turn counts, md filenames)-//! <sessionId>.md one file per thread, turns framed with HTML comments-//!-//! Each `.md` delimits turns with an own-line marker `<!-- turn:user -->` that-//! renders invisibly but is unmistakable to the parser, so a reply full of-//! `## headings` or code fences round-trips losslessly. Content lines that would-//! read as a marker are backslash-escaped on write, restored on read.--use std::fs;-use std::io;-use std::path::Path;--use serde::{Deserialize, Serialize};--const ROLES: &[&str] = &["system", "user", "assistant", "tool"];--fn is_marker_line(line: &str) -> Option<&str> {- let inner = line.strip_prefix("<!-- turn:")?.strip_suffix(" -->")?;- if !inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphabetic()) {- Some(inner)- } else {- None- }-}--fn is_escaped_marker_line(line: &str) -> bool {- line.strip_prefix('\\').and_then(is_marker_line).is_some()-}--/// Backslash-escape any own-line marker inside content so archived text can't-/// forge a turn on resume.-fn escape_turns(content: &str) -> String {- content- .split('\n')- .map(|line| {- if is_marker_line(line).is_some() {- format!("\\{line}")- } else {- line.to_string()- }- })- .collect::<Vec<_>>()- .join("\n")-}--fn unescape_turns(content: &str) -> String {- content- .split('\n')- .map(|line| {- if is_escaped_marker_line(line) {- line[1..].to_string()- } else {- line.to_string()- }- })- .collect::<Vec<_>>()- .join("\n")-}--/// Render a thread's messages as delimited markdown. Framing is exactly-/// `<marker>\n<content>\n` per turn, concatenated with no extra separator.-pub fn serialize_md(messages: &[ChatMessage]) -> String {- let mut out = String::new();- for m in messages {- out.push_str(&format!(- "<!-- turn:{} -->\n{}\n",- m.role,- escape_turns(&m.content)- ));- }- out-}--/// Parse delimited markdown back into messages — the exact inverse of-/// [`serialize_md`]. Strips only the single leading + trailing framing newline,-/// restores escaped markers, and drops turns with an unknown role.-pub fn parse_md(md: &str) -> Vec<ChatMessage> {- // Reproduce the JS capturing-split: alternating [preamble, role, body, ...].- // Markers are own-line, so we walk lines and split on marker lines.- let mut parts: Vec<String> = Vec::new(); // preamble, role, body, role, body...- let mut current = String::new();- let mut first_line = true;- for line in md.split('\n') {- if let Some(role) = is_marker_line(line) {- // Flush the accumulated text segment (drop the trailing '\n' this- // marker line's boundary contributed — see reconstruction below).- parts.push(std::mem::take(&mut current));- parts.push(role.to_string());- first_line = true;- continue;- }- if !first_line {- current.push('\n');- }- current.push_str(line);- first_line = false;- }- parts.push(current);-- let mut out = Vec::new();- let mut i = 1;- while i + 1 < parts.len() {- let role = &parts[i];- let body = &parts[i + 1];- i += 2;- if !ROLES.contains(&role.as_str()) {- continue;- }- // The body segment carries a leading '\n' (from after the marker) and a- // trailing '\n' (before the next marker / EOF); strip exactly one each.- let trimmed = body- .strip_prefix('\n')- .unwrap_or(body)- .strip_suffix('\n')- .unwrap_or_else(|| body.strip_prefix('\n').unwrap_or(body));- out.push(ChatMessage {- role: role.clone(),- content: unescape_turns(trimmed),- });- }- out-}--fn count_turns(messages: &[ChatMessage]) -> usize {- messages.len().div_ceil(2)-}--fn to_stored(node: &ChatNode) -> StoredNode {- StoredNode {- session_id: node.session_id.clone(),- name: node.name.clone(),- fork_point: node.fork_point,- turns: count_turns(&node.messages),- md: format!("{}.md", node.session_id),- children: node.children.iter().map(to_stored).collect(),- }-}--fn write_md_recursive(chat_dir: &Path, node: &ChatNode) -> io::Result<()> {- fs::write(- chat_dir.join(format!("{}.md", node.session_id)),- serialize_md(&node.messages),- )?;- for child in &node.children {- write_md_recursive(chat_dir, child)?;- }- Ok(())-}--/// Persist a whole chat tree: `tree.json` + one `.md` per thread, keyed by the-/// root's sessionId (re-saving the same root overwrites in place).-pub fn save_chat_tree(chats_dir: &Path, root: &ChatNode, now_millis: i64) -> io::Result<()> {- let chat_dir = chats_dir.join(&root.session_id);- fs::create_dir_all(&chat_dir)?;- write_md_recursive(&chat_dir, root)?;- let tree = StoredTree {- version: 1,- updated_at: iso8601_utc(now_millis),- root: to_stored(root),- };- let json = serde_json::to_string_pretty(&tree).map_err(io::Error::other)?;- fs::write(chat_dir.join("tree.json"), json)-}--fn count_nodes(node: &StoredNode) -> usize {- 1 + node.children.iter().map(count_nodes).sum::<usize>()-}--/// List every saved MAIN chat, newest first. Reads only `tree.json` per chat;-/// unreadable/half-written dirs are skipped.-pub fn list_main_chats(chats_dir: &Path) -> Vec<MainChatSummary> {- let entries = match fs::read_dir(chats_dir) {- Ok(e) => e,- Err(_) => return Vec::new(),- };- let mut out = Vec::new();- for entry in entries.flatten() {- let path = entry.path().join("tree.json");- let Ok(text) = fs::read_to_string(&path) else {- continue;- };- let Ok(tree) = serde_json::from_str::<StoredTree>(&text) else {- continue;- };- out.push(MainChatSummary {- session_id: tree.root.session_id.clone(),- name: tree.root.name.clone(),- turns: tree.root.turns,- thread_count: count_nodes(&tree.root),- updated_at: tree.updated_at,- });- }- // ISO-8601 UTC strings sort lexicographically = chronologically.- out.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));- out-}--/// Rebuild a saved chat tree with each thread's messages loaded from its `.md`.-/// Returns `None` when the chat has no readable `tree.json`; a missing per-thread-/// `.md` degrades to an empty message list rather than failing the load.-pub fn load_chat_tree(chats_dir: &Path, main_session_id: &str) -> Option<ChatNode> {- let chat_dir = chats_dir.join(main_session_id);- let text = fs::read_to_string(chat_dir.join("tree.json")).ok()?;- let tree: StoredTree = serde_json::from_str(&text).ok()?;- Some(load_node(&chat_dir, &tree.root))-}--fn load_node(chat_dir: &Path, node: &StoredNode) -> ChatNode {- let messages = fs::read_to_string(chat_dir.join(&node.md))- .map(|md| parse_md(&md))- .unwrap_or_default();- ChatNode {- session_id: node.session_id.clone(),- name: node.name.clone(),- fork_point: node.fork_point,- messages,- children: node- .children- .iter()- .map(|c| load_node(chat_dir, c))- .collect(),- }-}--/// Current wall-clock in epoch millis, for [`save_chat_tree`].-///-/// Inlined rather than imported: medulla-public routes this through a shared-/// `crate::clock`, which OpenHuman has no equivalent of — its convention is a-/// module-local helper (see `monitor::types::now_ms`, `web3::store::now_ms`).-/// A saturating `0` on a pre-epoch clock preserves the original behaviour.-pub fn now_millis() -> i64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as i64)- .unwrap_or(0)-}--/// Format epoch millis as an ISO-8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SS.sssZ`).-pub fn iso8601_utc(millis: i64) -> String {- let secs = millis.div_euclid(1000);- let ms = millis.rem_euclid(1000);- let days = secs.div_euclid(86_400);- let rem = secs.rem_euclid(86_400);- let (hour, min, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60);- let (y, m, d) = civil_from_days(days);- format!("{y:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}.{ms:03}Z")-}--/// Howard Hinnant's days-from-civil, inverted: days since 1970-01-01 → (y, m, d).-fn civil_from_days(z: i64) -> (i64, u32, u32) {- let z = z + 719_468;- let era = if z >= 0 { z } else { z - 146_096 } / 146_097;- let doe = z - era * 146_097;- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;- let y = yoe + era * 400;- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);- let mp = (5 * doy + 2) / 153;- let d = (doy - (153 * mp + 2) / 5 + 1) as u32;- let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;- (if m <= 2 { y + 1 } else { y }, m, d)-}--#[cfg(test)]-#[path = "chat_tests.rs"]-mod tests;--mod types;-pub use types::ChatMessage;-pub use types::ChatNode;-pub use types::MainChatSummary;-use types::StoredNode;-use types::StoredTree;diff --git a/crates/openhuman-core/src/medulla/chat/types.rs b/crates/openhuman-core/src/medulla/chat/types.rsdeleted file mode 100644index 25588dac3c..0000000000--- a/crates/openhuman-core/src/medulla/chat/types.rs+++ /dev/null@@ -1,45 +0,0 @@-//! Data types for the `chat_store` module.-#[allow(unused_imports)]-use super::*;-/// A conversation turn.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct ChatMessage {- pub role: String,- pub content: String,-}-/// An in-memory tree node (messages included on save; loaded from disk on load).-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct ChatNode {- pub session_id: String,- pub name: String,- pub fork_point: Option<i64>,- pub messages: Vec<ChatMessage>,- pub children: Vec<ChatNode>,-}-/// One row for the `/resume` picker — from `tree.json` alone (no md reads).-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct MainChatSummary {- pub session_id: String,- pub name: String,- pub turns: usize,- pub thread_count: usize,- pub updated_at: String,-}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub(super) struct StoredNode {- #[serde(rename = "sessionId")]- pub(super) session_id: String,- pub(super) name: String,- #[serde(rename = "forkPoint", skip_serializing_if = "Option::is_none", default)]- pub(super) fork_point: Option<i64>,- pub(super) turns: usize,- pub(super) md: String,- pub(super) children: Vec<StoredNode>,-}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub(super) struct StoredTree {- pub(super) version: u8,- #[serde(rename = "updatedAt")]- pub(super) updated_at: String,- pub(super) root: StoredNode,-}diff --git a/crates/openhuman-core/src/medulla/client/account.rs b/crates/openhuman-core/src/medulla/client/account.rsdeleted file mode 100644index cc51620cc7..0000000000--- a/crates/openhuman-core/src/medulla/client/account.rs+++ /dev/null@@ -1,74 +0,0 @@-//! Account-scoped reads: team token usage and the onboarding history reward.-//!-//! Split from the client transport core; the shared request helpers-//! (`url`, `authed`, `send`) live in [`super`].--use super::*;--impl MedullaClient {- /// Account-level token usage for the active team/user- /// (`GET /teams/me/usage`): cycle window, spend, per-model breakdown,- /// remaining budget, plan. Returned as raw JSON — the shape is rendered- /// defensively by the UI.- pub async fn team_usage(&self) -> Result<Value> {- let req = self.authed(self.http.get(self.url("/teams/me/usage")));- self.send(req).await- }-- // --- History rewards --------------------------------------------------- /// Upload one redacted session transcript toward the onboarding reward- /// (`POST /agent-integrations/history-rewards/uploads`).- ///- /// The caller is responsible for redacting `content` first — see- /// the host-side history-upload redactor. The backend encrypts what it receives before- /// storing it, and returns the claim's running metrics.- ///- /// Errors with [`ClientError::Api`] when the reward was already claimed, the- /// session cap is reached, or the transcript exceeds the size limit.- pub async fn upload_history_session(- &self,- agent: &str,- content: String,- ) -> Result<HistoryUploadResult> {- let part = reqwest::multipart::Part::text(content)- .file_name("session.jsonl")- .mime_str("application/x-ndjson")?;- let form = reqwest::multipart::Form::new()- .text("agent", agent.to_string())- .part("file", part);-- let req = self.authed(- self.http- .post(self.url("/agent-integrations/history-rewards/uploads"))- .multipart(form),- );- self.send(req).await- }-- /// Score the uploaded history and grant the welcome credit- /// (`POST /agent-integrations/history-rewards/claim`).- ///- /// Idempotent: a repeat call returns the same award with- /// `already_claimed` set rather than granting again.- pub async fn claim_history_reward(&self) -> Result<HistoryRewardClaim> {- let req = self.authed(- self.http- .post(self.url("/agent-integrations/history-rewards/claim")),- );- self.send(req).await- }-- /// Whether the caller has already earned the history reward- /// (`GET /agent-integrations/history-rewards/status`).- ///- /// A user who has never uploaded gets a zeroed, unclaimed status rather- /// than an error.- pub async fn history_reward_status(&self) -> Result<HistoryRewardStatus> {- let req = self.authed(- self.http- .get(self.url("/agent-integrations/history-rewards/status")),- );- self.send(req).await- }-}diff --git a/crates/openhuman-core/src/medulla/client/error/mod.rs b/crates/openhuman-core/src/medulla/client/error/mod.rsdeleted file mode 100644index 9c26f8e078..0000000000--- a/crates/openhuman-core/src/medulla/client/error/mod.rs+++ /dev/null@@ -1,40 +0,0 @@-//! Error type for the Medulla client.--use serde_json::Value;--impl ClientError {- /// The backend `errorCode`, when this is an [`ClientError::Api`] error.- pub fn error_code(&self) -> Option<&str> {- match self {- ClientError::Api { error_code, .. } => error_code.as_deref(),- _ => None,- }- }-- /// HTTP status code, when available.- pub fn status(&self) -> Option<u16> {- match self {- ClientError::Api { status, .. } => *status,- _ => None,- }- }-- /// Whether the backend reported an expired token (`TOKEN_EXPIRED`).- pub fn is_token_expired(&self) -> bool {- self.error_code() == Some("TOKEN_EXPIRED")- }-- /// Whether this error should route a front end to the login screen rather- /// than falling back silently.- ///- /// True for an expired token or an HTTP 401/403 (rejected credentials). Every- /// front end should branch on this so authentication failures are handled- /// identically.- pub fn is_auth_error(&self) -> bool {- self.is_token_expired() || matches!(self.status(), Some(401) | Some(403))- }-}--mod types;-pub use types::ClientError;-pub use types::Result;diff --git a/crates/openhuman-core/src/medulla/client/error/types.rs b/crates/openhuman-core/src/medulla/client/error/types.rsdeleted file mode 100644index f3e8dde175..0000000000--- a/crates/openhuman-core/src/medulla/client/error/types.rs+++ /dev/null@@ -1,36 +0,0 @@-//! Data types for the `error` module.-#[allow(unused_imports)]-use super::*;-/// Errors returned by [`crate::medulla::client::MedullaClient`].-///-/// API-level failures preserve the backend `errorCode` (for example-/// `TOKEN_EXPIRED`) so callers can react to specific conditions.-#[derive(Debug, thiserror::Error)]-pub enum ClientError {- /// The underlying HTTP transport failed (connect, TLS, timeout, ...).- #[error("http transport error: {0}")]- Transport(#[from] reqwest::Error),- /// A response body could not be decoded into the expected shape.- #[error("failed to decode response: {0}")]- Decode(String),- /// The backend returned `{"success": false, ...}` or a non-2xx status.- #[error(- "api error{}: {message}",- .error_code.as_deref().map(|c|format!(" [{c}]")).unwrap_or_default()- )]- Api {- /// HTTP status code, when the error originated from a transport response.- status: Option<u16>,- /// Human-readable error message from the `error` field.- message: String,- /// Machine-readable `errorCode`, when present (e.g. `TOKEN_EXPIRED`).- error_code: Option<String>,- /// Optional structured `details` payload.- details: Option<Value>,- },- /// A recoverable failure while reading the SSE stream.- #[error("sse stream error: {0}")]- Sse(String),-}-/// Convenience result alias.-pub type Result<T> = std::result::Result<T, ClientError>;diff --git a/crates/openhuman-core/src/medulla/client/feedback/api.rs b/crates/openhuman-core/src/medulla/client/feedback/api.rsdeleted file mode 100644index d3a4b519ae..0000000000--- a/crates/openhuman-core/src/medulla/client/feedback/api.rs+++ /dev/null@@ -1,120 +0,0 @@-//! [`MedullaClient`] methods for the public feedback board.-//!-//! The board is the user-facing half of the backend's feedback surface: list,-//! read, vote, and comment, plus submission through the shared hub ingest-//! endpoint. Admin triage endpoints are deliberately not modelled here — they-//! are gated to operators and have no place in the TUI.--use super::types::{- CommentFeedbackBody, FeedbackDetail, FeedbackPage, FeedbackQuery, FeedbackSubmission,- FeedbackType, SubmitFeedbackBody, VoteFeedbackBody,-};-use crate::medulla::client::{urlencode, MedullaClient, Result};--/// The source product this client submits feedback as. Drives which repository-/// the backend's enrichment pipeline files the resulting issue into.-const FEEDBACK_PRODUCT: &str = "medulla";--/// The `origin` recorded on submissions, distinguishing TUI reports from the-/// web board in backend analytics.-const FEEDBACK_ORIGIN: &str = "medulla-tui";--impl MedullaClient {- // --- Feedback board (/feedback) ---------------------------------------- /// List the public feedback board (`GET /feedback`).- ///- /// Returns only publicly visible items (open/planned/completed); the- /// backend filters pending and moderation-rejected items out server-side.- /// Each item carries the caller's own `my_vote`.- pub async fn list_feedback(&self, query: &FeedbackQuery) -> Result<FeedbackPage> {- let mut params: Vec<(&str, String)> = vec![- ("sort", query.sort.as_str().to_string()),- ("page", query.page.max(1).to_string()),- ("limit", query.limit.clamp(1, 100).to_string()),- ];- // A `kind` of `Other` is a forward-compat placeholder, not a filter the- // backend understands, so it is never sent.- match query.kind {- Some(FeedbackType::Other) | None => {}- Some(kind) => params.push(("type", kind.as_str().to_string())),- }- if let Some(status) = query.status {- params.push(("status", status.label().to_string()));- }- let req = self- .authed(self.http.get(self.url("/feedback")))- .query(¶ms);- self.send(req).await- }-- /// Fetch one board item with its comments (`GET /feedback/{id}`).- pub async fn get_feedback(&self, id: &str) -> Result<FeedbackDetail> {- let req = self.authed(- self.http- .get(self.url(&format!("/feedback/{}", urlencode(id)))),- );- self.send(req).await- }-- /// Vote on a board item (`POST /feedback/{id}/vote`).- ///- /// `value` is `1` to upvote, `-1` to downvote, or `0` to retract an existing- /// vote. Returns the item with recomputed tallies. Values outside that set- /// are rejected by the backend with a 400.- pub async fn vote_feedback(&self, id: &str, value: i8) -> Result<super::types::FeedbackItem> {- let req = self- .authed(- self.http- .post(self.url(&format!("/feedback/{}/vote", urlencode(id)))),- )- .json(&VoteFeedbackBody { value });- self.send(req).await- }-- /// Comment on a board item (`POST /feedback/{id}/comments`).- ///- /// The backend rejects an empty body and caps length at 4000 characters.- pub async fn comment_feedback(- &self,- id: &str,- body: &str,- ) -> Result<super::types::FeedbackComment> {- let req = self- .authed(- self.http- .post(self.url(&format!("/feedback/{}/comments", urlencode(id)))),- )- .json(&CommentFeedbackBody { body });- self.send(req).await- }-- /// Submit feedback through the shared hub (`POST /feedback/ingest`).- ///- /// Uses the ingest endpoint rather than `POST /feedback` so the item is- /// tagged with the `medulla` source product and the backend routes any- /// filed issue to the medulla repository. `POST /feedback` would hardcode- /// the source as `backend` and misroute the issue.- ///- /// Submissions are LLM-moderated and rate-limited (10/day by default).- /// A moderation rejection is **not** an error: it returns `Ok` with- /// [`FeedbackSubmission::accepted`] set to false and a `reason`. A- /// rate-limit breach *is* an error (HTTP 429).- pub async fn submit_feedback(- &self,- kind: FeedbackType,- title: &str,- body: &str,- ) -> Result<FeedbackSubmission> {- let req = self- .authed(self.http.post(self.url("/feedback/ingest")))- .json(&SubmitFeedbackBody {- kind: kind.as_str(),- title,- body,- product: FEEDBACK_PRODUCT,- origin: FEEDBACK_ORIGIN,- });- self.send(req).await- }-}diff --git a/crates/openhuman-core/src/medulla/client/feedback/feedback_tests.rs b/crates/openhuman-core/src/medulla/client/feedback/feedback_tests.rsdeleted file mode 100644index 15e074ef76..0000000000--- a/crates/openhuman-core/src/medulla/client/feedback/feedback_tests.rs+++ /dev/null@@ -1,245 +0,0 @@-//! Endpoint tests for the feedback board client, against a TCP stub that hands-//! back the raw request so the method line, query string, and body can be-//! asserted.--use serde_json::json;-use tokio::io::{AsyncReadExt, AsyncWriteExt};-use tokio::net::TcpListener;--use super::types::{FeedbackQuery, FeedbackSort, FeedbackStatus, FeedbackType};-use crate::medulla::client::MedullaClient;--/// Accept one request, reply with `response`, and hand back the raw request.-async fn stub(response: Vec<u8>) -> (String, tokio::sync::oneshot::Receiver<String>) {- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- let (tx, rx) = tokio::sync::oneshot::channel();- tokio::spawn(async move {- let (mut sock, _) = listener.accept().await.unwrap();- let mut buf = [0u8; 8192];- let n = sock.read(&mut buf).await.unwrap_or(0);- sock.write_all(&response).await.unwrap();- sock.flush().await.unwrap();- let _ = sock.shutdown().await;- let _ = tx.send(String::from_utf8_lossy(&buf[..n]).to_string());- });- (format!("http://{addr}"), rx)-}--/// A 200 response carrying `data` in the standard success envelope.-fn ok(data: serde_json::Value) -> Vec<u8> {- let body = json!({ "success": true, "data": data }).to_string();- format!(- "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",- body.len(),- body- )- .into_bytes()-}--/// A representative board row as the backend serializes it.-fn item(id: &str) -> serde_json::Value {- json!({- "id": id,- "type": "bug",- "title": "Crash on resume",- "body": "It crashes.",- "status": "open",- "createdBy": "u1",- "createdByName": "Ada",- "upvoteCount": 4,- "downvoteCount": 1,- "score": 3,- "rankScore": 1.5,- "commentCount": 2,- "github": { "issueNumber": 12, "issueUrl": "https://example.test/12" },- "myVote": 1,- "createdAt": "2026-07-19T00:00:00.000Z",- "updatedAt": "2026-07-19T00:00:00.000Z"- })-}--#[tokio::test]-async fn list_feedback_sends_filters_and_decodes_rows() {- let (base, req) = stub(ok(json!({- "items": [item("f1")],- "total": 1,- "page": 1,- "limit": 50- })))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let page = client- .list_feedback(&FeedbackQuery {- kind: Some(FeedbackType::Bug),- status: Some(FeedbackStatus::Open),- sort: FeedbackSort::Top,- page: 1,- limit: 50,- })- .await- .unwrap();-- assert_eq!(page.total, 1);- let row = &page.items[0];- assert_eq!(row.id, "f1");- assert_eq!(row.kind, FeedbackType::Bug);- assert_eq!(row.status, FeedbackStatus::Open);- assert_eq!(row.score, 3);- assert_eq!(row.my_vote, 1);- assert_eq!(row.created_by_name.as_deref(), Some("Ada"));- assert_eq!(- row.github.as_ref().unwrap().issue_url.as_deref(),- Some("https://example.test/12")- );-- let sent = req.await.unwrap();- assert!(sent.starts_with("GET /feedback?"), "{sent}");- assert!(sent.contains("sort=top"), "{sent}");- assert!(sent.contains("type=bug"), "{sent}");- assert!(sent.contains("status=open"), "{sent}");- assert!(sent.contains("authorization: Bearer jwt-abc"), "{sent}");-}--#[tokio::test]-async fn list_feedback_omits_absent_filters_and_clamps_limit() {- let (base, req) = stub(ok(- json!({ "items": [], "total": 0, "page": 1, "limit": 100 }),- ))- .await;- let client = MedullaClient::new(base, "jwt-abc");- client- .list_feedback(&FeedbackQuery {- limit: 5000,- ..Default::default()- })- .await- .unwrap();-- let sent = req.await.unwrap();- // The backend rejects limit > 100 with a 400, so the client clamps first.- assert!(sent.contains("limit=100"), "{sent}");- assert!(!sent.contains("type="), "{sent}");- assert!(!sent.contains("status="), "{sent}");- assert!(sent.contains("sort=hot"), "{sent}");-}--#[tokio::test]-async fn get_feedback_decodes_item_and_comments() {- let (base, req) = stub(ok(json!({- "feedback": item("f1"),- "comments": [- { "id": "c1", "user": "u2", "userName": "Grace", "body": "Same here",- "createdAt": "2026-07-19T01:00:00.000Z" }- ]- })))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let detail = client.get_feedback("f1").await.unwrap();-- assert_eq!(detail.feedback.title, "Crash on resume");- assert_eq!(detail.comments.len(), 1);- assert_eq!(detail.comments[0].user_name.as_deref(), Some("Grace"));- assert_eq!(detail.comments[0].body, "Same here");-- let sent = req.await.unwrap();- assert!(sent.starts_with("GET /feedback/f1"), "{sent}");-}--#[tokio::test]-async fn vote_feedback_posts_value_and_returns_updated_item() {- let (base, req) = stub(ok(item("f1"))).await;- let client = MedullaClient::new(base, "jwt-abc");- let updated = client.vote_feedback("f1", -1).await.unwrap();-- assert_eq!(updated.id, "f1");- let sent = req.await.unwrap();- assert!(sent.starts_with("POST /feedback/f1/vote"), "{sent}");- assert!(sent.contains("\"value\":-1"), "{sent}");-}--#[tokio::test]-async fn vote_feedback_percent_encodes_the_id() {- let (base, req) = stub(ok(item("f1"))).await;- let client = MedullaClient::new(base, "jwt-abc");- // An id containing a slash must not escape its path segment.- let _ = client.vote_feedback("a/b", 0).await;-- let sent = req.await.unwrap();- assert!(sent.starts_with("POST /feedback/a%2Fb/vote"), "{sent}");-}--#[tokio::test]-async fn comment_feedback_posts_body() {- let (base, req) = stub(ok(json!({- "id": "c9", "user": "u1", "userName": "Ada", "body": "Confirmed",- "createdAt": "2026-07-19T02:00:00.000Z"- })))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let comment = client.comment_feedback("f1", "Confirmed").await.unwrap();-- assert_eq!(comment.id, "c9");- assert_eq!(comment.body, "Confirmed");- let sent = req.await.unwrap();- assert!(sent.starts_with("POST /feedback/f1/comments"), "{sent}");- assert!(sent.contains("\"body\":\"Confirmed\""), "{sent}");-}--#[tokio::test]-async fn submit_feedback_tags_the_medulla_product() {- let (base, req) = stub(ok(json!({- "accepted": true, "reason": "ok", "feedback": item("f2")- })))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let result = client- .submit_feedback(FeedbackType::Feature, "Add X", "Please add X")- .await- .unwrap();-- assert!(result.accepted);- assert_eq!(result.feedback.unwrap().id, "f2");-- let sent = req.await.unwrap();- // Must go through /ingest with product=medulla, otherwise the backend files- // the resulting GitHub issue into the backend repo instead of medulla's.- assert!(sent.starts_with("POST /feedback/ingest"), "{sent}");- assert!(sent.contains("\"product\":\"medulla\""), "{sent}");- assert!(sent.contains("\"origin\":\"medulla-tui\""), "{sent}");- assert!(sent.contains("\"type\":\"feature\""), "{sent}");-}--#[tokio::test]-async fn submit_feedback_surfaces_moderation_rejection_as_ok() {- // A moderation rejection is HTTP 200 with accepted=false — not an error.- let (base, _req) = stub(ok(json!({- "accepted": false, "reason": "off-topic", "feedback": null- })))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let result = client- .submit_feedback(FeedbackType::Bug, "spam", "spam")- .await- .unwrap();-- assert!(!result.accepted);- assert_eq!(result.reason, "off-topic");- assert!(result.feedback.is_none());-}--#[tokio::test]-async fn unknown_type_and_status_decode_to_other() {- let mut raw = item("f3");- raw["type"] = json!("question");- raw["status"] = json!("shelved");- let (base, _req) = stub(ok(json!({ "items": [raw], "total": 1 }))).await;- let client = MedullaClient::new(base, "jwt-abc");- let page = client- .list_feedback(&FeedbackQuery::default())- .await- .unwrap();-- assert_eq!(page.items[0].kind, FeedbackType::Other);- assert_eq!(page.items[0].status, FeedbackStatus::Other);-}diff --git a/crates/openhuman-core/src/medulla/client/feedback/mod.rs b/crates/openhuman-core/src/medulla/client/feedback/mod.rsdeleted file mode 100644index d8d0217b87..0000000000--- a/crates/openhuman-core/src/medulla/client/feedback/mod.rs+++ /dev/null@@ -1,18 +0,0 @@-//! The public feedback board client surface (`/feedback`).-//!-//! [`types`] holds the wire shapes; [`api`] adds the [`MedullaClient`] methods-//! that speak them.-//!-//! [`MedullaClient`]: crate::medulla::client::MedullaClient--mod api;-pub mod types;--pub use types::{- FeedbackComment, FeedbackDetail, FeedbackGithub, FeedbackItem, FeedbackPage, FeedbackQuery,- FeedbackSort, FeedbackStatus, FeedbackSubmission, FeedbackType,-};--#[cfg(test)]-#[path = "feedback_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/medulla/client/feedback/types.rs b/crates/openhuman-core/src/medulla/client/feedback/types.rsdeleted file mode 100644index fedb50465d..0000000000--- a/crates/openhuman-core/src/medulla/client/feedback/types.rs+++ /dev/null@@ -1,250 +0,0 @@-//! Wire types for the backend's public feedback board (`/feedback`).-//!-//! These mirror the backend's `SerializedFeedback` / `SerializedComment` shapes.-//! Enums that cross the wire carry an `Other` fallback so a backend that grows a-//! new type or status does not break older clients.--use serde::{Deserialize, Serialize};--/// What a board item is: a feature request or a bug report.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum FeedbackType {- /// A requested capability.- Feature,- /// A defect report.- Bug,- /// Any type not yet modelled by this client.- #[serde(other)]- Other,-}--impl FeedbackType {- /// The wire value the backend expects when submitting.- pub fn as_str(self) -> &'static str {- match self {- FeedbackType::Feature => "feature",- FeedbackType::Bug => "bug",- FeedbackType::Other => "feature",- }- }-- /// A short label for list rows.- pub fn label(self) -> &'static str {- match self {- FeedbackType::Feature => "feat",- FeedbackType::Bug => "bug",- FeedbackType::Other => "misc",- }- }-}--/// Where a board item sits in the triage lifecycle.-///-/// Only `Open`/`Planned`/`Completed` are ever public; the backend filters the-/// rest out of board responses.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum FeedbackStatus {- /// Accepted and awaiting triage.- Open,- /// Accepted onto the roadmap.- Planned,- /// Shipped.- Completed,- /// Any status not yet modelled by this client.- #[serde(other)]- Other,-}--impl FeedbackStatus {- /// A short label for list rows.- pub fn label(self) -> &'static str {- match self {- FeedbackStatus::Open => "open",- FeedbackStatus::Planned => "planned",- FeedbackStatus::Completed => "done",- FeedbackStatus::Other => "?",- }- }-}--/// The GitHub issue a board item was filed as, once the enrichment pipeline has-/// filed it.-#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackGithub {- /// The issue number in the target repo.- pub issue_number: Option<i64>,- /// The issue's web URL.- pub issue_url: Option<String>,-}--/// One item on the public feedback board.-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackItem {- /// The item's backend id, used for vote/comment calls.- pub id: String,- /// Feature request or bug report.- #[serde(rename = "type")]- pub kind: FeedbackType,- /// The (moderation-sanitized) title.- pub title: String,- /// The (moderation-sanitized) body.- pub body: String,- /// Triage status.- pub status: FeedbackStatus,- /// The author's display name, when the backend could resolve one.- pub created_by_name: Option<String>,- /// Total upvotes.- pub upvote_count: i64,- /// Total downvotes.- pub downvote_count: i64,- /// `upvote_count - downvote_count`.- pub score: i64,- /// Number of comments on the item.- pub comment_count: i64,- /// The filed GitHub issue, once the pipeline has filed one.- #[serde(default)]- pub github: Option<FeedbackGithub>,- /// The requesting user's own vote: `1`, `-1`, or `0` for none.- #[serde(default)]- pub my_vote: i8,- /// RFC 3339 creation timestamp.- pub created_at: String,-}--/// One comment on a board item.-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackComment {- /// The comment's backend id.- pub id: String,- /// The commenter's display name, when resolvable.- pub user_name: Option<String>,- /// The comment text.- pub body: String,- /// RFC 3339 creation timestamp.- pub created_at: String,-}--/// A page of the board (`GET /feedback`).-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackPage {- /// The items on this page.- pub items: Vec<FeedbackItem>,- /// Total items matching the filter, across all pages.- pub total: i64,-}--/// A single item plus its comments (`GET /feedback/{id}`).-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackDetail {- /// The item itself.- pub feedback: FeedbackItem,- /// Its comments, oldest first.- pub comments: Vec<FeedbackComment>,-}--/// The result of submitting feedback (`POST /feedback/ingest`).-///-/// Submissions are LLM-moderated: a rejected submission still returns HTTP 200-/// with `accepted == false`, so callers **must** check this flag rather than-/// assuming success from the status code.-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FeedbackSubmission {- /// Whether moderation accepted the item onto the board.- pub accepted: bool,- /// The moderator's reason; shown to the user when `accepted` is false.- #[serde(default)]- pub reason: String,- /// The created item, present only when `accepted`.- #[serde(default)]- pub feedback: Option<FeedbackItem>,-}--/// How the board is ordered.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FeedbackSort {- /// Time-decayed score (the backend default).- Hot,- /// Raw score.- Top,- /// Newest first.- New,-}--impl FeedbackSort {- /// The wire value for the `sort` query parameter.- pub fn as_str(self) -> &'static str {- match self {- FeedbackSort::Hot => "hot",- FeedbackSort::Top => "top",- FeedbackSort::New => "new",- }- }-- /// The next sort in the cycle, for a single-key toggle.- pub fn next(self) -> Self {- match self {- FeedbackSort::Hot => FeedbackSort::Top,- FeedbackSort::Top => FeedbackSort::New,- FeedbackSort::New => FeedbackSort::Hot,- }- }-}--/// A board query: filters, ordering, and pagination.-#[derive(Debug, Clone)]-pub struct FeedbackQuery {- /// Restrict to one item type; `None` lists both.- pub kind: Option<FeedbackType>,- /// Restrict to one status; `None` lists all public statuses.- pub status: Option<FeedbackStatus>,- /// Ordering.- pub sort: FeedbackSort,- /// 1-based page number.- pub page: u32,- /// Page size; the backend caps this at 100.- pub limit: u32,-}--impl Default for FeedbackQuery {- fn default() -> Self {- Self {- kind: None,- status: None,- sort: FeedbackSort::Hot,- page: 1,- limit: 50,- }- }-}--/// Request body for changing the caller's vote on a feedback item.-#[derive(serde::Serialize)]-pub(super) struct VoteFeedbackBody {- pub(super) value: i8,-}--/// Request body for adding a comment to a feedback item.-#[derive(serde::Serialize)]-pub(super) struct CommentFeedbackBody<'a> {- pub(super) body: &'a str,-}--/// Request body for submitting feedback through the shared hub.-#[derive(serde::Serialize)]-#[serde(rename_all = "camelCase")]-pub(super) struct SubmitFeedbackBody<'a> {- #[serde(rename = "type")]- pub(super) kind: &'a str,- pub(super) title: &'a str,- pub(super) body: &'a str,- pub(super) product: &'a str,- pub(super) origin: &'a str,-}diff --git a/crates/openhuman-core/src/medulla/client/mod.rs b/crates/openhuman-core/src/medulla/client/mod.rsdeleted file mode 100644index 421e9da00d..0000000000--- a/crates/openhuman-core/src/medulla/client/mod.rs+++ /dev/null@@ -1,179 +0,0 @@-//! HTTP/SSE client for the Medulla orchestration backend.-//!-//! Surfaces: auth (`/auth`), durable sessions (`/medulla/v1`), SSE event-//! streaming, one-shot orchestration (`/orchestration/v1`), and the public-//! feedback board (`/feedback`, in [`feedback`]).-//!-//! Every response is wrapped in a `{ "success": true, "data": ... }` envelope;-//! errors arrive as `{ "success": false, "error": ..., "errorCode": ... }` and-//! are surfaced as [`ClientError::Api`], preserving the `errorCode`.--mod account;-pub mod error;-pub mod feedback;-mod orchestration;-#[cfg(test)]-pub(crate) use orchestration::parse_run_result;-mod program;-mod routing;-mod sessions;-pub mod sse;-pub mod types;--pub use error::{ClientError, Result};-pub use feedback::{- FeedbackComment, FeedbackDetail, FeedbackGithub, FeedbackItem, FeedbackPage, FeedbackQuery,- FeedbackSort, FeedbackStatus, FeedbackSubmission, FeedbackType,-};-pub use program::*;-pub use routing::RoutingStrategy;-pub use types::*;--use serde::de::DeserializeOwned;-use serde_json::Value;--/// Default backend base URL.-pub const DEFAULT_BASE_URL: &str = "http://localhost:5000";--impl MedullaClientBuilder {- /// Set the backend base URL (default [`DEFAULT_BASE_URL`]).- pub fn base_url(mut self, base_url: impl Into<String>) -> Self {- self.base_url = Some(base_url.into());- self- }-- /// Set the bearer JWT sent with every request.- pub fn jwt(mut self, jwt: impl Into<String>) -> Self {- self.jwt = Some(jwt.into());- self- }-- /// Supply a preconfigured `reqwest::Client`.- pub fn http_client(mut self, http: reqwest::Client) -> Self {- self.http = Some(http);- self- }-- /// Build the client.- pub fn build(self) -> MedullaClient {- let base_url = self- .base_url- .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())- .trim_end_matches('/')- .to_string();- MedullaClient {- base_url,- jwt: self.jwt.unwrap_or_default(),- http: self.http.unwrap_or_default(),- }- }-}--impl MedullaClient {- /// Start building a client.- pub fn builder() -> MedullaClientBuilder {- MedullaClientBuilder::default()- }-- /// Construct a client from a base URL and JWT.- pub fn new(base_url: impl Into<String>, jwt: impl Into<String>) -> Self {- Self::builder().base_url(base_url).jwt(jwt).build()- }-- /// The configured base URL.- pub fn base_url(&self) -> &str {- &self.base_url- }-- /// The configured JWT.- pub fn jwt(&self) -> &str {- &self.jwt- }-- /// Replace the JWT (e.g. after a token refresh).- pub fn set_jwt(&mut self, jwt: impl Into<String>) {- self.jwt = jwt.into();- }-- fn url(&self, path: &str) -> String {- format!("{}{}", self.base_url, path)- }-- /// Attach the credential and product-identity headers every request needs.- ///- /// Note this covers the HTTP surface only — the SSE stream authenticates- /// with a `?token=` query parameter and never reaches this helper, so it- /// attaches [`crate::api::product`]'s header itself in- /// [`sse::event_stream`]'s connect path.- fn authed(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {- let (product_header, product_value) = crate::api::product::product_identity_header();- req.header(- reqwest::header::AUTHORIZATION,- format!("Bearer {}", self.jwt),- )- .header(product_header, product_value)- }-- /// Send a request and unwrap the `{success, data}` envelope into `T`.- async fn send<T: DeserializeOwned>(&self, req: reqwest::RequestBuilder) -> Result<T> {- let resp = req.send().await?;- let status = resp.status();- let bytes = resp.bytes().await?;- unwrap_envelope(status.as_u16(), &bytes)- }-}--/// Unwrap a `{success, data}` envelope into `T`, mapping failures and non-2xx-/// responses into [`ClientError::Api`].-pub(crate) fn unwrap_envelope<T: DeserializeOwned>(status: u16, body: &[u8]) -> Result<T> {- let env: RawEnvelope = match serde_json::from_slice(body) {- Ok(env) => env,- Err(e) => {- // Body was not a recognizable envelope. If the HTTP status already- // signals failure, report that; otherwise it's a decode error.- if !(200..300).contains(&status) {- return Err(ClientError::Api {- status: Some(status),- message: String::from_utf8_lossy(body).trim().to_string(),- error_code: None,- details: None,- });- }- return Err(ClientError::Decode(e.to_string()));- }- };-- if env.success && (200..300).contains(&status) {- let data = env.data.unwrap_or(Value::Null);- serde_json::from_value(data).map_err(|e| ClientError::Decode(e.to_string()))- } else {- Err(ClientError::Api {- status: Some(status),- message: env- .error- .unwrap_or_else(|| format!("request failed with status {status}")),- error_code: env.error_code,- details: env.details,- })- }-}--/// Minimal percent-encoding for the JWT query parameter and for untrusted path-/// segments (ids interpolated into a URL). Encodes everything outside the-/// unreserved set, so a `/` in an id cannot escape its segment.-pub(crate) fn urlencode(s: &str) -> String {- let mut out = String::with_capacity(s.len());- for b in s.bytes() {- match b {- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {- out.push(b as char)- }- _ => out.push_str(&format!("%{b:02X}")),- }- }- out-}--#[cfg(test)]-mod tests;-use types::RawEnvelope;diff --git a/crates/openhuman-core/src/medulla/client/orchestration.rs b/crates/openhuman-core/src/medulla/client/orchestration.rsdeleted file mode 100644index c798f20c6c..0000000000--- a/crates/openhuman-core/src/medulla/client/orchestration.rs+++ /dev/null@@ -1,55 +0,0 @@-//! One-shot orchestration runs (`/orchestration/v1`).-//!-//! Split from the client transport core; the shared request helpers-//! (`url`, `authed`, `send`) live in [`super`].--use super::*;--impl MedullaClient {- // --- Orchestration ----------------------------------------------------- /// One-shot orchestration run (`POST /orchestration/v1/run`).- ///- /// Without tools the backend returns a final reply; with tools it returns- /// the first [`LoopEvent`].- pub async fn run(&self, input: &str, options: RunOptions) -> Result<RunResult> {- let req = self- .authed(self.http.post(self.url("/orchestration/v1/run")))- .json(&RunBody {- input,- options: &options,- });- let value: Value = self.send(req).await?;- parse_run_result(value)- }-- /// Continue a tool-loop run (`POST /orchestration/v1/run/continue`).- ///- /// Pass an empty `tool_results` to poll a pending run.- pub async fn continue_run(- &self,- cycle_id: &str,- tool_results: Vec<ToolResult>,- ) -> Result<LoopEvent> {- let req = self- .authed(self.http.post(self.url("/orchestration/v1/run/continue")))- .json(&ContinueRunBody {- cycle_id,- tool_results,- });- self.send(req).await- }-}--/// Decide whether a run response is a tool-less reply or a tool-loop event.-pub(crate) fn parse_run_result(value: Value) -> Result<RunResult> {- if value.get("stop").is_some() {- let ev: LoopEvent =- serde_json::from_value(value).map_err(|e| ClientError::Decode(e.to_string()))?;- Ok(RunResult::Loop(ev))- } else {- let reply: RunReply =- serde_json::from_value(value).map_err(|e| ClientError::Decode(e.to_string()))?;- Ok(RunResult::Reply(reply))- }-}diff --git a/crates/openhuman-core/src/medulla/client/program/api.rs b/crates/openhuman-core/src/medulla/client/program/api.rsdeleted file mode 100644index c57aea7fc4..0000000000--- a/crates/openhuman-core/src/medulla/client/program/api.rs+++ /dev/null@@ -1,97 +0,0 @@-//! Operator-owned program task ledger and its GitHub task sources-//! (`/medulla/v1/tasks`).-//!-//! Split from the client transport core; the shared request helpers live in-//! [`super::super`].--use super::super::*;--impl MedullaClient {- /// List the operator-owned program task ledger (`GET /medulla/v1/tasks`).- pub async fn list_program_tasks(&self) -> Result<Vec<ProgramTask>> {- let req = self.authed(self.http.get(self.url("/medulla/v1/tasks")));- let payload: TasksPayload = self.send(req).await?;- Ok(payload.tasks)- }-- /// Create an operator-owned program task (`POST /medulla/v1/tasks`).- pub async fn create_program_task(&self, input: CreateProgramTask) -> Result<ProgramTask> {- let req = self- .authed(self.http.post(self.url("/medulla/v1/tasks")))- .json(&input);- let payload: TaskPayload = self.send(req).await?;- Ok(payload.task)- }-- /// Update an operator-owned program task (`PATCH /medulla/v1/tasks/:id`).- pub async fn update_program_task(- &self,- task_id: &str,- patch: UpdateProgramTask,- ) -> Result<ProgramTask> {- let task_id = urlencode(task_id);- let req = self- .authed(- self.http- .patch(self.url(&format!("/medulla/v1/tasks/{task_id}"))),- )- .json(&patch);- let payload: TaskPayload = self.send(req).await?;- Ok(payload.task)- }-- /// Delete an operator-owned program task (`DELETE /medulla/v1/tasks/:id`).- pub async fn delete_program_task(&self, task_id: &str) -> Result<bool> {- let task_id = urlencode(task_id);- let req = self.authed(- self.http- .delete(self.url(&format!("/medulla/v1/tasks/{task_id}"))),- );- let payload: DeleteProgramItem = self.send(req).await?;- Ok(payload.deleted)- }-- /// List configured GitHub task sources (`GET /medulla/v1/tasks/sources`).- pub async fn list_program_task_sources(&self) -> Result<Vec<ProgramTaskSource>> {- let req = self.authed(self.http.get(self.url("/medulla/v1/tasks/sources")));- let payload: TaskSourcesPayload = self.send(req).await?;- Ok(payload.sources)- }-- /// Configure a GitHub task source (`POST /medulla/v1/tasks/sources`).- ///- /// `input.token` is write-only: the backend encrypts it and responses expose- /// only [`ProgramTaskSource::has_token`].- pub async fn create_program_task_source(- &self,- input: CreateProgramTaskSource,- ) -> Result<ProgramTaskSource> {- let req = self- .authed(self.http.post(self.url("/medulla/v1/tasks/sources")))- .json(&input);- let payload: TaskSourcePayload = self.send(req).await?;- Ok(payload.source)- }-- /// Synchronize one GitHub source into the task ledger.- pub async fn sync_program_task_source(&self, source_id: &str) -> Result<TaskSourceSyncResult> {- let source_id = urlencode(source_id);- let req = self.authed(- self.http- .post(self.url(&format!("/medulla/v1/tasks/sources/{source_id}/sync"))),- );- let payload: TaskSourceSyncPayload = self.send(req).await?;- Ok(payload.result)- }-- /// Remove a configured GitHub task source.- pub async fn delete_program_task_source(&self, source_id: &str) -> Result<bool> {- let source_id = urlencode(source_id);- let req = self.authed(- self.http- .delete(self.url(&format!("/medulla/v1/tasks/sources/{source_id}"))),- );- let payload: DeleteProgramItem = self.send(req).await?;- Ok(payload.deleted)- }-}diff --git a/crates/openhuman-core/src/medulla/client/program/mod.rs b/crates/openhuman-core/src/medulla/client/program/mod.rsdeleted file mode 100644index 1a3ff403f4..0000000000--- a/crates/openhuman-core/src/medulla/client/program/mod.rs+++ /dev/null@@ -1,9 +0,0 @@-//! Typed models shared by the public worker-roster and task-program endpoints.--mod types;--mod api;-pub use types::*;-pub(crate) use types::{- TaskPayload, TaskSourcePayload, TaskSourceSyncPayload, TaskSourcesPayload, TasksPayload,-};diff --git a/crates/openhuman-core/src/medulla/client/program/types.rs b/crates/openhuman-core/src/medulla/client/program/types.rsdeleted file mode 100644index c876948b41..0000000000--- a/crates/openhuman-core/src/medulla/client/program/types.rs+++ /dev/null@@ -1,312 +0,0 @@-//! Wire models for the worker roster and operator-owned task program APIs.--use serde::{Deserialize, Serialize};-use serde_json::Value;--/// Client-safe harness budget advertised by a connected worker.-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RosterBudget {- /// Provider that meters the budget.- pub provider: String,- /// Provider-defined accounting window.- pub window: String,- /// Tokens still available in the current window, when known.- #[serde(default)]- pub remaining_tokens: Option<u64>,- /// Total token allowance for the current window, when known.- #[serde(default)]- pub limit_tokens: Option<u64>,- /// Unix timestamp after which a depleted budget becomes usable.- #[serde(default)]- pub cooldown_until: Option<u64>,- /// Origin of the budget observation.- pub source: String,-}--/// Connected worker returned by `GET /medulla/v1/roster`.-#[derive(Debug, Clone, Deserialize, Serialize, Default)]-#[serde(rename_all = "camelCase")]-pub struct RosterWorker {- /// Stable worker identifier in the manager registry.- pub registry_id: String,- /// Operator-facing worker label.- pub label: String,- /// Operator-facing description of the worker.- pub description: String,- /// Current manager-reported availability.- pub availability: String,- /// Harness implementation serving the worker.- #[serde(default)]- pub harness: Option<String>,- /// Network address advertised by the worker.- #[serde(default)]- pub address: Option<String>,- /// Provider-specific worker handle.- #[serde(default)]- pub handle: Option<String>,- /// Peer identifier used for wallet-backed routing.- #[serde(default)]- pub wallet_peer_id: Option<String>,- /// Logical CPU capacity visible to the worker.- #[serde(default)]- pub cpu_cores: Option<u32>,- /// Total host memory in bytes.- #[serde(default)]- pub total_mem_bytes: Option<u64>,- /// Currently available host memory in bytes.- #[serde(default)]- pub available_mem_bytes: Option<u64>,- /// Primary IPv4 address selected by the manager.- #[serde(default)]- pub primary_ipv4: Option<String>,- /// Routing and discovery labels attached to the worker.- #[serde(default)]- pub tags: Vec<String>,- /// Whether the worker is currently selected for dispatch.- pub selected: bool,- /// Provider-specific capability document.- #[serde(default)]- pub capabilities: Option<Value>,- /// Client-safe budgets reported for this worker.- #[serde(default)]- pub budgets: Vec<RosterBudget>,-}--/// Response payload of `GET /medulla/v1/roster`.-#[derive(Debug, Clone, Deserialize, Serialize)]-pub struct Roster {- /// Workers currently known to the manager.- #[serde(default)]- pub workers: Vec<RosterWorker>,-}--/// Lifecycle state of an operator-owned program task.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub enum ProgramTaskStatus {- /// Ready for work.- Open,- /// Work has started.- InProgress,- /// Work completed successfully.- Done,- /// Work was intentionally abandoned.- Cancelled,-}--/// Recurrence frequency for an operator-owned program task.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub enum TaskRecurrenceFrequency {- /// Repeat every day.- Daily,- /// Repeat every week.- Weekly,- /// Repeat every month.- Monthly,- /// Repeat after a custom number of days.- EveryDays,-}--/// Optional recurrence rule attached to a program task.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskRecurrence {- /// Schedule family used to calculate the next occurrence.- pub frequency: TaskRecurrenceFrequency,- /// Custom day interval used with [`TaskRecurrenceFrequency::EveryDays`].- #[serde(default, skip_serializing_if = "Option::is_none")]- pub interval_days: Option<u32>,- /// RFC 3339 timestamp for the next scheduled occurrence.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub next_at: Option<String>,-}--/// External source identity attached to a synchronized task.-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgramTaskSourceRef {- /// Source provider name.- pub provider: String,- /// Stable item identifier assigned by the provider.- pub source_id: String,- /// Browser URL for the source item.- #[serde(default)]- pub url: Option<String>,-}--/// An operator-owned task in the backend program ledger.-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgramTask {- /// Stable backend task identifier.- pub id: String,- /// Short operator-facing title.- pub title: String,- /// Detailed task description.- pub description: String,- /// Current task lifecycle state.- pub status: ProgramTaskStatus,- /// Recurrence rule, if the task repeats.- #[serde(default)]- pub recurrence: Option<TaskRecurrence>,- /// External item that produced this task.- #[serde(default)]- pub source: Option<ProgramTaskSourceRef>,- /// RFC 3339 creation timestamp.- pub created_at: String,- /// RFC 3339 timestamp of the latest update.- pub updated_at: String,- /// RFC 3339 timestamp of the latest source synchronization.- #[serde(default)]- pub last_synced_at: Option<String>,- /// Backend-owned dispatch state.- #[serde(default)]- pub dispatch: Value,-}--/// Input for creating a program task.-#[derive(Debug, Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct CreateProgramTask {- /// Short operator-facing title.- pub title: String,- /// Detailed task description.- #[serde(skip_serializing_if = "Option::is_none")]- pub description: Option<String>,- /// Initial lifecycle state; the backend default applies when omitted.- #[serde(skip_serializing_if = "Option::is_none")]- pub status: Option<ProgramTaskStatus>,- /// Initial recurrence rule.- #[serde(skip_serializing_if = "Option::is_none")]- pub recurrence: Option<TaskRecurrence>,-}--/// Patch accepted by `PATCH /medulla/v1/tasks/:id`.-#[derive(Debug, Clone, Default, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UpdateProgramTask {- /// Replacement title, or omission to preserve the current title.- #[serde(skip_serializing_if = "Option::is_none")]- pub title: Option<String>,- /// Replacement description, or omission to preserve the current description.- #[serde(skip_serializing_if = "Option::is_none")]- pub description: Option<String>,- /// Replacement lifecycle state, or omission to preserve the current state.- #[serde(skip_serializing_if = "Option::is_none")]- pub status: Option<ProgramTaskStatus>,- /// Recurrence patch: outer `None` omits the field, inner `None` sends JSON- /// `null` to clear recurrence, and `Some(Some(_))` replaces the rule.- #[serde(skip_serializing_if = "Option::is_none")]- pub recurrence: Option<Option<TaskRecurrence>>,-}--/// GitHub issue state selected by a task source.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum GithubIssueState {- /// Synchronize open issues.- Open,- /// Synchronize closed issues.- Closed,- /// Synchronize issues in either state.- All,-}--/// A configured GitHub task source. Tokens never appear on this response.-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgramTaskSource {- /// Stable backend source identifier.- pub id: String,- /// Source provider name.- pub provider: String,- /// Whether periodic synchronization is enabled.- pub enabled: bool,- /// GitHub repository in `owner/name` form.- pub repository: String,- /// Issue state included by the source.- pub state: GithubIssueState,- /// Labels that issues must match.- #[serde(default)]- pub labels: Vec<String>,- /// Additional provider-defined search filter.- #[serde(default)]- pub filter: Option<String>,- /// Whether a provider token is configured; the token itself is never returned.- pub has_token: bool,- /// RFC 3339 creation timestamp.- pub created_at: String,- /// RFC 3339 timestamp of the latest update.- pub updated_at: String,-}--/// Input for configuring a GitHub task source.-#[derive(Debug, Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct CreateProgramTaskSource {- /// GitHub repository in `owner/name` form.- pub repository: String,- /// Issue state to synchronize.- #[serde(skip_serializing_if = "Option::is_none")]- pub state: Option<GithubIssueState>,- /// Labels that issues must match.- #[serde(skip_serializing_if = "Option::is_none")]- pub labels: Option<Vec<String>>,- /// Additional provider-defined search filter.- #[serde(skip_serializing_if = "Option::is_none")]- pub filter: Option<String>,- /// Provider token to store; this write-only value is never returned.- #[serde(skip_serializing_if = "Option::is_none")]- pub token: Option<String>,- /// Whether periodic synchronization should be enabled.- #[serde(skip_serializing_if = "Option::is_none")]- pub enabled: Option<bool>,-}--/// Result of synchronizing one GitHub source into the task ledger.-#[derive(Debug, Clone, Deserialize, Serialize)]-pub struct TaskSourceSyncResult {- /// Number of tasks created.- pub added: u64,- /// Number of existing tasks updated.- pub updated: u64,- /// Number of source items already current.- pub unchanged: u64,- /// Non-fatal provider errors encountered during synchronization.- #[serde(default)]- pub errors: Vec<String>,-}--#[derive(Debug, Deserialize, Serialize)]-pub(crate) struct TasksPayload {- pub(crate) tasks: Vec<ProgramTask>,-}--#[derive(Debug, Deserialize, Serialize)]-pub(crate) struct TaskPayload {- pub(crate) task: ProgramTask,-}--#[derive(Debug, Deserialize, Serialize)]-pub(crate) struct TaskSourcesPayload {- pub(crate) sources: Vec<ProgramTaskSource>,-}--#[derive(Debug, Deserialize, Serialize)]-pub(crate) struct TaskSourcePayload {- pub(crate) source: ProgramTaskSource,-}--#[derive(Debug, Deserialize, Serialize)]-pub(crate) struct TaskSourceSyncPayload {- pub(crate) result: TaskSourceSyncResult,-}--/// Result shared by program task/source delete endpoints.-#[derive(Debug, Clone, Deserialize, Serialize)]-pub struct DeleteProgramItem {- /// Whether the requested resource existed and was removed.- pub deleted: bool,-}diff --git a/crates/openhuman-core/src/medulla/client/routing.rs b/crates/openhuman-core/src/medulla/client/routing.rsdeleted file mode 100644index 91ac87f20e..0000000000--- a/crates/openhuman-core/src/medulla/client/routing.rs+++ /dev/null@@ -1,91 +0,0 @@-//! Worker routing strategy and the connected-worker roster.-//!-//! Split from the client transport core; the shared request helpers-//! (`url`, `authed`, `send`) live in [`super`].--use super::*;--impl MedullaClient {- /// Read the backend's configured worker routing strategy- /// (`GET /medulla/v1/routing/strategy`).- ///- /// Returns `None` when the backend has no strategy configured or the value is- /// unrecognized, so an absent/garbled strategy degrades to "no backend- /// preference" rather than an error — the operator's local config still wins.- pub async fn get_routing_strategy(&self) -> Result<Option<RoutingStrategy>> {- let req = self.authed(self.http.get(self.url("/medulla/v1/routing/strategy")));- let value: Value = self.send(req).await?;- Ok(value- .get("strategy")- .and_then(|v| v.as_str())- .and_then(RoutingStrategy::from_wire))- }-- /// Persist the operator's worker routing strategy to the backend- /// (`PUT /medulla/v1/routing/strategy`) as `{ "strategy": <camelCase> }`.- pub async fn set_routing_strategy(&self, strategy: RoutingStrategy) -> Result<()> {- let req = self- .authed(self.http.put(self.url("/medulla/v1/routing/strategy")))- .json(&serde_json::json!({ "strategy": strategy.as_wire() }));- let _: Value = self.send(req).await?;- Ok(())- }-- /// Read the connected worker roster (`GET /medulla/v1/roster`).- pub async fn roster(&self) -> Result<Vec<RosterWorker>> {- let req = self.authed(self.http.get(self.url("/medulla/v1/roster")));- let payload: Roster = self.send(req).await?;- Ok(payload.workers)- }-}--/// How the backend picks a worker for a delegated task.-///-/// The camelCase wire tokens match the backend's persisted `routingStrategy`-/// config key, so one value round-trips across config, backend, and host.-///-/// Migrated from medulla-public `runtime/types.rs`: the client is the only thing-/// that speaks these tokens over the wire, so the enum lives beside the two-/// methods that encode and decode it.-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]-#[serde(rename_all = "camelCase")]-pub enum RoutingStrategy {- /// Preserve the operator's explicit host selection.- Manual,- /// Prefer CPU, using available memory as the tie-breaker.- Balanced,- /// Prefer the worker with the most logical CPU cores.- CpuFirst,- /// Prefer the worker with the most currently available memory.- MemoryFirst,-}--impl RoutingStrategy {- /// The camelCase wire token (`manual` / `balanced` / `cpuFirst` / `memoryFirst`).- pub fn as_wire(&self) -> &'static str {- match self {- RoutingStrategy::Manual => "manual",- RoutingStrategy::Balanced => "balanced",- RoutingStrategy::CpuFirst => "cpuFirst",- RoutingStrategy::MemoryFirst => "memoryFirst",- }- }-- /// Parse a camelCase wire token, or `None` when unrecognized.- ///- /// An unrecognized value degrades to "no backend preference" rather than an- /// error, so a newer backend token never breaks an older host.- pub fn from_wire(value: &str) -> Option<Self> {- match value {- "manual" => Some(RoutingStrategy::Manual),- "balanced" => Some(RoutingStrategy::Balanced),- "cpuFirst" => Some(RoutingStrategy::CpuFirst),- "memoryFirst" => Some(RoutingStrategy::MemoryFirst),- _ => None,- }- }-}--#[cfg(test)]-#[path = "routing_routing_strategy_tests_tests.rs"]-mod routing_strategy_tests;diff --git a/crates/openhuman-core/src/medulla/client/routing_routing_strategy_tests_tests.rs b/crates/openhuman-core/src/medulla/client/routing_routing_strategy_tests_tests.rsdeleted file mode 100644index 5be90f0d9c..0000000000--- a/crates/openhuman-core/src/medulla/client/routing_routing_strategy_tests_tests.rs+++ /dev/null@@ -1,19 +0,0 @@-use super::RoutingStrategy;--#[test]-fn wire_tokens_round_trip() {- for s in [- RoutingStrategy::Manual,- RoutingStrategy::Balanced,- RoutingStrategy::CpuFirst,- RoutingStrategy::MemoryFirst,- ] {- assert_eq!(RoutingStrategy::from_wire(s.as_wire()), Some(s));- }-}--#[test]-fn unknown_token_is_none_not_an_error() {- assert_eq!(RoutingStrategy::from_wire("quantumFirst"), None);- assert_eq!(RoutingStrategy::from_wire(""), None);-}diff --git a/crates/openhuman-core/src/medulla/client/sessions.rs b/crates/openhuman-core/src/medulla/client/sessions.rsdeleted file mode 100644index 63943032fa..0000000000--- a/crates/openhuman-core/src/medulla/client/sessions.rs+++ /dev/null@@ -1,141 +0,0 @@-//! Durable session lifecycle (`/medulla/v1/sessions`) and its SSE stream.-//!-//! Split from the client transport core; the shared request helpers-//! (`url`, `authed`, `send`) live in [`super`].--use super::*;-use futures::stream::Stream;--impl MedullaClient {- // --- Sessions ---------------------------------------------------------- /// Create a durable session (`POST /medulla/v1/sessions`).- pub async fn create_session(&self, title: Option<&str>) -> Result<SessionCreated> {- self.create_session_with(title, &[]).await- }-- /// Create a durable session, attaching authored workspace profiles to the mint- /// (`POST /medulla/v1/sessions` with `workspaceProfiles`).- ///- /// Each profile is one workspace root's verbatim `MEDULLA.md`, collected via- /// the host-side workspace-profile collector. An empty slice mints a plain- /// session (the `workspaceProfiles` key is omitted). The backend validates the- /// shape and rejects a malformed profile with a 400.- pub async fn create_session_with(- &self,- title: Option<&str>,- workspace_profiles: &[WorkspaceProfileInput],- ) -> Result<SessionCreated> {- let req = self- .authed(self.http.post(self.url("/medulla/v1/sessions")))- .json(&CreateSessionBody {- title,- workspace_profiles,- });- self.send(req).await- }-- /// List sessions (`GET /medulla/v1/sessions`).- pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>> {- let req = self.authed(self.http.get(self.url("/medulla/v1/sessions")));- self.send(req).await- }-- /// Fetch a session's state (`GET /medulla/v1/sessions/:id`).- pub async fn get_session(&self, session_id: &str) -> Result<SessionDetail> {- let req = self.authed(- self.http- .get(self.url(&format!("/medulla/v1/sessions/{session_id}"))),- );- self.send(req).await- }-- /// Archive a session (`DELETE /medulla/v1/sessions/:id`).- pub async fn archive_session(&self, session_id: &str) -> Result<SessionArchived> {- let req = self.authed(- self.http- .delete(self.url(&format!("/medulla/v1/sessions/{session_id}"))),- );- self.send(req).await- }-- /// Send a message (`POST /medulla/v1/sessions/:id/messages`).- ///- /// With `sync = false` the backend returns 202 `{cycleId, seq}`; with- /// `sync = true` it blocks and returns `{cycleId, seq, reply}`.- pub async fn send_message(- &self,- session_id: &str,- body: &str,- sync: bool,- ) -> Result<SendResult> {- let sync_flag = if sync { "1" } else { "0" };- let req = self- .authed(- self.http- .post(self.url(&format!("/medulla/v1/sessions/{session_id}/messages")))- .query(&[("sync", sync_flag)]),- )- .json(&SendMessageBody { body });- self.send(req).await- }-- /// Replay messages after `after` (`GET .../messages?after=`).- pub async fn list_messages(- &self,- session_id: &str,- after: Option<i64>,- ) -> Result<Vec<Message>> {- let mut req = self- .http- .get(self.url(&format!("/medulla/v1/sessions/{session_id}/messages")));- if let Some(after) = after {- req = req.query(&[("after", after)]);- }- self.send(self.authed(req)).await- }-- /// Replay events after `after` (`GET .../events?after=`).- pub async fn list_events(- &self,- session_id: &str,- after: Option<i64>,- ) -> Result<Vec<WireEventEnvelope>> {- let mut req = self- .http- .get(self.url(&format!("/medulla/v1/sessions/{session_id}/events")));- if let Some(after) = after {- req = req.query(&[("after", after)]);- }- self.send(self.authed(req)).await- }-- /// Abort the running cycle (`POST /medulla/v1/sessions/:id/abort`).- pub async fn abort(&self, session_id: &str) -> Result<AbortResult> {- let req = self.authed(- self.http- .post(self.url(&format!("/medulla/v1/sessions/{session_id}/abort"))),- );- self.send(req).await- }- // --- SSE --------------------------------------------------------------- /// Open a reconnecting SSE stream of events for a session- /// (`GET /medulla/v1/sessions/:id/stream?token=<jwt>`).- ///- /// The returned stream auto-reconnects with `Last-Event-ID` and- /// de-duplicates replayed frames by seq. Drop it to stop.- pub fn stream_events(- &self,- session_id: &str,- last_event_id: Option<u64>,- ) -> impl Stream<Item = Result<WireEventEnvelope>> {- let url = format!(- "{}/medulla/v1/sessions/{}/stream?token={}",- self.base_url,- session_id,- urlencode(&self.jwt),- );- sse::event_stream(self.http.clone(), url, last_event_id)- }-}diff --git a/crates/openhuman-core/src/medulla/client/sse/mod.rs b/crates/openhuman-core/src/medulla/client/sse/mod.rsdeleted file mode 100644index c54c6cd5ee..0000000000--- a/crates/openhuman-core/src/medulla/client/sse/mod.rs+++ /dev/null@@ -1,227 +0,0 @@-//! Hand-rolled Server-Sent Events parsing and a reconnecting event stream.-//!-//! The backend emits frames of the form:-//!-//! ```text-//! id: 42-//! data: {"seq":42,"at":...,"sessionId":"...","event":{"kind":"assistant","body":"hi"}}-//!-//! : ping-//!-//! ```-//!-//! `id:` sets the replay cursor (persisted events only; deltas omit it),-//! `data:` carries the JSON [`WireEventEnvelope`], comment lines (`: ping`) are-//! ignored, and a blank line terminates the current frame.--use std::collections::VecDeque;--use futures::stream::{Stream, StreamExt};--use crate::medulla::client::error::{ClientError, Result};-use crate::medulla::client::types::WireEventEnvelope;--impl SseParser {- /// Create an empty parser.- pub fn new() -> Self {- Self::default()- }-- /// Feed a chunk of decoded text, appending any completed frames to `out`.- pub fn feed(&mut self, chunk: &str, out: &mut Vec<SseFrame>) {- self.line_buf.push_str(chunk);- while let Some(nl) = self.line_buf.find('\n') {- let mut line = self.line_buf[..nl].to_string();- // Drain the line plus the newline from the buffer.- self.line_buf.drain(..=nl);- if line.ends_with('\r') {- line.pop();- }- self.feed_line(&line, out);- }- }-- fn feed_line(&mut self, line: &str, out: &mut Vec<SseFrame>) {- if line.is_empty() {- // Blank line terminates the frame.- if self.got_data || self.id.is_some() {- out.push(SseFrame {- id: self.id.take(),- data: std::mem::take(&mut self.data),- });- }- self.got_data = false;- self.id = None;- return;- }- // Comment line (`: ...`, e.g. `: ping`) — ignore.- if line.starts_with(':') {- return;- }- let (field, value) = match line.find(':') {- Some(i) => {- let v = &line[i + 1..];- // A single leading space after the colon is stripped.- (&line[..i], v.strip_prefix(' ').unwrap_or(v))- }- None => (line, ""),- };- match field {- "id" => {- if let Ok(seq) = value.trim().parse::<u64>() {- self.id = Some(seq);- }- }- "data" => {- if self.got_data {- self.data.push('\n');- }- self.data.push_str(value);- self.got_data = true;- }- // `event:`, `retry:` and unknown fields are not used here.- _ => {}- }- }-}--impl SeqDedup {- /// Start from an optional last-seen seq (the reconnect `Last-Event-ID`).- pub fn new(start: Option<u64>) -> Self {- Self { cursor: start }- }-- /// The current cursor, suitable for a `Last-Event-ID` reconnect header.- pub fn cursor(&self) -> Option<u64> {- self.cursor- }-- /// Decide whether a frame with the given seq should be yielded, advancing- /// the cursor when it does.- pub fn accept(&mut self, seq: Option<u64>) -> bool {- match seq {- None => true,- Some(s) => {- if self.cursor.map(|c| s > c).unwrap_or(true) {- self.cursor = Some(s);- true- } else {- false- }- }- }- }-}--impl StreamState {- /// Open (or reopen) the SSE connection using the current cursor.- async fn connect(&mut self) -> Result<()> {- if !self.first_connect {- // Small backoff between reconnect attempts.- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }- self.first_connect = false;- // The SSE handshake carries its credential in the URL rather than a- // header, so it never passes through `MedullaClient::authed` — the- // product identity has to be attached here or streaming traffic would- // reach the backend unattributed.- let (product_header, product_value) = crate::api::product::product_identity_header();- let mut req = self- .http- .get(&self.url)- .header(reqwest::header::ACCEPT, "text/event-stream")- .header(product_header, product_value);- if let Some(cursor) = self.dedup.cursor() {- req = req.header("Last-Event-ID", cursor.to_string());- }- let resp = req.send().await?.error_for_status()?;- // Map chunks to owned bytes so the stored stream item type stays- // nameable without depending on `bytes` directly.- let body = resp.bytes_stream().map(|r| r.map(|b| b.to_vec()));- self.body = Some(body.boxed());- Ok(())- }-- /// Convert a completed frame into a deduped, decoded envelope (if any).- fn ingest(&mut self, frame: SseFrame) {- if !self.dedup.accept(frame.id) {- return;- }- let trimmed = frame.data.trim();- if trimmed.is_empty() {- return;- }- match serde_json::from_str::<WireEventEnvelope>(trimmed) {- Ok(env) => self.pending.push_back(Ok(env)),- Err(e) => self- .pending- .push_back(Err(ClientError::Decode(e.to_string()))),- }- }-- /// Produce the next stream item, reconnecting as needed. Returns `None`- /// only when the stream is permanently exhausted (never, in practice —- /// it reconnects on end-of-body).- async fn next(&mut self) -> Option<Result<WireEventEnvelope>> {- loop {- if let Some(item) = self.pending.pop_front() {- return Some(item);- }- if self.body.is_none() {- if let Err(e) = self.connect().await {- // Surface the connect error, then retry on the next poll.- return Some(Err(e));- }- }- let body = self.body.as_mut().expect("body set above");- match body.next().await {- Some(Ok(bytes)) => {- let text = String::from_utf8_lossy(&bytes);- let mut frames = Vec::new();- self.parser.feed(&text, &mut frames);- for frame in frames {- self.ingest(frame);- }- }- Some(Err(e)) => {- self.body = None;- return Some(Err(ClientError::Transport(e)));- }- None => {- // Server closed the connection; reconnect from cursor.- self.body = None;- }- }- }- }-}--/// Build a reconnecting SSE stream of [`WireEventEnvelope`]s.-///-/// `url` must already include auth (`?token=<jwt>`). The stream reconnects with-/// the `Last-Event-ID` header and de-duplicates replayed frames by seq. Drop-/// the returned stream to stop.-pub fn event_stream(- http: reqwest::Client,- url: String,- last_event_id: Option<u64>,-) -> impl Stream<Item = Result<WireEventEnvelope>> {- let state = StreamState {- http,- url,- parser: SseParser::new(),- dedup: SeqDedup::new(last_event_id),- pending: VecDeque::new(),- body: None,- first_connect: true,- };- futures::stream::unfold(state, |mut state| async move {- state.next().await.map(|item| (item, state))- })-}--mod types;-pub use types::SeqDedup;-pub use types::SseFrame;-pub use types::SseParser;-use types::StreamState;diff --git a/crates/openhuman-core/src/medulla/client/sse/types.rs b/crates/openhuman-core/src/medulla/client/sse/types.rsdeleted file mode 100644index b0e6564196..0000000000--- a/crates/openhuman-core/src/medulla/client/sse/types.rs+++ /dev/null@@ -1,41 +0,0 @@-//! Data types for the `sse` module.-#[allow(unused_imports)]-use super::*;-/// A completed SSE frame.-#[derive(Debug, Clone, PartialEq)]-pub struct SseFrame {- /// Cursor value from an `id:` line, when present.- pub id: Option<u64>,- /// Concatenated `data:` payload (lines joined with `\n`).- pub data: String,-}-/// Incremental SSE line parser. Feed byte chunks; collect completed frames.-#[derive(Debug, Default)]-pub struct SseParser {- /// Bytes of an incomplete trailing line.- pub(super) line_buf: String,- /// Accumulated `data:` payload for the in-progress frame.- pub(super) data: String,- /// Whether any `data:` line has been seen for the in-progress frame.- pub(super) got_data: bool,- /// `id:` value seen for the in-progress frame.- pub(super) id: Option<u64>,-}-/// Seq-based de-duplication for reconnect replay.-///-/// Frames carrying a persisted `seq` are only accepted when they advance past-/// the cursor; frames without a seq (deltas) always pass.-#[derive(Debug, Default)]-pub struct SeqDedup {- pub(super) cursor: Option<u64>,-}-/// Internal driver state for the reconnecting stream.-pub(super) struct StreamState {- pub(super) http: reqwest::Client,- pub(super) url: String,- pub(super) parser: SseParser,- pub(super) dedup: SeqDedup,- pub(super) pending: VecDeque<Result<WireEventEnvelope>>,- pub(super) body: Option<futures::stream::BoxStream<'static, reqwest::Result<Vec<u8>>>>,- pub(super) first_connect: bool,-}diff --git a/crates/openhuman-core/src/medulla/client/tests/decode_tests.rs b/crates/openhuman-core/src/medulla/client/tests/decode_tests.rsdeleted file mode 100644index e5b82ba099..0000000000--- a/crates/openhuman-core/src/medulla/client/tests/decode_tests.rs+++ /dev/null@@ -1,301 +0,0 @@-//! Decode fixtures: event envelope/kind decoding, success/error envelope-//! unwrapping and error mapping, and `LoopEvent`/`RunResult` deserialization.--use crate::medulla::client::*;-use serde_json::{json, Value};--// ----------------------------------------------------------------------------// Event envelope / kind decode fixtures-// -----------------------------------------------------------------------------fn envelope(event: Value) -> WireEventEnvelope {- let raw = json!({- "seq": 5,- "at": 1234,- "sessionId": "s1",- "cycleId": "c1",- "event": event,- });- serde_json::from_value(raw).unwrap()-}--#[test]-fn wire_envelope_carries_session_and_cycle_ids() {- // The wire type is what `ops::list_events` returns; it must decode the- // `sessionId` / `cycleId` fields the in-process contract type lacks. This- // pins the distinction from `events::EventEnvelope` so a future edit cannot- // silently reintroduce the naming ambiguity (#6078).- let env: WireEventEnvelope = serde_json::from_value(json!({- "at": 42,- "sessionId": "sess-1",- "event": {"kind": "user", "body": "hi"},- }))- .unwrap();- assert_eq!(env.session_id, "sess-1");- assert_eq!(env.at, 42);- // `seq` and `cycleId` are optional on the wire.- assert_eq!(env.seq, None);- assert_eq!(env.cycle_id, None);-- let with_optionals: WireEventEnvelope = serde_json::from_value(json!({- "seq": 7,- "at": 43,- "sessionId": "sess-1",- "cycleId": "cyc-9",- "event": {"kind": "assistant", "body": "yo"},- }))- .unwrap();- assert_eq!(with_optionals.seq, Some(7));- assert_eq!(with_optionals.cycle_id, Some("cyc-9".into()));-}--#[test]-fn decodes_user_and_assistant() {- assert_eq!(- envelope(json!({"kind": "user", "body": "hi"})).kind(),- EventKind::User { body: "hi".into() }- );- assert_eq!(- envelope(json!({"kind": "assistant", "body": "yo"})).kind(),- EventKind::Assistant { body: "yo".into() }- );-}--#[test]-fn decodes_cycle_bracket() {- assert_eq!(- envelope(json!({"kind": "cycle_start", "cycleId": "c1"})).kind(),- EventKind::CycleStart {- cycle_id: Some("c1".into())- }- );- assert_eq!(- envelope(json!({"kind": "cycle_end", "cycleId": "c1", "passCount": 3, "durationMs": 120}))- .kind(),- EventKind::CycleEnd {- cycle_id: Some("c1".into()),- pass_count: Some(3),- duration_ms: Some(120),- error: None,- }- );- assert_eq!(- envelope(json!({"kind": "cycle_end", "cycleId": "c1", "error": true})).kind(),- EventKind::CycleEnd {- cycle_id: Some("c1".into()),- pass_count: None,- duration_ms: None,- error: Some(true),- }- );-}--#[test]-fn decodes_error_and_deltas() {- assert_eq!(- envelope(json!({"kind": "error", "source": "cycle", "message": "boom"})).kind(),- EventKind::Error {- source: "cycle".into(),- message: "boom".into(),- }- );- assert_eq!(- envelope(json!({"kind": "assistant_delta", "delta": "to"})).kind(),- EventKind::AssistantDelta { delta: "to".into() }- );- assert_eq!(- envelope(json!({"kind": "reasoning_delta", "delta": "hm"})).kind(),- EventKind::ReasoningDelta { delta: "hm".into() }- );- match envelope(json!({"kind": "tool_call_delta", "id": "t1"})).kind() {- EventKind::ToolCallDelta { value } => assert_eq!(value["id"], json!("t1")),- other => panic!("expected tool_call_delta, got {other:?}"),- }-}--#[test]-fn unknown_kind_passthrough_preserves_raw() {- let ev = envelope(json!({"kind": "future_thing", "payload": 9}));- match ev.kind() {- EventKind::Unknown(v) => {- assert_eq!(v["kind"], json!("future_thing"));- assert_eq!(v["payload"], json!(9));- }- other => panic!("expected unknown, got {other:?}"),- }- // Raw value stays accessible on the envelope.- assert_eq!(ev.event["payload"], json!(9));- assert_eq!(ev.seq, Some(5));-}--// ----------------------------------------------------------------------------// Envelope unwrapping / error mapping-// -----------------------------------------------------------------------------#[test]-fn unwraps_success_envelope() {- let body = br#"{"success":true,"data":{"sessionId":"abc"}}"#;- let out: SessionCreated = unwrap_envelope(201, body).unwrap();- assert_eq!(out.session_id, "abc");-}--#[test]-fn maps_error_envelope_with_code() {- let body = br#"{"success":false,"error":"token expired","errorCode":"TOKEN_EXPIRED"}"#;- let err = unwrap_envelope::<Value>(401, body).unwrap_err();- assert_eq!(err.error_code(), Some("TOKEN_EXPIRED"));- assert!(err.is_token_expired());- assert_eq!(err.status(), Some(401));- match err {- ClientError::Api { message, .. } => assert_eq!(message, "token expired"),- other => panic!("expected api error, got {other:?}"),- }-}--#[test]-fn maps_error_envelope_with_details() {- let body = br#"{"success":false,"error":"bad","errorCode":"PROTOCOL_MISMATCH","details":{"min":1,"max":2}}"#;- let err = unwrap_envelope::<Value>(409, body).unwrap_err();- match err {- ClientError::Api { details, .. } => {- let d = details.unwrap();- assert_eq!(d["min"], json!(1));- assert_eq!(d["max"], json!(2));- }- other => panic!("expected api error, got {other:?}"),- }-}--#[test]-fn non_json_error_body_becomes_api_error() {- let err = unwrap_envelope::<Value>(500, b"internal error").unwrap_err();- assert_eq!(err.status(), Some(500));- assert_eq!(err.error_code(), None);-}--#[test]-fn auth_error_classification_covers_status_codes_and_non_api_errors() {- let api_error = |status: Option<u16>, error_code: Option<&str>| ClientError::Api {- status,- message: "rejected".into(),- error_code: error_code.map(str::to_owned),- details: None,- };-- assert!(api_error(Some(401), None).is_auth_error());- assert!(api_error(Some(403), None).is_auth_error());- assert!(api_error(Some(500), Some("TOKEN_EXPIRED")).is_auth_error());- assert!(!api_error(Some(400), Some("INVALID_REQUEST")).is_auth_error());-- let decode = ClientError::Decode("bad response".into());- assert_eq!(decode.error_code(), None);- assert_eq!(decode.status(), None);- assert!(!decode.is_token_expired());- assert!(!decode.is_auth_error());-}--// ----------------------------------------------------------------------------// LoopEvent / run result decode-// -----------------------------------------------------------------------------#[test]-fn decodes_loop_events() {- let tool_use: LoopEvent = serde_json::from_value(json!({- "stop": "tool_use",- "cycleId": "c1",- "sessionId": "s1",- "toolCalls": [{"id": "t1", "name": "search", "args": {"q": "x"}}],- }))- .unwrap();- match tool_use {- LoopEvent::ToolUse { tool_calls, .. } => {- assert_eq!(tool_calls[0].name, "search");- assert_eq!(tool_calls[0].args["q"], json!("x"));- }- other => panic!("expected tool_use, got {other:?}"),- }-- let end: LoopEvent = serde_json::from_value(json!({- "stop": "end",- "cycleId": "c1",- "sessionId": "s1",- "reply": "done",- "passCount": 2,- }))- .unwrap();- match end {- LoopEvent::End {- reply, pass_count, ..- } => {- assert_eq!(reply, "done");- assert_eq!(pass_count, Some(2));- }- other => panic!("expected end, got {other:?}"),- }-- let pending: LoopEvent =- serde_json::from_value(json!({"stop": "pending", "cycleId": "c1", "sessionId": "s1"}))- .unwrap();- assert!(matches!(pending, LoopEvent::Pending { .. }));-}--#[test]-fn run_result_distinguishes_reply_and_loop() {- let reply = parse_run_result(json!({- "reply": "hello",- "passCount": 1,- "sessionId": "s1",- "cycleId": "c1",- }))- .unwrap();- assert!(matches!(reply, RunResult::Reply(_)));-- let looped = parse_run_result(json!({- "stop": "end",- "cycleId": "c1",- "sessionId": "s1",- "reply": "done",- }))- .unwrap();- assert!(matches!(looped, RunResult::Loop(LoopEvent::End { .. })));-}--#[test]-fn run_options_serialize_camel_case() {- let opts = RunOptions {- session_id: Some("s1".into()),- tools: None,- options: Some(RunOrchestrationOptions {- config: Some(RunConfig {- max_passes: Some(4),- ..Default::default()- }),- ..Default::default()- }),- };- let v = serde_json::to_value(&opts).unwrap();- assert_eq!(v["sessionId"], json!("s1"));- assert_eq!(v["options"]["config"]["maxPasses"], json!(4));- // Unset fields are omitted.- assert!(v.get("tools").is_none());- assert!(v["options"].get("workspaceProfiles").is_none());-}--#[test]-fn workspace_profiles_serialize_camel_case() {- let opts = RunOptions {- options: Some(RunOrchestrationOptions {- workspace_profiles: Some(vec![WorkspaceProfileInput {- workspace: "/repo/pay".into(),- medulla_md: "Payments service.".into(),- }]),- ..Default::default()- }),- ..Default::default()- };- let v = serde_json::to_value(&opts).unwrap();- let profiles = &v["options"]["workspaceProfiles"];- assert_eq!(profiles[0]["workspace"], json!("/repo/pay"));- // Sent verbatim as `medullaMd` — the backend/SDK owns parsing.- assert_eq!(profiles[0]["medullaMd"], json!("Payments service."));-}diff --git a/crates/openhuman-core/src/medulla/client/tests/integration_tests.rs b/crates/openhuman-core/src/medulla/client/tests/integration_tests.rsdeleted file mode 100644index 07ed02002b..0000000000--- a/crates/openhuman-core/src/medulla/client/tests/integration_tests.rs+++ /dev/null@@ -1,480 +0,0 @@-//! End-to-end tests of the HTTP endpoint surface driven against a local TCP-//! stub, asserting on request lines/bodies and the decoded responses as well-//! as transport/decode error paths.--use super::{http_json, spawn_stub, spawn_stub_capture};-use crate::api::product::{- product_identity_test_lock, reset_product_identity_for_test, set_product_identity,- ProductIdentity, DEFAULT_PRODUCT_IDENTITY, PRODUCT_IDENTITY_HEADER,-};-use crate::medulla::client::*;-use serde_json::json;-use tokio::net::TcpListener;--// ----------------------------------------------------------------------------// Integration: create session / error envelope round-trips-// -----------------------------------------------------------------------------#[tokio::test]-async fn integration_create_session_round_trip() {- let body = r#"{"success":true,"data":{"sessionId":"sess-123"}}"#;- let base = spawn_stub(http_json("HTTP/1.1 201 Created", body)).await;- let client = MedullaClient::new(base, "jwt-abc");- let created = client.create_session(Some("hello")).await.unwrap();- assert_eq!(created.session_id, "sess-123");-}--#[tokio::test]-async fn integration_error_envelope_maps() {- let body = r#"{"success":false,"error":"nope","errorCode":"TOKEN_EXPIRED"}"#;- let base = spawn_stub(http_json("HTTP/1.1 401 Unauthorized", body)).await;- let client = MedullaClient::new(base, "jwt-abc");- let err = client.team_usage().await.unwrap_err();- assert!(err.is_token_expired());-}--// ----------------------------------------------------------------------------// Integration: full endpoint surface against the TCP stub-// -----------------------------------------------------------------------------/// A loopback address with nothing listening (bound then immediately released),-/// so a connect attempt is refused.-async fn dead_addr() -> String {- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- drop(listener);- format!("http://{addr}")-}--fn ok_envelope(status: &str, data: serde_json::Value) -> Vec<u8> {- http_json(- status,- &json!({ "success": true, "data": data }).to_string(),- )-}--#[tokio::test]-async fn routing_strategy_get_and_put_round_trip_camel_case() {- use crate::medulla::client::RoutingStrategy;-- // GET decodes the camelCase strategy; an unknown value degrades to None.- let (base, req) = spawn_stub_capture(ok_envelope(- "HTTP/1.1 200 OK",- json!({ "strategy": "memoryFirst" }),- ))- .await;- let client = MedullaClient::new(base, "jwt-abc");- let got = client.get_routing_strategy().await.unwrap();- assert_eq!(got, Some(RoutingStrategy::MemoryFirst));- let sent = req.await.unwrap();- assert!(- sent.starts_with("GET /medulla/v1/routing/strategy"),- "{sent}"- );-- // PUT sends `{ "strategy": <camelCase> }`.- let (base, req) = spawn_stub_capture(ok_envelope(- "HTTP/1.1 200 OK",- json!({ "strategy": "cpuFirst" }),- ))- .await;- let client = MedullaClient::new(base, "jwt-abc");- client- .set_routing_strategy(RoutingStrategy::CpuFirst)- .await- .unwrap();- let sent = req.await.unwrap();- assert!(- sent.starts_with("PUT /medulla/v1/routing/strategy"),- "{sent}"- );- assert!(sent.contains("\"strategy\":\"cpuFirst\""), "{sent}");-}--#[tokio::test]-async fn roster_decodes_capacity_and_safe_budgets() {- let data = json!({- "workers": [{- "registryId": "agent-1",- "label": "Reviewer",- "description": "Reviews changes",- "availability": "online",- "harness": "codex",- "cpuCores": 8,- "selected": true,- "budgets": [{- "provider": "codex",- "window": "weekly",- "remainingTokens": 9000,- "limitTokens": 10000,- "source": "configured"- }]- }]- });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let workers = client.roster().await.unwrap();- assert_eq!(workers[0].registry_id, "agent-1");- assert_eq!(workers[0].cpu_cores, Some(8));- assert_eq!(workers[0].budgets[0].remaining_tokens, Some(9000));- assert!(req.await.unwrap().starts_with("GET /medulla/v1/roster "));-}--#[tokio::test]-async fn program_task_create_uses_camel_case_contract() {- let data = json!({- "task": {- "id": "task-1",- "title": "Ship integration",- "description": "",- "status": "inProgress",- "createdAt": "2026-07-25T00:00:00Z",- "updatedAt": "2026-07-25T00:00:00Z",- "dispatch": {}- }- });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 201 Created", data)).await;- let client = MedullaClient::new(base, "jwt");- let task = client- .create_program_task(CreateProgramTask {- title: "Ship integration".into(),- description: None,- status: Some(ProgramTaskStatus::InProgress),- recurrence: None,- })- .await- .unwrap();- assert_eq!(task.status, ProgramTaskStatus::InProgress);- let sent = req.await.unwrap();- assert!(sent.starts_with("POST /medulla/v1/tasks "), "{sent}");- assert!(sent.contains("\"status\":\"inProgress\""), "{sent}");-}--#[test]-fn program_task_patch_distinguishes_omitted_and_cleared_recurrence() {- let omitted = serde_json::to_value(UpdateProgramTask::default()).unwrap();- assert_eq!(omitted, json!({}));-- let cleared = serde_json::to_value(UpdateProgramTask {- recurrence: Some(None),- ..UpdateProgramTask::default()- })- .unwrap();- assert_eq!(cleared, json!({ "recurrence": null }));-}--#[tokio::test]-async fn program_resource_ids_are_encoded_as_single_path_segments() {- let (base, req) =- spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", json!({ "deleted": true }))).await;- let client = MedullaClient::new(base, "jwt");- assert!(client.delete_program_task("task/with?#").await.unwrap());- assert!(req- .await- .unwrap()- .starts_with("DELETE /medulla/v1/tasks/task%2Fwith%3F%23 "),);-- assert_eq!(- super::super::urlencode("source/with?#"),- "source%2Fwith%3F%23"- );-}--#[tokio::test]-async fn program_source_sync_surfaces_nonfatal_provider_errors() {- let data = json!({- "result": {- "added": 2,- "updated": 1,- "unchanged": 3,- "errors": ["GitHub result truncated at the page cap"]- }- });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let result = client.sync_program_task_source("source-1").await.unwrap();- assert_eq!(result.added, 2);- assert_eq!(result.errors.len(), 1);- assert!(req- .await- .unwrap()- .starts_with("POST /medulla/v1/tasks/sources/source-1/sync "));-}--#[tokio::test]-async fn authed_get_carries_bearer_and_unwraps() {- let (base, req) =- spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", json!({ "spend": 1 }))).await;- let client = MedullaClient::new(base, "jwt-abc");- let usage = client.team_usage().await.unwrap();- assert_eq!(usage["spend"], json!(1));- let sent = req.await.unwrap();- assert!(sent.contains("authorization: Bearer jwt-abc"), "{sent}");-}--#[tokio::test]-async fn authed_requests_carry_the_default_product_identity() {- let _guard = product_identity_test_lock();- reset_product_identity_for_test();-- let (base, req) =- spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", json!({ "spend": 1 }))).await;- let client = MedullaClient::new(base, "jwt-abc");- client.team_usage().await.unwrap();-- let sent = req.await.unwrap();- assert!(- sent.contains(&format!(- "{PRODUCT_IDENTITY_HEADER}: {DEFAULT_PRODUCT_IDENTITY}"- )),- "{sent}"- );-}--#[tokio::test]-async fn authed_requests_carry_an_overridden_product_identity() {- let _guard = product_identity_test_lock();- reset_product_identity_for_test();- set_product_identity(ProductIdentity::new("medulla").unwrap());-- let (base, req) =- spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", json!({ "spend": 1 }))).await;- let client = MedullaClient::new(base, "jwt-abc");- let result = client.team_usage().await;-- reset_product_identity_for_test();- result.unwrap();-- let sent = req.await.unwrap();- assert!(- sent.contains(&format!("{PRODUCT_IDENTITY_HEADER}: medulla")),- "{sent}"- );- assert!(- !sent.contains(&format!(- "{PRODUCT_IDENTITY_HEADER}: {DEFAULT_PRODUCT_IDENTITY}"- )),- "the override must replace the default, not sit alongside it: {sent}"- );-}--#[tokio::test]-async fn team_usage_fetches_and_unwraps() {- let data = json!({- "plan": "pro",- "inferenceTotals": { "spent": 1.5, "calls": 3 },- "remainingUsd": 4.5,- });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt-abc");- let usage = client.team_usage().await.unwrap();- assert_eq!(usage["plan"], json!("pro"));- assert_eq!(usage["inferenceTotals"]["calls"], json!(3));- let sent = req.await.unwrap();- assert!(sent.starts_with("GET /teams/me/usage"), "{sent}");- assert!(sent.contains("authorization: Bearer jwt-abc"), "{sent}");-}--#[tokio::test]-async fn list_sessions_decodes_rows() {- let data = json!([- { "sessionId": "s1", "title": "One", "status": "active", "lastSeq": 4 },- { "sessionId": "s2", "status": "idle" },- ]);- let (base, _req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let rows = client.list_sessions().await.unwrap();- assert_eq!(rows.len(), 2);- assert_eq!(rows[0].session_id, "s1");- assert_eq!(rows[0].title.as_deref(), Some("One"));- assert_eq!(rows[1].status, SessionStatus::Idle);-}--#[tokio::test]-async fn get_session_decodes_detail() {- let data = json!({ "sessionId": "s9", "status": "active", "eventSeq": 12, "lastSeq": 12 });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let detail = client.get_session("s9").await.unwrap();- assert_eq!(detail.session_id, "s9");- assert_eq!(detail.event_seq, Some(12));- let sent = req.await.unwrap();- assert!(sent.starts_with("GET /medulla/v1/sessions/s9 "), "{sent}");-}--#[tokio::test]-async fn archive_session_round_trip() {- let data = json!({ "sessionId": "s3", "status": "archived" });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let out = client.archive_session("s3").await.unwrap();- assert_eq!(out.session_id, "s3");- assert_eq!(out.status, SessionStatus::Archived);- let sent = req.await.unwrap();- assert!(sent.starts_with("DELETE /medulla/v1/sessions/s3"), "{sent}");-}--#[tokio::test]-async fn send_message_async_sets_sync_zero() {- let data = json!({ "cycleId": "c1", "seq": 7 });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 202 Accepted", data)).await;- let client = MedullaClient::new(base, "jwt");- let out = client.send_message("s1", "hello", false).await.unwrap();- assert_eq!(out.cycle_id, "c1");- assert_eq!(out.seq, 7);- assert!(out.reply.is_none());- let sent = req.await.unwrap();- assert!(sent.contains("sync=0"), "{sent}");- assert!(sent.contains("\"body\":\"hello\""), "{sent}");-}--#[tokio::test]-async fn send_message_sync_carries_reply_and_flag() {- let data = json!({ "cycleId": "c2", "seq": 9, "reply": "done" });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let out = client.send_message("s1", "hi", true).await.unwrap();- assert_eq!(out.reply.as_deref(), Some("done"));- let sent = req.await.unwrap();- assert!(sent.contains("sync=1"), "{sent}");-}--#[tokio::test]-async fn list_messages_passes_after_cursor() {- let data = json!([{ "seq": 3, "role": "user", "body": "q", "ts": 100 }]);- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let msgs = client.list_messages("s1", Some(2)).await.unwrap();- assert_eq!(msgs.len(), 1);- assert_eq!(msgs[0].role, Role::User);- assert_eq!(msgs[0].seq, 3);- let sent = req.await.unwrap();- assert!(sent.contains("after=2"), "{sent}");-}--#[tokio::test]-async fn list_events_decodes_envelopes() {- let data = json!([- { "seq": 1, "at": 10, "sessionId": "s1", "event": { "kind": "assistant", "body": "hi" } },- ]);- let (base, _req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let evs = client.list_events("s1", None).await.unwrap();- assert_eq!(evs.len(), 1);- assert_eq!(evs[0].kind(), EventKind::Assistant { body: "hi".into() });-}--#[tokio::test]-async fn abort_round_trip() {- let data = json!({ "sessionId": "s1", "aborted": true });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let out = client.abort("s1").await.unwrap();- assert!(out.aborted);- let sent = req.await.unwrap();- assert!(- sent.starts_with("POST /medulla/v1/sessions/s1/abort"),- "{sent}"- );-}--#[tokio::test]-async fn run_returns_reply_when_toolless() {- let data = json!({ "reply": "hello", "passCount": 1, "sessionId": "s1", "cycleId": "c1" });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let out = client.run("go", RunOptions::default()).await.unwrap();- match out {- RunResult::Reply(r) => {- assert_eq!(r.reply, "hello");- assert_eq!(r.pass_count, Some(1));- }- other => panic!("expected reply, got {other:?}"),- }- let sent = req.await.unwrap();- assert!(sent.starts_with("POST /orchestration/v1/run"), "{sent}");- assert!(sent.contains("\"input\":\"go\""), "{sent}");-}--#[tokio::test]-async fn run_returns_loop_when_tools_present() {- let data = json!({- "stop": "tool_use",- "cycleId": "c1",- "sessionId": "s1",- "toolCalls": [{ "id": "t1", "name": "search", "args": { "q": "x" } }],- });- let (base, _req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let opts = RunOptions {- tools: Some(vec![ToolDef {- name: "search".into(),- description: "web".into(),- parameters: json!({ "type": "object" }),- }]),- ..Default::default()- };- let out = client.run("go", opts).await.unwrap();- match out {- RunResult::Loop(LoopEvent::ToolUse { tool_calls, .. }) => {- assert_eq!(tool_calls[0].name, "search");- }- other => panic!("expected tool_use loop, got {other:?}"),- }-}--#[tokio::test]-async fn continue_run_decodes_loop_event() {- let data = json!({ "stop": "end", "cycleId": "c1", "sessionId": "s1", "reply": "fin" });- let (base, req) = spawn_stub_capture(ok_envelope("HTTP/1.1 200 OK", data)).await;- let client = MedullaClient::new(base, "jwt");- let results = vec![ToolResult {- id: "t1".into(),- ok: true,- result: Some(json!({ "answer": 42 })),- error: None,- }];- let ev = client.continue_run("c1", results).await.unwrap();- match ev {- LoopEvent::End { reply, .. } => assert_eq!(reply, "fin"),- other => panic!("expected end, got {other:?}"),- }- let sent = req.await.unwrap();- assert!(sent.contains("\"cycleId\":\"c1\""), "{sent}");- assert!(sent.contains("\"toolResults\""), "{sent}");-}--#[tokio::test]-async fn http_error_without_envelope_becomes_api_error() {- let (base, _req) = spawn_stub_capture(http_json(- "HTTP/1.1 503 Service Unavailable",- "upstream down",- ))- .await;- let client = MedullaClient::new(base, "jwt");- let err = client.get_session("s1").await.unwrap_err();- assert_eq!(err.status(), Some(503));- assert_eq!(err.error_code(), None);- match err {- ClientError::Api { message, .. } => assert_eq!(message, "upstream down"),- other => panic!("expected api error, got {other:?}"),- }-}--#[tokio::test]-async fn success_status_with_non_json_body_is_decode_error() {- let (base, _req) = spawn_stub_capture(http_json("HTTP/1.1 200 OK", "not json at all")).await;- let client = MedullaClient::new(base, "jwt");- let err = client.team_usage().await.unwrap_err();- assert!(matches!(err, ClientError::Decode(_)), "got {err:?}");-}--#[tokio::test]-async fn connection_refused_surfaces_transport_error() {- let base = dead_addr().await;- let client = MedullaClient::new(base, "jwt");- let err = client.list_sessions().await.unwrap_err();- assert!(matches!(err, ClientError::Transport(_)), "got {err:?}");- assert_eq!(err.status(), None);- assert_eq!(err.error_code(), None);-}diff --git a/crates/openhuman-core/src/medulla/client/tests/mod.rs b/crates/openhuman-core/src/medulla/client/tests/mod.rsdeleted file mode 100644index 7eaf28dec9..0000000000--- a/crates/openhuman-core/src/medulla/client/tests/mod.rs+++ /dev/null@@ -1,106 +0,0 @@-//! Unit and integration tests for the Medulla client, split by surface:-//! [`decode_tests`] covers envelope/error/run-result JSON decoding;-//! [`sse_tests`] covers the SSE parser, dedupe cursor, and streaming;-//! [`integration_tests`] covers the HTTP endpoint surface against a TCP stub.-//!-//! Shared TCP-stub helpers used by more than one child module live here.--use tokio::io::{AsyncReadExt, AsyncWriteExt};-use tokio::net::TcpListener;--mod decode_tests;-mod integration_tests;-mod sse_tests;--/// Bind a stub server that handles one connection: drain the request, then-/// write `response` verbatim and close. Returns the bound address.-pub(super) async fn spawn_stub(response: Vec<u8>) -> String {- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- let (mut sock, _) = listener.accept().await.unwrap();- // Read whatever the client sent (headers, possibly body); ignore it.- let mut buf = [0u8; 4096];- let _ = sock.read(&mut buf).await;- sock.write_all(&response).await.unwrap();- sock.flush().await.unwrap();- let _ = sock.shutdown().await;- });- format!("http://{addr}")-}--/// Like [`spawn_stub`], but also hands back the raw request bytes the client-/// sent so tests can assert on the method line, query string, headers and body.-///-/// Reads until the request is complete rather than taking whatever a single-/// `read` returns. One read is not one request: TCP may split the body from the-/// headers, or split the headers themselves. Callers assert on both halves-/// (`x-sdk-name` in the header block, JSON payloads in the body), so a short-/// read would surface as an assertion failure against a truncated prefix — a-/// flake that only reproduces under load.-pub(super) async fn spawn_stub_capture(- response: Vec<u8>,-) -> (String, tokio::sync::oneshot::Receiver<String>) {- /// Byte-substring search; `[u8]::contains` matches single elements only.- fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {- haystack.windows(needle.len()).position(|w| w == needle)- }-- /// `Content-Length` from a header block, or 0 when absent (e.g. GET).- /// Header names are case-insensitive per RFC 9110.- fn content_length(headers: &[u8]) -> usize {- String::from_utf8_lossy(headers)- .lines()- .filter_map(|line| line.split_once(':'))- .find(|(name, _)| name.trim().eq_ignore_ascii_case("content-length"))- .and_then(|(_, value)| value.trim().parse().ok())- .unwrap_or(0)- }-- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- let (tx, rx) = tokio::sync::oneshot::channel();- tokio::spawn(async move {- let (mut sock, _) = listener.accept().await.unwrap();- let mut raw: Vec<u8> = Vec::new();- let mut buf = [0u8; 4096];-- // Read to the end of the header block. A 0-length read (peer closed) or- // an error ends the loop, so a misbehaving client cannot hang the test.- let header_end = loop {- match sock.read(&mut buf).await {- Ok(0) | Err(_) => break raw.len(),- Ok(n) => {- raw.extend_from_slice(&buf[..n]);- if let Some(at) = find(&raw, b"\r\n\r\n") {- break at + 4;- }- }- }- };-- // Then read until the declared body has arrived.- let want = header_end + content_length(&raw[..header_end.min(raw.len())]);- while raw.len() < want {- match sock.read(&mut buf).await {- Ok(0) | Err(_) => break,- Ok(n) => raw.extend_from_slice(&buf[..n]),- }- }-- sock.write_all(&response).await.unwrap();- sock.flush().await.unwrap();- let _ = sock.shutdown().await;- let _ = tx.send(String::from_utf8_lossy(&raw).to_string());- });- (format!("http://{addr}"), rx)-}--/// Build a minimal HTTP/1.1 JSON response with the given status line and body.-pub(super) fn http_json(status_line: &str, body: &str) -> Vec<u8> {- format!(- "{status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",- body.len()- )- .into_bytes()-}diff --git a/crates/openhuman-core/src/medulla/client/tests/sse_tests.rs b/crates/openhuman-core/src/medulla/client/tests/sse_tests.rsdeleted file mode 100644index 4b03550555..0000000000--- a/crates/openhuman-core/src/medulla/client/tests/sse_tests.rs+++ /dev/null@@ -1,245 +0,0 @@-//! SSE-focused tests: the incremental frame parser, the reconnect dedupe-//! cursor, and end-to-end streaming (including decode/empty/connect edges)-//! driven through the shared TCP stub.--use super::{http_json, spawn_stub, spawn_stub_capture};-use crate::api::product::{- product_identity_test_lock, reset_product_identity_for_test, set_product_identity,- ProductIdentity, DEFAULT_PRODUCT_IDENTITY, PRODUCT_IDENTITY_HEADER,-};-use crate::medulla::client::sse::{SeqDedup, SseFrame, SseParser};-use crate::medulla::client::*;-use futures::StreamExt;--// ----------------------------------------------------------------------------// SSE parser-// -----------------------------------------------------------------------------fn parse_all(input: &str) -> Vec<SseFrame> {- let mut parser = SseParser::new();- let mut out = Vec::new();- parser.feed(input, &mut out);- out-}--#[test]-fn parses_id_and_data_frame() {- let frames = parse_all("id: 42\ndata: {\"a\":1}\n\n");- assert_eq!(- frames,- vec![SseFrame {- id: Some(42),- data: "{\"a\":1}".to_string(),- }]- );-}--#[test]-fn ignores_ping_comments() {- let frames = parse_all(": ping\n\ndata: hi\n\n");- assert_eq!(- frames,- vec![SseFrame {- id: None,- data: "hi".to_string(),- }]- );-}--#[test]-fn concatenates_multiline_data() {- let frames = parse_all("data: line1\ndata: line2\n\n");- assert_eq!(- frames,- vec![SseFrame {- id: None,- data: "line1\nline2".to_string(),- }]- );-}--#[test]-fn handles_chunked_and_crlf_boundaries() {- let mut parser = SseParser::new();- let mut out = Vec::new();- // Split a single frame across several feeds, with CRLF line endings.- parser.feed("id: 7\r\nda", &mut out);- parser.feed("ta: {\"x\":", &mut out);- parser.feed("2}\r\n\r\n", &mut out);- assert_eq!(- out,- vec![SseFrame {- id: Some(7),- data: "{\"x\":2}".to_string(),- }]- );-}--#[test]-fn yields_multiple_frames() {- let frames = parse_all("id: 1\ndata: a\n\nid: 2\ndata: b\n\n");- assert_eq!(frames.len(), 2);- assert_eq!(frames[0].id, Some(1));- assert_eq!(frames[1].id, Some(2));-}--// ----------------------------------------------------------------------------// Reconnect dedupe cursor-// -----------------------------------------------------------------------------#[test]-fn dedupe_skips_replayed_seqs_and_advances_cursor() {- let mut d = SeqDedup::new(Some(2));- assert!(!d.accept(Some(1))); // replayed, below cursor- assert!(!d.accept(Some(2))); // equal to cursor- assert!(d.accept(Some(3))); // new- assert_eq!(d.cursor(), Some(3));- assert!(d.accept(None)); // deltas always pass- assert!(!d.accept(Some(3))); // duplicate- assert!(d.accept(Some(4)));- assert_eq!(d.cursor(), Some(4));-}--#[test]-fn dedupe_from_start_accepts_everything() {- let mut d = SeqDedup::new(None);- assert!(d.accept(Some(0)));- assert!(d.accept(Some(1)));- assert!(!d.accept(Some(1)));-}--// ----------------------------------------------------------------------------// Integration: SSE streaming through the TCP stub-// -----------------------------------------------------------------------------#[tokio::test]-async fn integration_sse_stream_yields_frames() {- // SSE response: headers, then two persisted event frames, then close.- let frame = |seq: u64, body: &str| {- format!(- "id: {seq}\ndata: {{\"seq\":{seq},\"at\":1,\"sessionId\":\"s1\",\"event\":{{\"kind\":\"assistant\",\"body\":\"{body}\"}}}}\n\n"- )- };- let mut response =- b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_vec();- response.extend_from_slice(": ping\n\n".as_bytes());- response.extend_from_slice(frame(1, "one").as_bytes());- response.extend_from_slice(frame(2, "two").as_bytes());- let base = spawn_stub(response).await;-- let client = MedullaClient::new(base, "jwt-abc");- let stream = client.stream_events("s1", None);- futures::pin_mut!(stream);-- let first = stream.next().await.unwrap().unwrap();- assert_eq!(first.seq, Some(1));- assert_eq!(first.kind(), EventKind::Assistant { body: "one".into() });-- let second = stream.next().await.unwrap().unwrap();- assert_eq!(second.seq, Some(2));- assert_eq!(second.kind(), EventKind::Assistant { body: "two".into() });- // Stop by dropping the stream.-}--/// The SSE handshake authenticates with a `?token=` query parameter, so it-/// never passes through `MedullaClient::authed`. Its product-identity header is-/// attached in the connect path instead — assert it on the wire, because the-/// two transports have no shared code path that a single test could cover.-async fn sse_request_line(identity: Option<&str>) -> String {- let mut response =- b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_vec();- response.extend_from_slice(- b"id: 1\ndata: {\"seq\":1,\"at\":1,\"sessionId\":\"s1\",\"event\":{\"kind\":\"assistant\",\"body\":\"one\"}}\n\n",- );- let (base, req) = spawn_stub_capture(response).await;-- reset_product_identity_for_test();- if let Some(identity) = identity {- set_product_identity(ProductIdentity::new(identity).unwrap());- }-- let client = MedullaClient::new(base, "jwt-abc");- {- let stream = client.stream_events("s1", None);- futures::pin_mut!(stream);- let first = stream.next().await.unwrap().unwrap();- assert_eq!(first.seq, Some(1));- }-- reset_product_identity_for_test();- req.await.unwrap()-}--#[tokio::test]-async fn sse_stream_carries_the_default_product_identity() {- let _guard = product_identity_test_lock();- let sent = sse_request_line(None).await;- assert!(- sent.contains(&format!(- "{PRODUCT_IDENTITY_HEADER}: {DEFAULT_PRODUCT_IDENTITY}"- )),- "{sent}"- );-}--#[tokio::test]-async fn sse_stream_carries_an_overridden_product_identity() {- let _guard = product_identity_test_lock();- let sent = sse_request_line(Some("medulla")).await;- assert!(- sent.contains(&format!("{PRODUCT_IDENTITY_HEADER}: medulla")),- "{sent}"- );-}--// ----------------------------------------------------------------------------// SSE stream edge cases (decode error, empty-data skip, connect failure)-// -----------------------------------------------------------------------------#[tokio::test]-async fn sse_surfaces_a_decode_error_for_bad_json() {- let mut response =- b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_vec();- response.extend_from_slice(b": ping\n\n");- response.extend_from_slice(b"data: {not valid json}\n\n");- let base = spawn_stub(response).await;- let client = MedullaClient::new(base, "jwt");- let stream = client.stream_events("s1", None);- futures::pin_mut!(stream);- let first = stream.next().await.unwrap();- assert!(matches!(first, Err(ClientError::Decode(_))), "{first:?}");-}--#[tokio::test]-async fn sse_skips_empty_data_frames() {- let mut response =- b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_vec();- // An id-only frame and an empty-data frame both carry no payload → skipped.- response.extend_from_slice(b"data: \n\n");- response.extend_from_slice(- b"id: 5\ndata: {\"seq\":5,\"at\":1,\"sessionId\":\"s1\",\"event\":{\"kind\":\"assistant\",\"body\":\"real\"}}\n\n",- );- let base = spawn_stub(response).await;- let client = MedullaClient::new(base, "jwt");- let stream = client.stream_events("s1", None);- futures::pin_mut!(stream);- let first = stream.next().await.unwrap().unwrap();- assert_eq!(first.seq, Some(5));- assert_eq!(- first.kind(),- EventKind::Assistant {- body: "real".into()- }- );-}--#[tokio::test]-async fn sse_connect_failure_surfaces_transport_error() {- // A non-2xx status on the stream GET fails `error_for_status`.- let base = spawn_stub(http_json("HTTP/1.1 500 Internal Server Error", "boom")).await;- let client = MedullaClient::new(base, "jwt");- let stream = client.stream_events("s1", None);- futures::pin_mut!(stream);- let first = stream.next().await.unwrap();- assert!(matches!(first, Err(ClientError::Transport(_))), "{first:?}");-}diff --git a/crates/openhuman-core/src/medulla/client/types/event.rs b/crates/openhuman-core/src/medulla/client/types/event.rsdeleted file mode 100644index 217b61d75b..0000000000--- a/crates/openhuman-core/src/medulla/client/types/event.rs+++ /dev/null@@ -1,113 +0,0 @@-//! Sequenced session event stream types.-//!-//! Split from the parent types module. Field names use serde renames to match-//! the backend camelCase wire format exactly, and unknown fields are tolerated-//! so the client keeps working against newer server versions.--use serde::{Deserialize, Serialize};-use serde_json::Value;--/// Envelope wrapping every event on the session stream.-///-/// This is the **wire** shape: it carries `sessionId` / `cycleId` and matches-/// what `ops::list_events` returns over the RPC surface. Distinct from the-/// in-process contract type `events::EventEnvelope`, which has neither field —-/// the two are named apart so a consumer cannot build one where the other is-/// expected (see #6078).-///-/// `event` retains the raw JSON payload; [`WireEventEnvelope::kind`] parses it-/// into a typed [`EventKind`].-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct WireEventEnvelope {- #[serde(default, skip_serializing_if = "Option::is_none")]- pub seq: Option<u64>,- pub at: u64,- #[serde(rename = "sessionId")]- pub session_id: String,- #[serde(rename = "cycleId", default, skip_serializing_if = "Option::is_none")]- pub cycle_id: Option<String>,- /// Raw event payload; shape depends on `event.kind`.- pub event: Value,-}--impl WireEventEnvelope {- /// Parse the raw `event` payload into a typed [`EventKind`].- pub fn kind(&self) -> EventKind {- EventKind::from_value(&self.event)- }-}--/// Typed event payload parsed from [`WireEventEnvelope::event`].-///-/// `Unknown` preserves the raw value for forward-compatibility with event-/// kinds this client does not yet model.-#[derive(Debug, Clone, PartialEq)]-pub enum EventKind {- /// A user message was recorded.- User { body: String },- /// The assistant produced a final message.- Assistant { body: String },- /// A cognitive cycle started.- CycleStart { cycle_id: Option<String> },- /// A cognitive cycle ended.- CycleEnd {- cycle_id: Option<String>,- pass_count: Option<u64>,- duration_ms: Option<u64>,- error: Option<bool>,- },- /// An error occurred during a cycle.- Error { source: String, message: String },- /// Streaming assistant token delta (unpersisted, no seq).- AssistantDelta { delta: String },- /// Streaming reasoning token delta (unpersisted, no seq).- ReasoningDelta { delta: String },- /// Streaming tool-call delta (unpersisted); raw payload preserved.- ToolCallDelta { value: Value },- /// An event kind not modelled by this client; raw payload preserved.- Unknown(Value),-}--impl EventKind {- /// Parse a raw event object (`{ "kind": ..., ... }`) into a typed kind.- pub fn from_value(v: &Value) -> EventKind {- let kind = v.get("kind").and_then(Value::as_str).unwrap_or("");- let str_field = |k: &str| {- v.get(k)- .and_then(Value::as_str)- .unwrap_or_default()- .to_string()- };- let opt_str = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);- let opt_u64 = |k: &str| v.get(k).and_then(Value::as_u64);- match kind {- "user" => EventKind::User {- body: str_field("body"),- },- "assistant" => EventKind::Assistant {- body: str_field("body"),- },- "cycle_start" => EventKind::CycleStart {- cycle_id: opt_str("cycleId"),- },- "cycle_end" => EventKind::CycleEnd {- cycle_id: opt_str("cycleId"),- pass_count: opt_u64("passCount"),- duration_ms: opt_u64("durationMs"),- error: v.get("error").and_then(Value::as_bool),- },- "error" => EventKind::Error {- source: str_field("source"),- message: str_field("message"),- },- "assistant_delta" => EventKind::AssistantDelta {- delta: str_field("delta"),- },- "reasoning_delta" => EventKind::ReasoningDelta {- delta: str_field("delta"),- },- "tool_call_delta" => EventKind::ToolCallDelta { value: v.clone() },- _ => EventKind::Unknown(v.clone()),- }- }-}diff --git a/crates/openhuman-core/src/medulla/client/types/mod.rs b/crates/openhuman-core/src/medulla/client/types/mod.rsdeleted file mode 100644index 6ed7d907a3..0000000000--- a/crates/openhuman-core/src/medulla/client/types/mod.rs+++ /dev/null@@ -1,109 +0,0 @@-//! JSON types mirroring the backend API responses.-//!-//! Field names use `serde` renames to match the backend's camelCase wire-//! format exactly. Unknown fields are tolerated so the client keeps working-//! against newer server versions.--use serde::{Deserialize, Serialize};-use serde_json::Value;--mod event;-mod reward;-mod run;-mod session;--pub use event::{EventKind, WireEventEnvelope};-pub use reward::{- HistoryRewardBreakdown, HistoryRewardClaim, HistoryRewardStatus, HistoryUploadResult,-};-pub use run::{- LoopEvent, RunConfig, RunLimits, RunOptions, RunOrchestrationOptions, RunReply, RunResult,- ToolCall, ToolDef, ToolResult, WorkspaceProfileInput,-};-pub use session::{- AbortResult, Message, Role, SendResult, SessionArchived, SessionCreated, SessionDetail,- SessionStatus, SessionSummary,-};--// ----------------------------------------------------------------------------// Auth-// -----------------------------------------------------------------------------/// Audience hint accepted by the login-token consume endpoint.-#[derive(Debug, Clone, Copy, Serialize)]-#[serde(rename_all = "lowercase")]-pub enum Audience {- App,- Dashboard,-}--// ----------------------------------------------------------------------------// Sessions (/medulla/v1)-// -----------------------------------------------------------------------------/// Client for the Medulla backend HTTP + SSE API.-#[derive(Debug, Clone)]-pub struct MedullaClient {- pub(super) base_url: String,- pub(super) jwt: String,- pub(super) http: reqwest::Client,-}-/// Builder for [`MedullaClient`].-#[derive(Debug, Default)]-pub struct MedullaClientBuilder {- pub(super) base_url: Option<String>,- pub(super) jwt: Option<String>,- pub(super) http: Option<reqwest::Client>,-}-/// Raw response envelope shared by every endpoint.-#[derive(Debug, Deserialize)]-pub(super) struct RawEnvelope {- #[serde(default)]- pub(super) success: bool,- #[serde(default)]- pub(super) data: Option<Value>,- #[serde(default)]- pub(super) error: Option<String>,- #[serde(rename = "errorCode", default)]- pub(super) error_code: Option<String>,- #[serde(default)]- pub(super) details: Option<Value>,-}--/// Request body for creating a durable session.-///-/// `workspaceProfiles` carries the authored `MEDULLA.md` for each active-/// workspace root; the backend session-mint accepts and distils them. Omitted-/// entirely when no workspace has a profile, so a plain session mint is unchanged.-#[derive(serde::Serialize)]-pub(super) struct CreateSessionBody<'a> {- #[serde(skip_serializing_if = "Option::is_none")]- pub(super) title: Option<&'a str>,- #[serde(- rename = "workspaceProfiles",- skip_serializing_if = "<[WorkspaceProfileInput]>::is_empty"- )]- pub(super) workspace_profiles: &'a [WorkspaceProfileInput],-}--/// Request body for adding a message to a session.-#[derive(serde::Serialize)]-pub(super) struct SendMessageBody<'a> {- pub(super) body: &'a str,-}--/// Request body for starting an orchestration run.-#[derive(serde::Serialize)]-pub(super) struct RunBody<'a> {- pub(super) input: &'a str,- #[serde(flatten)]- pub(super) options: &'a RunOptions,-}--/// Request body for continuing an orchestration run.-#[derive(serde::Serialize)]-#[serde(rename_all = "camelCase")]-pub(super) struct ContinueRunBody<'a> {- pub(super) cycle_id: &'a str,- pub(super) tool_results: Vec<ToolResult>,-}diff --git a/crates/openhuman-core/src/medulla/client/types/reward.rs b/crates/openhuman-core/src/medulla/client/types/reward.rsdeleted file mode 100644index acdfbb932f..0000000000--- a/crates/openhuman-core/src/medulla/client/types/reward.rs+++ /dev/null@@ -1,81 +0,0 @@-//! Onboarding history-reward upload, scoring, and claim types.-//!-//! Split from the parent types module. Field names use serde renames to match-//! the backend camelCase wire format exactly, and unknown fields are tolerated-//! so the client keeps working against newer server versions.--use serde::Deserialize;--/// Running claim metrics returned after uploading one transcript-/// (`POST /agent-integrations/history-rewards/uploads`).-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HistoryUploadResult {- /// Transcripts accumulated on the claim so far.- pub session_count: u64,- /// Running token total across the claim.- pub cumulative_tokens: u64,- /// Running distinct-active-day count across the claim.- pub active_days: u64,- /// Agents represented on the claim so far.- #[serde(default)]- pub agents: Vec<String>,-}--/// Per-metric USD contributions, so the reveal can show how a total was earned.-#[derive(Debug, Clone, Default, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HistoryRewardBreakdown {- pub tokens_usd: f64,- pub active_days_usd: f64,- pub sessions_usd: f64,- pub multi_agent_usd: f64,-}--/// The caller's history-reward status-/// (`GET /agent-integrations/history-rewards/status`).-///-/// This is the authority for "has this user already earned the reward?" — the-/// local config flag only decides whether to re-render the welcome screen.-#[derive(Debug, Clone, Default, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HistoryRewardStatus {- /// True once the reward has been granted.- pub claimed: bool,- /// True when at least one transcript was uploaded but not yet claimed.- #[serde(default)]- pub has_uploads: bool,- /// USD granted, populated once scored.- #[serde(default)]- pub awarded_usd: f64,- /// Human-facing power-level label.- #[serde(default)]- pub tier: Option<String>,- #[serde(default)]- pub session_count: u64,- #[serde(default)]- pub cumulative_tokens: u64,- #[serde(default)]- pub active_days: u64,- #[serde(default)]- pub agents: Vec<String>,- /// Advertised ceiling, so the client renders "x of $25" without hardcoding.- #[serde(default)]- pub max_reward_usd: f64,-}--/// Result of claiming the reward-/// (`POST /agent-integrations/history-rewards/claim`).-#[derive(Debug, Clone, Default, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HistoryRewardClaim {- /// The settled status after claiming.- #[serde(flatten)]- pub status: HistoryRewardStatus,- /// How the award was composed.- #[serde(default)]- pub breakdown: HistoryRewardBreakdown,- /// True when this call granted nothing new (a repeat claim).- #[serde(default)]- pub already_claimed: bool,-}diff --git a/crates/openhuman-core/src/medulla/client/types/run.rs b/crates/openhuman-core/src/medulla/client/types/run.rsdeleted file mode 100644index 270a87ed24..0000000000--- a/crates/openhuman-core/src/medulla/client/types/run.rs+++ /dev/null@@ -1,177 +0,0 @@-//! One-shot orchestration run types (/orchestration/v1).-//!-//! Split from the parent types module. Field names use serde renames to match-//! the backend camelCase wire format exactly, and unknown fields are tolerated-//! so the client keeps working against newer server versions.--use serde::{Deserialize, Serialize};-use serde_json::Value;--/// A client-side tool definition offered to a run.-#[derive(Debug, Clone, Serialize)]-pub struct ToolDef {- pub name: String,- pub description: String,- /// JSON-Schema object describing the tool parameters.- pub parameters: Value,-}--/// A tool call requested by the orchestrator.-#[derive(Debug, Clone, Deserialize)]-pub struct ToolCall {- pub id: String,- pub name: String,- #[serde(default)]- pub args: Value,-}--/// A tool result fed back via `run/continue`.-#[derive(Debug, Clone, Serialize)]-pub struct ToolResult {- pub id: String,- pub ok: bool,- #[serde(skip_serializing_if = "Option::is_none")]- pub result: Option<Value>,- #[serde(skip_serializing_if = "Option::is_none")]- pub error: Option<String>,-}--/// Config knobs for a run (`options.config`).-#[derive(Debug, Clone, Default, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RunConfig {- #[serde(skip_serializing_if = "Option::is_none")]- pub max_passes: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub max_steps: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub max_depth: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub context_window_tokens: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub verification: Option<String>,-}--/// Resource limits for a run (`options.limits`).-#[derive(Debug, Clone, Default, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RunLimits {- #[serde(skip_serializing_if = "Option::is_none")]- pub max_concurrency: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub max_tokens: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub deadline_ms: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub max_tasks_per_delegate: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- pub max_depth: Option<u32>,-}--/// One workspace's authored `MEDULLA.md`, sent verbatim on a run request. The-/// medulla SDK owns the format, so the text is forwarded unparsed and the-/// backend distils it into the orchestrator's context.-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkspaceProfileInput {- /// The workspace/repo path this profile describes.- pub workspace: String,- /// Verbatim `MEDULLA.md` contents.- pub medulla_md: String,-}--/// The `options` object of a run request.-#[derive(Debug, Clone, Default, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RunOrchestrationOptions {- #[serde(skip_serializing_if = "Option::is_none")]- pub prompt_overrides: Option<std::collections::BTreeMap<String, String>>,- #[serde(skip_serializing_if = "Option::is_none")]- pub config: Option<RunConfig>,- #[serde(skip_serializing_if = "Option::is_none")]- pub limits: Option<RunLimits>,- /// Authored workspace profiles for the directories this cycle works over.- #[serde(skip_serializing_if = "Option::is_none")]- pub workspace_profiles: Option<Vec<WorkspaceProfileInput>>,-}--/// Optional inputs to [`crate::medulla::client::MedullaClient::run`].-#[derive(Debug, Clone, Default, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RunOptions {- #[serde(skip_serializing_if = "Option::is_none")]- pub session_id: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub tools: Option<Vec<ToolDef>>,- #[serde(skip_serializing_if = "Option::is_none")]- pub options: Option<RunOrchestrationOptions>,-}--/// Final reply from a tool-less run.-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct RunReply {- pub reply: String,- #[serde(default)]- pub pass_count: Option<u32>,- #[serde(default)]- pub compressed_history: Vec<Value>,- #[serde(default)]- pub escalations: Vec<Value>,- #[serde(default)]- pub session_id: Option<String>,- #[serde(default)]- pub cycle_id: Option<String>,-}--/// A single step of the client tool-loop.-#[derive(Debug, Clone, Deserialize)]-#[serde(tag = "stop", rename_all = "snake_case")]-pub enum LoopEvent {- /// The orchestrator wants the client to run tools and continue.- ToolUse {- #[serde(rename = "cycleId")]- cycle_id: String,- #[serde(rename = "sessionId")]- session_id: String,- #[serde(rename = "toolCalls", default)]- tool_calls: Vec<ToolCall>,- },- /// The run finished with a final reply.- End {- #[serde(rename = "cycleId")]- cycle_id: String,- #[serde(rename = "sessionId")]- session_id: String,- reply: String,- #[serde(rename = "passCount", default)]- pass_count: Option<u32>,- #[serde(rename = "compressedHistory", default)]- compressed_history: Vec<Value>,- #[serde(default)]- escalations: Vec<Value>,- },- /// Long-poll returned without progress; poll `run/continue` again.- Pending {- #[serde(rename = "cycleId")]- cycle_id: String,- #[serde(rename = "sessionId")]- session_id: String,- },- /// The run errored.- Error {- #[serde(rename = "cycleId")]- cycle_id: String,- #[serde(rename = "sessionId")]- session_id: String,- error: Value,- },-}--/// Outcome of [`crate::medulla::client::MedullaClient::run`]: either a final reply (tool-less)-/// or a tool-loop event (when tools were supplied).-#[derive(Debug, Clone)]-pub enum RunResult {- Reply(RunReply),- Loop(LoopEvent),-}diff --git a/crates/openhuman-core/src/medulla/client/types/session.rs b/crates/openhuman-core/src/medulla/client/types/session.rsdeleted file mode 100644index a6e8725ba5..0000000000--- a/crates/openhuman-core/src/medulla/client/types/session.rs+++ /dev/null@@ -1,110 +0,0 @@-//! Durable session lifecycle types (/medulla/v1/sessions).-//!-//! Split from the parent types module. Field names use serde renames to match-//! the backend camelCase wire format exactly, and unknown fields are tolerated-//! so the client keeps working against newer server versions.--use serde::{Deserialize, Serialize};--/// Session lifecycle status.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum SessionStatus {- Active,- Idle,- Archived,- /// Any status not yet modelled by this client.- ///- /// Also the `Default`: a value constructed rather than decoded has not- /// declared a status, and defaulting to `Active` would assert one.- #[default]- #[serde(other)]- Other,-}--/// Message author role.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum Role {- User,- Assistant,- #[serde(other)]- Other,-}--/// Result of creating a session (`POST /medulla/v1/sessions`).-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SessionCreated {- pub session_id: String,-}--/// Item in the session list (`GET /medulla/v1/sessions`).-#[derive(Debug, Clone, Deserialize, Serialize, Default)]-#[serde(rename_all = "camelCase")]-pub struct SessionSummary {- pub session_id: String,- #[serde(default)]- pub title: Option<String>,- #[serde(default)]- pub last_active_at: Option<i64>,- pub status: SessionStatus,- #[serde(default)]- pub last_seq: Option<i64>,-}--/// Detailed session state (`GET /medulla/v1/sessions/:id`).-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SessionDetail {- pub session_id: String,- pub status: SessionStatus,- #[serde(default)]- pub last_cycle_id: Option<String>,- #[serde(default)]- pub last_seq: Option<i64>,- #[serde(default)]- pub event_seq: Option<i64>,-}--/// Result of archiving a session (`DELETE /medulla/v1/sessions/:id`).-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SessionArchived {- pub session_id: String,- pub status: SessionStatus,-}--/// Result of `POST /medulla/v1/sessions/:id/messages`.-///-/// The async (202) response carries `cycle_id`/`seq`; the sync (`?sync=1`)-/// response additionally carries `reply`.-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SendResult {- pub cycle_id: String,- pub seq: i64,- #[serde(default)]- pub reply: Option<String>,-}--/// A replayed message (`GET /medulla/v1/sessions/:id/messages`).-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct Message {- pub seq: i64,- pub role: Role,- pub body: String,- #[serde(default)]- pub ts: Option<i64>,- #[serde(default)]- pub cycle_id: Option<String>,-}--/// Result of `POST /medulla/v1/sessions/:id/abort`.-#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct AbortResult {- pub session_id: String,- pub aborted: bool,-}diff --git a/crates/openhuman-core/src/medulla/contract.rs b/crates/openhuman-core/src/medulla/contract.rsdeleted file mode 100644index 0bd10a3443..0000000000--- a/crates/openhuman-core/src/medulla/contract.rs+++ /dev/null@@ -1,304 +0,0 @@-//! Serde data types for the public agent-harness wire shapes. Field renames pin-//! every struct to the JSON contract-//! (`rename_all = "camelCase"`); enum renames pin the lowercase status/state-//! strings used on the wire. Only shapes and their trivial impls live here —-//! the reserved tool-name vocabulary and re-exports live in the parent module.-//!-//! Two payloads are intentionally opaque: `HarnessStatus::last_result` and-//! `HarnessEvent::CycleEvent { event }`. Neither payload is a contract this-//! crate consumes, so both-//! are kept as [`serde_json::Value`] rather than mirrored field-by-field; this-//! preserves them losslessly without coupling the client to their internals.--use serde::{Deserialize, Serialize};-use serde_json::Value;-use std::collections::BTreeMap;--/// Lifecycle of a tracked task. The lowercase rename matches the wire strings-/// (`"open"`, `"active"`, …).-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum TrackedTaskStatus {- /// Opened, not yet started.- Open,- /// Actively being worked.- Active,- /// Blocked on something.- Blocked,- /// Completed.- Done,- /// Abandoned.- Cancelled,-}--/// Advisory boundaries and completion criteria for one delegated worker lane.-/// Medulla transports this object verbatim; enforcement remains host-owned.-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkerContract {- /// The exact outcome the lane should produce.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub outcome: Option<String>,- /// Workspace globs the lane is permitted to change.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub permitted_paths: Option<Vec<String>>,- /// Work explicitly excluded from this lane.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub non_goals: Option<Vec<String>>,- /// Focused verification commands the worker should run.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub verify_commands: Option<Vec<String>>,- /// Condition that ends the lane.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub terminal_condition: Option<String>,-}--/// One command or named gate outcome attributed to a task.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct VerificationEvidence {- /// Exact verification command, mutually exclusive with `gate` by convention.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub command: Option<String>,- /// Named library gate, mutually exclusive with `command` by convention.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub gate: Option<String>,- /// Whether the verification passed.- pub ok: bool,- /// Bounded human-readable outcome.- pub summary: String,-}--/// One unit of intended work on the session task board.-/// `created_at`/`updated_at` are ISO-8601 strings and-/// `delegated_task_ids`/`notes` are always-present arrays (never omitted).-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TrackedTask {- /// Stable task id (minted host-side).- pub id: String,- /// Short imperative title.- pub title: String,- /// Optional longer description; omitted from JSON when absent.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub detail: Option<String>,- /// Current lifecycle status.- pub status: TrackedTaskStatus,- /// ISO-8601 creation timestamp.- pub created_at: String,- /// ISO-8601 timestamp of the last update.- pub updated_at: String,- /// The originating orchestrator instruction / cycle, when recorded.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub instruction_id: Option<String>,- /// Delegation-ledger keys this task fanned out to.- #[serde(default)]- pub delegated_task_ids: Vec<String>,- /// Append-only free-form notes.- #[serde(default)]- pub notes: Vec<String>,- /// Worker-lane boundaries associated with a linked delegation.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub contract: Option<WorkerContract>,- /// Append-only per-task verification observations.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub evidence: Option<Vec<VerificationEvidence>>,-}--/// The run state of the agent harness. The lowercase rename matches the wire-/// strings.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum HarnessState {- /// No instruction is running and the queue is empty.- Idle,- /// A cycle is running or the queue is non-empty.- Running,- /// `stop()` has latched; no new work starts.- Stopped,-}--/// Rolled-up token/cycle accounting.-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HarnessUsage {- /// Completed cycles.- pub cycles: u64,- /// Total prompt tokens across cycles and settled delegations.- pub input_tokens: u64,- /// Total completion tokens across cycles and settled delegations.- pub output_tokens: u64,-}--/// A synchronous snapshot of the agent harness.-///-/// `last_result` is kept opaque (see the module doc): present after the first-/// cycle settles, omitted before then.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct HarnessStatus {- /// Run state.- pub state: HarnessState,- /// Instructions still waiting in the FIFO queue.- pub queued: u64,- /// The running instruction's id, when a cycle is active.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub active_instruction_id: Option<String>,- /// The running cycle's id, when a cycle is active.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub active_cycle_id: Option<String>,- /// The live task board.- #[serde(default)]- pub tasks: Vec<TrackedTask>,- /// Currently in-flight delegated sub-agent tasks.- pub running_delegations: u64,- /// Rolled-up usage.- pub usage: HarnessUsage,- /// The most recent cycle result (opaque `CycleResult`); omitted before the- /// first cycle settles.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub last_result: Option<Value>,- /// Escalation messages accumulated across cycles.- #[serde(default)]- pub escalations: Vec<String>,-}--/// A harness observability event, tagged by its `kind` field. The three-/// lifecycle kinds share a shape but stay distinct-/// variants so the `kind` string round-trips exactly.-///-/// `CycleEvent { event }` keeps its inner event opaque (see the module doc).-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-// Keep the public `task: TrackedTask` field source-compatible; boxing only this-// wire variant would impose an unrelated API migration on an additive schema.-#[allow(clippy::large_enum_variant)]-#[serde(- tag = "kind",- rename_all = "snake_case",- rename_all_fields = "camelCase"-)]-pub enum HarnessEvent {- /// An instruction was enqueued.- InstructionQueued {- /// The enqueued instruction's id.- instruction_id: String,- /// The cycle id minted for it.- cycle_id: String,- },- /// A cycle started.- CycleStart {- /// The running instruction's id.- instruction_id: String,- /// The running cycle's id.- cycle_id: String,- },- /// A cycle ended.- CycleEnd {- /// The finished instruction's id.- instruction_id: String,- /// The finished cycle's id.- cycle_id: String,- },- /// A task board entry changed.- TaskBoardChanged {- /// The task whose state changed.- task: TrackedTask,- },- /// A raw per-cycle event was re-emitted (opaque `CycleEvent`).- CycleEvent {- /// The wrapped cycle event payload.- event: Value,- },-}--/// The serialisable receipt returned when an instruction is queued.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct InstructionReceipt {- /// The enqueued instruction's id.- pub instruction_id: String,- /// The cycle id minted for it.- pub cycle_id: String,-}--/// Machine-readable seat attribution stamped onto an agent descriptor at-/// `metadata.budget`.-///-/// Note the timestamp contrast with [`SeatHeadroom`]: here `primary_resets_at`-/// is an **ISO-8601 string** (formatted at the roster boundary), whereas-/// `SeatHeadroom` carries epoch-milliseconds numbers throughout.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct AgentBudgetMetadata {- /// The seat this agent draws from.- pub seat_id: String,- /// The metering provider (e.g. `"anthropic"`, `"openai"`).- pub provider: String,- /// The plan id (e.g. `"claude_max_5x"`).- pub plan: String,- /// The human-facing plan label (e.g. `"Claude Max 5×"`).- pub plan_label: String,- /// Remaining headroom, in tokens, at snapshot time.- pub headroom_tokens: u64,- /// True when headroom is below the exhausted floor.- pub exhausted: bool,- /// ISO-8601 timestamp the primary window next refills.- pub primary_resets_at: String,-}--/// Remaining tokens and next-reset for one refill window, keyed by window id in-/// [`SeatHeadroom::per_window`]. Times are epoch-milliseconds.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WindowHeadroom {- /// Tokens left in this window.- pub remaining: u64,- /// Epoch-ms this window next refills.- pub resets_at: i64,-}--/// Live headroom for one connected seat. All timestamps are epoch-milliseconds-/// numbers (contrast-/// [`AgentBudgetMetadata`], which formats `primary_resets_at` to an ISO string).-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SeatHeadroom {- /// Stable seat id.- pub seat_id: String,- /// The metering provider.- pub provider: String,- /// The plan id resolved against the plan catalog.- pub plan: String,- /// The human-facing plan label.- pub plan_label: String,- /// Roster agent ids this seat is pinned to.- #[serde(default)]- pub agent_ids: Vec<String>,- /// Whether the seat is enabled for delegation.- pub enabled: bool,- /// Lower wins when picking among a provider's seats.- pub priority: i64,- /// Min headroom across windows; 0 when disabled or throttled.- pub headroom_tokens: u64,- /// True when headroom is below the exhausted floor.- pub exhausted: bool,- /// Epoch-ms the seat is throttled until; omitted when not throttled.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub throttled_until: Option<i64>,- /// Epoch-ms the primary (first) window next refills.- pub primary_resets_at: i64,- /// Remaining tokens + next-reset per window, keyed by window id.- #[serde(default)]- pub per_window: BTreeMap<String, WindowHeadroom>,-}--impl AgentBudgetMetadata {- /// Parse the budget stamp out of an agent descriptor's `metadata` map, if a- /// well-formed `budget` object is present. Returns `None` when the key is- /// absent or the value does not match the [`AgentBudgetMetadata`] shape, so a- /// malformed stamp degrades to "no budget shown" rather than erroring.- pub fn from_metadata(metadata: &serde_json::Map<String, Value>) -> Option<AgentBudgetMetadata> {- let budget = metadata.get("budget")?;- serde_json::from_value(budget.clone()).ok()- }-}diff --git a/crates/openhuman-core/src/medulla/events/mod.rs b/crates/openhuman-core/src/medulla/events/mod.rsdeleted file mode 100644index 796e7d0517..0000000000--- a/crates/openhuman-core/src/medulla/events/mod.rs+++ /dev/null@@ -1,36 +0,0 @@-//! The Medulla event vocabulary: every library cycle event plus the-//! host-sourced rows (cycle framing, conversation turns, agent/session status,-//! effects).-//!-//! [`SessionEvent`] deserializes any JSON `{kind, ...}` shape and keeps unrecognized-//! kinds in [`SessionEvent::Unknown`], so a newer backend never drops rows on an-//! older host.-//!-//! # This module is an ungated type carve-out-//!-//! Unlike the rest of `medulla`, these types stay compiled whether or not the-//! `medulla` feature is on. They are inert serde/std definitions with no-//! coupling to their gated siblings, and `crates/openhuman-embed/src/` names them in public-//! signatures — gating them would take the facade down with them.-//!-//! This follows the rule `AGENTS.md` draws from the `skills` / `mcp`-//! gates: put a domain's inert types in a dependency-free submodule and leave it-//! ungated; gate only behaviour. Both builds then share one definition, so-//! fields cannot drift between them.-//!-//! Split by responsibility: [`types`] is the data model (including-//! [`SessionEvent::kind`], which the codec writes as the wire discriminator) and-//! `serde_impl` the custom compact-JSON codec.-//!-//! Presentation derivations — transcript rendering, last-message lookup,-//! one-line descriptions — deliberately do NOT live here. They are the-//! renderer's concern and stay in the host, so the core carries the wire-//! contract only.--mod serde_impl;-mod types;--#[cfg(test)]-mod tests;--pub use types::{EventEnvelope, NodeTrace, SessionEvent, TaskDigest, ToolCall, Usage};diff --git a/crates/openhuman-core/src/medulla/events/serde_impl.rs b/crates/openhuman-core/src/medulla/events/serde_impl.rsdeleted file mode 100644index 8b7619c257..0000000000--- a/crates/openhuman-core/src/medulla/events/serde_impl.rs+++ /dev/null@@ -1,249 +0,0 @@-//! Custom `Serialize`/`Deserialize` for [`SessionEvent`].-//!-//! `SessionEvent` serializes to a compact `{kind, ...}` JSON object (camelCase keys,-//! null fields dropped) and deserializes any such object — keeping unrecognized-//! kinds as [`SessionEvent::Unknown`] so a newer backend never drops rows on an older-//! TUI. The field-extraction helpers below tolerate missing or ill-typed fields.--use serde::de::{self, Deserializer};-use serde::ser::Serializer;-use serde::{Deserialize, Serialize};-use serde_json::{json, Map, Value};--use super::types::SessionEvent;--impl SessionEvent {- /// Render the event to its compact JSON object, including the `kind` tag and- /// with null fields dropped to keep the shape TS-friendly.- fn to_value(&self) -> Value {- let mut v = match self {- SessionEvent::InferenceStart { tier, op, model } => {- json!({ "tier": tier, "op": op, "model": model })- }- SessionEvent::InferenceEnd {- tier,- op,- model,- duration_ms,- usage,- content,- reasoning,- tool_calls,- } => json!({- "tier": tier, "op": op, "model": model, "durationMs": duration_ms,- "usage": usage, "content": content, "reasoning": reasoning,- "toolCalls": tool_calls,- }),- SessionEvent::ToolCallStart { index, name } => json!({ "index": index, "name": name }),- SessionEvent::ToolCallDelta { index, args_delta } => {- json!({ "index": index, "argsDelta": args_delta })- }- SessionEvent::AssistantDelta { delta } => json!({ "delta": delta }),- SessionEvent::ReasoningDelta { delta } => json!({ "delta": delta }),- SessionEvent::TaskStart {- task_id,- instruction,- depth,- agent_id,- contract,- } => {- json!({ "taskId": task_id, "instruction": instruction, "depth": depth, "agentId": agent_id, "contract": contract })- }- SessionEvent::TaskEvent {- task_id,- event_kind,- content,- harness,- } => {- json!({ "taskId": task_id, "eventKind": event_kind, "content": content, "harness": harness })- }- SessionEvent::TaskAttention {- task_id,- reason,- content,- question_id,- } => {- json!({ "taskId": task_id, "reason": reason, "content": content, "questionId": question_id })- }- SessionEvent::TaskComplete { digest } => json!({ "digest": digest }),- SessionEvent::Trace { entry } => json!({ "entry": entry }),- SessionEvent::Error { source, message } => {- json!({ "source": source, "message": message })- }- SessionEvent::CycleStart { cycle_id } => json!({ "cycleId": cycle_id }),- SessionEvent::CycleEnd {- cycle_id,- pass_count,- duration_ms,- } => json!({ "cycleId": cycle_id, "passCount": pass_count, "durationMs": duration_ms }),- SessionEvent::AgentStatus {- agent_id,- availability,- detail,- } => json!({ "agentId": agent_id, "availability": availability, "detail": detail }),- SessionEvent::SessionEvent {- agent_id,- session_id,- event_kind,- content,- } => {- json!({ "agentId": agent_id, "sessionId": session_id, "eventKind": event_kind, "content": content })- }- SessionEvent::PeerSession {- agent_id,- session_id,- state,- harness,- } => {- json!({ "agentId": agent_id, "sessionId": session_id, "state": state, "harness": harness })- }- SessionEvent::User { body } => json!({ "body": body }),- SessionEvent::Assistant { body } => json!({ "body": body }),- SessionEvent::Effect { effect } => json!({ "effect": effect }),- SessionEvent::Unknown { data, .. } => Value::Object(data.clone()),- };- if let Value::Object(map) = &mut v {- map.insert("kind".into(), Value::String(self.kind().to_string()));- // Drop nulls to keep the JSON compact and TS-shaped.- map.retain(|_, val| !val.is_null());- }- v- }-}--impl Serialize for SessionEvent {- fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {- self.to_value().serialize(s)- }-}--/// Read a required string field, defaulting to `""` when missing or non-string.-fn get_str(m: &Map<String, Value>, k: &str) -> String {- m.get(k).and_then(Value::as_str).unwrap_or("").to_string()-}-/// Read an optional string field: missing, non-string, or empty all map to `None`.-fn opt_str(m: &Map<String, Value>, k: &str) -> Option<String> {- m.get(k)- .and_then(Value::as_str)- .map(str::to_string)- .filter(|s| !s.is_empty())-}-/// Read a required integer field, defaulting to `0` when missing or non-integer.-fn get_i64(m: &Map<String, Value>, k: &str) -> i64 {- m.get(k).and_then(Value::as_i64).unwrap_or(0)-}-/// Deserialize a nested field into `T`, yielding `None` on any decode failure.-fn from_field<T: for<'d> Deserialize<'d>>(m: &Map<String, Value>, k: &str) -> Option<T> {- m.get(k)- .and_then(|v| serde_json::from_value(v.clone()).ok())-}--impl<'de> Deserialize<'de> for SessionEvent {- fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {- let value = Value::deserialize(d)?;- let map = value- .as_object()- .ok_or_else(|| de::Error::custom("event must be an object"))?;- let kind = map.get("kind").and_then(Value::as_str).unwrap_or("");- Ok(match kind {- "inference_start" => SessionEvent::InferenceStart {- tier: get_str(map, "tier"),- op: get_str(map, "op"),- model: opt_str(map, "model"),- },- "inference_end" => SessionEvent::InferenceEnd {- tier: get_str(map, "tier"),- op: get_str(map, "op"),- model: opt_str(map, "model"),- duration_ms: get_i64(map, "durationMs"),- usage: from_field(map, "usage"),- content: opt_str(map, "content"),- reasoning: opt_str(map, "reasoning"),- tool_calls: from_field(map, "toolCalls"),- },- "tool_call_start" => SessionEvent::ToolCallStart {- index: get_i64(map, "index"),- name: get_str(map, "name"),- },- "tool_call_delta" => SessionEvent::ToolCallDelta {- index: get_i64(map, "index"),- args_delta: get_str(map, "argsDelta"),- },- "assistant_delta" => SessionEvent::AssistantDelta {- delta: get_str(map, "delta"),- },- "reasoning_delta" => SessionEvent::ReasoningDelta {- delta: get_str(map, "delta"),- },- "task_start" => SessionEvent::TaskStart {- task_id: get_str(map, "taskId"),- instruction: get_str(map, "instruction"),- depth: get_i64(map, "depth"),- agent_id: opt_str(map, "agentId"),- contract: from_field(map, "contract"),- },- "task_event" => SessionEvent::TaskEvent {- task_id: get_str(map, "taskId"),- event_kind: get_str(map, "eventKind"),- content: get_str(map, "content"),- harness: opt_str(map, "harness"),- },- "task_attention" => SessionEvent::TaskAttention {- task_id: get_str(map, "taskId"),- reason: get_str(map, "reason"),- content: get_str(map, "content"),- question_id: opt_str(map, "questionId"),- },- "task_complete" => SessionEvent::TaskComplete {- digest: from_field(map, "digest")- .ok_or_else(|| de::Error::custom("task_complete needs digest"))?,- },- "trace" => SessionEvent::Trace {- entry: from_field(map, "entry")- .ok_or_else(|| de::Error::custom("trace needs entry"))?,- },- "error" => SessionEvent::Error {- source: get_str(map, "source"),- message: get_str(map, "message"),- },- "cycle_start" => SessionEvent::CycleStart {- cycle_id: get_str(map, "cycleId"),- },- "cycle_end" => SessionEvent::CycleEnd {- cycle_id: get_str(map, "cycleId"),- pass_count: get_i64(map, "passCount"),- duration_ms: get_i64(map, "durationMs"),- },- "agent_status" => SessionEvent::AgentStatus {- agent_id: get_str(map, "agentId"),- availability: get_str(map, "availability"),- detail: opt_str(map, "detail"),- },- "session_event" => SessionEvent::SessionEvent {- agent_id: get_str(map, "agentId"),- session_id: get_str(map, "sessionId"),- event_kind: get_str(map, "eventKind"),- content: get_str(map, "content"),- },- "peer_session" => SessionEvent::PeerSession {- agent_id: get_str(map, "agentId"),- session_id: get_str(map, "sessionId"),- state: get_str(map, "state"),- harness: opt_str(map, "harness"),- },- "user" => SessionEvent::User {- body: get_str(map, "body"),- },- "assistant" => SessionEvent::Assistant {- body: get_str(map, "body"),- },- "effect" => SessionEvent::Effect {- effect: map.get("effect").cloned().unwrap_or(Value::Null),- },- other => SessionEvent::Unknown {- kind: other.to_string(),- data: map.clone(),- },- })- }-}diff --git a/crates/openhuman-core/src/medulla/events/tests/mod.rs b/crates/openhuman-core/src/medulla/events/tests/mod.rsdeleted file mode 100644index 9b9c155485..0000000000--- a/crates/openhuman-core/src/medulla/events/tests/mod.rs+++ /dev/null@@ -1,12 +0,0 @@-//! Unit tests for the event vocabulary, split by the surface under test:-//! [`serde_tests`] covers JSON round-trips and deserialize tolerance;-//! [`derive_tests`] covers the read-only derivations.--use crate::medulla::events::{EventEnvelope, SessionEvent};--mod serde_tests;--/// Build an envelope at `seq` with a zero timestamp for concise test setup.-pub(super) fn env(seq: u64, event: SessionEvent) -> EventEnvelope {- EventEnvelope { seq, at: 0, event }-}diff --git a/crates/openhuman-core/src/medulla/events/tests/serde_tests.rs b/crates/openhuman-core/src/medulla/events/tests/serde_tests.rsdeleted file mode 100644index fb8f901500..0000000000--- a/crates/openhuman-core/src/medulla/events/tests/serde_tests.rs+++ /dev/null@@ -1,331 +0,0 @@-//! Tests for [`SessionEvent`] JSON serialization: full round-trips across every-//! kind, and the deserialize tolerance rules (unknown kinds, missing fields,-//! empty-string normalization, and error cases).--use serde_json::json;--use crate::medulla::events::*;--#[test]-fn unknown_kind_round_trips() {- let json = r#"{"kind":"weird_kind","payload":42}"#;- let ev: SessionEvent = serde_json::from_str(json).unwrap();- match &ev {- SessionEvent::Unknown { kind, data } => {- assert_eq!(kind, "weird_kind");- assert_eq!(data.get("payload").unwrap(), &json!(42));- }- _ => panic!("expected unknown"),- }- let back = serde_json::to_value(&ev).unwrap();- assert_eq!(back.get("kind").unwrap(), &json!("weird_kind"));- assert_eq!(back.get("payload").unwrap(), &json!(42));-}--#[test]-fn known_event_round_trips() {- let ev = SessionEvent::InferenceEnd {- tier: "reasoning".into(),- op: "execute_step".into(),- model: Some("gpt".into()),- duration_ms: 120,- usage: Some(Usage {- input_tokens: 10,- output_tokens: 5,- ..Default::default()- }),- content: None,- reasoning: None,- tool_calls: None,- };- let s = serde_json::to_string(&ev).unwrap();- let back: SessionEvent = serde_json::from_str(&s).unwrap();- assert_eq!(ev, back);-}--/// One representative JSON per kind, exercising every deserialize arm.-fn one_of_each() -> Vec<(&'static str, SessionEvent)> {- vec![- (- "inference_start",- SessionEvent::InferenceStart {- tier: "orchestrator".into(),- op: "orchestrate".into(),- model: Some("m".into()),- },- ),- (- "inference_end",- SessionEvent::InferenceEnd {- tier: "reasoning".into(),- op: "step".into(),- model: None,- duration_ms: 5,- usage: None,- content: Some("c".into()),- reasoning: Some("r".into()),- tool_calls: Some(vec![ToolCall {- name: "grep".into(),- args: json!({"q": 1}),- }]),- },- ),- (- "tool_call_start",- SessionEvent::ToolCallStart {- index: 2,- name: "read".into(),- },- ),- (- "tool_call_delta",- SessionEvent::ToolCallDelta {- index: 2,- args_delta: "{\"a\":".into(),- },- ),- (- "assistant_delta",- SessionEvent::AssistantDelta { delta: "x".into() },- ),- (- "reasoning_delta",- SessionEvent::ReasoningDelta { delta: "y".into() },- ),- (- "task_start",- SessionEvent::TaskStart {- task_id: "t1".into(),- instruction: "do".into(),- depth: 2,- agent_id: Some("dev".into()),- contract: None,- },- ),- (- "task_event",- SessionEvent::TaskEvent {- task_id: "t1".into(),- event_kind: "text".into(),- content: "hi".into(),- harness: Some("codex".into()),- },- ),- (- "task_attention",- SessionEvent::TaskAttention {- task_id: "t1".into(),- reason: "confirm".into(),- content: "proceed?".into(),- question_id: Some("q1".into()),- },- ),- (- "task_complete",- SessionEvent::TaskComplete {- digest: TaskDigest {- task_id: "t1".into(),- status: "done".into(),- digest: "d".into(),- result_ref: Some(json!({"ref": 1})),- usage: Some(Usage {- input_tokens: 1,- output_tokens: 2,- ..Default::default()- }),- depth: 2,- contract: None,- evidence: None,- },- },- ),- (- "trace",- SessionEvent::Trace {- entry: NodeTrace {- node: "orchestrate".into(),- ms: 12,- tool: Some("grep".into()),- op: None,- },- },- ),- (- "error",- SessionEvent::Error {- source: "cycle".into(),- message: "boom".into(),- },- ),- (- "cycle_start",- SessionEvent::CycleStart {- cycle_id: "c1".into(),- },- ),- (- "cycle_end",- SessionEvent::CycleEnd {- cycle_id: "c1".into(),- pass_count: 3,- duration_ms: 99,- },- ),- (- "agent_status",- SessionEvent::AgentStatus {- agent_id: "dev".into(),- availability: "online".into(),- detail: Some("idle".into()),- },- ),- (- "session_event",- SessionEvent::SessionEvent {- agent_id: "m1".into(),- session_id: "s1".into(),- event_kind: "stdout".into(),- content: "log".into(),- },- ),- (- "peer_session",- SessionEvent::PeerSession {- agent_id: "m1".into(),- session_id: "s1".into(),- state: "working".into(),- harness: Some("codex".into()),- },- ),- ("user", SessionEvent::User { body: "hey".into() }),- ("assistant", SessionEvent::Assistant { body: "yo".into() }),- (- "effect",- SessionEvent::Effect {- effect: json!({"kind": "send"}),- },- ),- ]-}--#[test]-fn every_kind_round_trips_and_reports_kind() {- for (kind, ev) in one_of_each() {- assert_eq!(ev.kind(), kind, "kind() mismatch for {kind}");- let s = serde_json::to_string(&ev).unwrap();- let back: SessionEvent = serde_json::from_str(&s).unwrap();- assert_eq!(ev, back, "round-trip mismatch for {kind}");- }-}--#[test]-fn empty_object_is_unknown_with_empty_kind() {- let ev: SessionEvent = serde_json::from_str("{}").unwrap();- assert!(matches!(&ev, SessionEvent::Unknown { kind, .. } if kind.is_empty()));- assert_eq!(ev.kind(), "");-}--#[test]-fn non_object_json_is_a_deserialize_error() {- assert!(serde_json::from_str::<SessionEvent>("[1,2,3]").is_err());- assert!(serde_json::from_str::<SessionEvent>("42").is_err());-}--#[test]-fn task_complete_without_digest_errors() {- assert!(serde_json::from_str::<SessionEvent>(r#"{"kind":"task_complete"}"#).is_err());-}--#[test]-fn trace_without_entry_errors() {- assert!(serde_json::from_str::<SessionEvent>(r#"{"kind":"trace"}"#).is_err());-}--#[test]-fn opt_str_filters_empty_to_none() {- // An empty `model` string decodes to `None`, not `Some("")`.- let ev: SessionEvent =- serde_json::from_str(r#"{"kind":"inference_start","tier":"r","op":"o","model":""}"#)- .unwrap();- assert!(matches!(- ev,- SessionEvent::InferenceStart { model: None, .. }- ));-}--#[test]-fn serialize_drops_null_fields() {- // A model-less inference_start must not carry a `"model":null` key.- let ev = SessionEvent::InferenceStart {- tier: "r".into(),- op: "o".into(),- model: None,- };- let v = serde_json::to_value(&ev).unwrap();- assert!(v.get("model").is_none(), "null model should be dropped");- assert_eq!(v.get("kind").unwrap(), &json!("inference_start"));-}--#[test]-fn effect_decode_defaults_to_null_when_missing() {- let ev: SessionEvent = serde_json::from_str(r#"{"kind":"effect"}"#).unwrap();- assert!(matches!(ev, SessionEvent::Effect { effect } if effect.is_null()));-}--#[test]-fn envelope_round_trips() {- let e = EventEnvelope {- seq: 7,- at: 123,- event: SessionEvent::User { body: "hi".into() },- };- let s = serde_json::to_string(&e).unwrap();- let back: EventEnvelope = serde_json::from_str(&s).unwrap();- assert_eq!(e, back);-}--#[test]-fn tool_call_defaults_args_to_null() {- let tc: ToolCall = serde_json::from_str(r#"{"name":"grep"}"#).unwrap();- assert_eq!(tc.name, "grep");- assert!(tc.args.is_null());-}--#[test]-fn worker_contract_and_evidence_round_trip_on_task_events() {- let start = json!({- "kind": "task_start",- "taskId": "lane-1",- "instruction": "Implement.",- "depth": 2,- "contract": {- "outcome": "Ship the parser",- "permittedPaths": ["src/parser/**"],- "nonGoals": ["No UI"],- "verifyCommands": ["cargo test parser"],- "terminalCondition": "tests green"- }- });- let event: SessionEvent = serde_json::from_value(start.clone()).unwrap();- assert_eq!(serde_json::to_value(event).unwrap(), start);-- let complete = json!({- "kind": "task_complete",- "digest": {- "taskId": "lane-1",- "status": "done",- "digest": "implemented",- "depth": 2,- "contract": {- "outcome": "Ship the parser",- "permittedPaths": ["src/parser/**"]- },- "evidence": [- {"gate": "verify_examples", "ok": true, "summary": "VERIFIED"},- {"command": "cargo test parser", "ok": true, "summary": "12 passed"}- ]- }- });- let event: SessionEvent = serde_json::from_value(complete.clone()).unwrap();- assert_eq!(serde_json::to_value(event).unwrap(), complete);-}diff --git a/crates/openhuman-core/src/medulla/events/types.rs b/crates/openhuman-core/src/medulla/events/types.rsdeleted file mode 100644index de367fb179..0000000000--- a/crates/openhuman-core/src/medulla/events/types.rs+++ /dev/null@@ -1,242 +0,0 @@-//! The event data model: the [`SessionEvent`] union and its payload structs plus the-//! sequenced [`EventEnvelope`]. These are plain data types; the custom-//! serialization lives in [`super::serde_impl`] and the read-only derivations in-//! [`super::derive`].--use serde::{Deserialize, Serialize};-use serde_json::{Map, Value};--use super::super::contract::{VerificationEvidence, WorkerContract};--/// Token accounting reported alongside an inference or task result.-///-/// The cache fields are optional because not every provider reports them and-/// not every wire carries them: absent means "not reported", which the UI-/// renders as no cache segment rather than as zero. Reading a missing number as-/// 0% would claim a cache miss that was never measured.-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]-pub struct Usage {- /// Tokens consumed by the prompt.- #[serde(rename = "inputTokens")]- pub input_tokens: i64,- /// Tokens produced by the model.- #[serde(rename = "outputTokens")]- pub output_tokens: i64,- /// Prompt tokens served from the provider's cache, when reported.- #[serde(- default,- rename = "cacheReadTokens",- skip_serializing_if = "Option::is_none"- )]- pub cache_read_tokens: Option<i64>,- /// Prompt tokens written into the provider's cache, when reported.- #[serde(- default,- rename = "cacheCreationTokens",- skip_serializing_if = "Option::is_none"- )]- pub cache_creation_tokens: Option<i64>,-}--impl Usage {- /// The share of prompt tokens that came from cache, when both numbers are- /// known and the prompt was non-empty.- pub fn cache_hit_rate(&self) -> Option<f64> {- let cached = self.cache_read_tokens? as f64;- // `inputTokens` is the whole prompt, cached portion included, so the- // ratio is against it rather than against cached + uncached.- let total = self.input_tokens as f64;- (total > 0.0).then(|| (cached / total).clamp(0.0, 1.0))- }-}--/// A single tool invocation emitted by a completed inference.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct ToolCall {- /// The tool's name.- pub name: String,- /// The tool arguments as raw JSON; defaults to `null` when absent.- #[serde(default)]- pub args: Value,-}--/// The terminal summary of a task: status, digest text, and optional result/usage.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct TaskDigest {- /// The task identifier this digest closes out.- #[serde(rename = "taskId")]- pub task_id: String,- /// The final task status (e.g. `done`).- pub status: String,- /// A short human-readable digest of the outcome.- #[serde(default)]- pub digest: String,- /// An optional reference to the full result payload.- #[serde(default, rename = "resultRef", skip_serializing_if = "Option::is_none")]- pub result_ref: Option<Value>,- /// Token usage accrued by the task, when reported.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub usage: Option<Usage>,- /// The task's nesting depth in the cycle tree.- #[serde(default)]- pub depth: i64,- /// Advisory boundaries supplied at delegation time.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub contract: Option<WorkerContract>,- /// Verification observations produced in this task's scope.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub evidence: Option<Vec<VerificationEvidence>>,-}--/// One node-execution trace entry for the Trace / Overview lists.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct NodeTrace {- /// The node that ran.- pub node: String,- /// Wall-clock duration in milliseconds.- #[serde(default)]- pub ms: i64,- /// The tool the node invoked, if any.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub tool: Option<String>,- /// The operation the node performed, if any (used when no `tool` is set).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub op: Option<String>,-}--/// The full event union. Unknown kinds ride through in `Unknown`.-#[derive(Debug, Clone, PartialEq)]-pub enum SessionEvent {- /// An inference call began.- InferenceStart {- tier: String,- op: String,- model: Option<String>,- },- /// An inference call finished, with timing, usage, and any output.- InferenceEnd {- tier: String,- op: String,- model: Option<String>,- duration_ms: i64,- usage: Option<Usage>,- content: Option<String>,- reasoning: Option<String>,- tool_calls: Option<Vec<ToolCall>>,- },- /// A streamed tool call started at `index`.- ToolCallStart { index: i64, name: String },- /// A chunk of streamed tool-call arguments.- ToolCallDelta { index: i64, args_delta: String },- /// A chunk of streamed assistant text.- AssistantDelta { delta: String },- /// A chunk of streamed reasoning text.- ReasoningDelta { delta: String },- /// A task began.- TaskStart {- task_id: String,- instruction: String,- depth: i64,- agent_id: Option<String>,- contract: Option<WorkerContract>,- },- /// A task emitted an event (text, status, etc.).- TaskEvent {- task_id: String,- event_kind: String,- content: String,- harness: Option<String>,- },- /// A task needs operator attention (e.g. a confirmation).- TaskAttention {- task_id: String,- reason: String,- content: String,- question_id: Option<String>,- },- /// A task finished; carries its [`TaskDigest`].- TaskComplete { digest: TaskDigest },- /// A node-execution trace entry.- Trace { entry: NodeTrace },- /// An error surfaced by a source component.- Error { source: String, message: String },- /// A cycle began.- CycleStart { cycle_id: String },- /// A cycle finished, with its pass count and duration.- CycleEnd {- cycle_id: String,- pass_count: i64,- duration_ms: i64,- },- /// An agent's availability changed.- AgentStatus {- agent_id: String,- availability: String,- detail: Option<String>,- },- /// A session emitted an event on an agent.- SessionEvent {- agent_id: String,- session_id: String,- event_kind: String,- content: String,- },- /// A peer session's state changed.- PeerSession {- agent_id: String,- session_id: String,- state: String,- harness: Option<String>,- },- /// A user chat turn.- User { body: String },- /// An assistant chat turn.- Assistant { body: String },- /// A host effect (opaque JSON).- Effect { effect: Value },- /// An unrecognized event kind, preserved verbatim for forward compatibility.- Unknown {- kind: String,- data: Map<String, Value>,- },-}--/// A sequenced event with its wall-clock timestamp (epoch ms).-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct EventEnvelope {- /// Monotonic sequence number within the stream.- pub seq: u64,- /// Wall-clock timestamp in epoch milliseconds.- pub at: i64,- /// The wrapped event.- pub event: SessionEvent,-}--impl SessionEvent {- /// The `kind` discriminator, matching the JSON tag.- pub fn kind(&self) -> &str {- match self {- SessionEvent::InferenceStart { .. } => "inference_start",- SessionEvent::InferenceEnd { .. } => "inference_end",- SessionEvent::ToolCallStart { .. } => "tool_call_start",- SessionEvent::ToolCallDelta { .. } => "tool_call_delta",- SessionEvent::AssistantDelta { .. } => "assistant_delta",- SessionEvent::ReasoningDelta { .. } => "reasoning_delta",- SessionEvent::TaskStart { .. } => "task_start",- SessionEvent::TaskEvent { .. } => "task_event",- SessionEvent::TaskAttention { .. } => "task_attention",- SessionEvent::TaskComplete { .. } => "task_complete",- SessionEvent::Trace { .. } => "trace",- SessionEvent::Error { .. } => "error",- SessionEvent::CycleStart { .. } => "cycle_start",- SessionEvent::CycleEnd { .. } => "cycle_end",- SessionEvent::AgentStatus { .. } => "agent_status",- SessionEvent::SessionEvent { .. } => "session_event",- SessionEvent::PeerSession { .. } => "peer_session",- SessionEvent::User { .. } => "user",- SessionEvent::Assistant { .. } => "assistant",- SessionEvent::Effect { .. } => "effect",- SessionEvent::Unknown { kind, .. } => kind,- }- }-}diff --git a/crates/openhuman-core/src/medulla/mod.rs b/crates/openhuman-core/src/medulla/mod.rsdeleted file mode 100644index adbdc89f33..0000000000--- a/crates/openhuman-core/src/medulla/mod.rs+++ /dev/null@@ -1,71 +0,0 @@-//! Medulla integration domain — the cloud client, its wire vocabulary, and the-//! harness contract types the two share.-//!-//! This is the real Medulla surface. It replaced the `medulla_local` draft — a-//! supervised `medulla-serve` child that answered two of N ports — which has-//! since been removed along with the `subconscious.engine = "medulla"`-//! behaviour it backed. That engine is to be re-ported onto this domain; its-//! config keys remain accepted as inert serde meanwhile so existing configs-//! still boot (see `config::schema::subconscious`).-//!-//! # Two directions, one product name-//!-//! Do not confuse this domain with `socket::medulla`. They are unrelated code-//! paths that share nothing but a word:-//!-//! | Module | Role | Transport |-//! |---|---|---|-//! | `crate::medulla` (here) | OpenHuman as a Medulla **client** | outbound HTTP/SSE to the backend |-//! | `crate::platform::socket::medulla` | OpenHuman as a Medulla **worker** | inbound Socket.IO from a remote operator |-//!-//! A single binary can be both at once.-//!-//! # Gating-//!-//! Behaviour is gated on the `medulla` Cargo feature and tagged-//! [`DomainGroup::Medulla`](crate::core::all::DomainGroup) at runtime. The-//! [`contract`] and [`events`] type modules are **ungated carve-outs** — see-//! [`events`] for why.--/// Medulla chat-session store (`medulla_chat`). Gated on the same `medulla`-/// feature as the rest of the family.-#[cfg(feature = "medulla")]-pub mod chat;-#[cfg(feature = "medulla")]-pub mod client;-pub mod contract;-pub mod events;-#[cfg(feature = "medulla")]-pub mod ops;-#[cfg(feature = "medulla")]-pub mod resolve;-#[cfg(feature = "medulla")]-mod schemas;--pub use contract::{VerificationEvidence, WorkerContract};-pub use events::{EventEnvelope, SessionEvent};-#[cfg(feature = "medulla")]-pub use schemas::{all_medulla_controller_schemas, all_medulla_registered_controllers};--/// The tool names the Medulla harness reserves for its built-in memory and-/// task-tracker modules.-///-/// A module author registering business tools must avoid these: the harness-/// composes its own modules eagerly and a collision throws at construction.-pub const RESERVED_TOOL_NAMES: [&str; 6] = [- "task_create",- "task_update",- "task_list",- "memory_write",- "memory_read",- "memory_list",-];--/// Whether `name` collides with a harness-reserved tool name.-pub fn is_reserved_tool_name(name: &str) -> bool {- RESERVED_TOOL_NAMES.contains(&name)-}--#[cfg(test)]-#[path = "mod_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/medulla/mod_tests.rs b/crates/openhuman-core/src/medulla/mod_tests.rsdeleted file mode 100644index 3702c985f2..0000000000--- a/crates/openhuman-core/src/medulla/mod_tests.rs+++ /dev/null@@ -1,15 +0,0 @@-use super::*;--#[test]-fn reserved_tool_names_are_detected() {- for name in RESERVED_TOOL_NAMES {- assert!(is_reserved_tool_name(name), "{name} must be reserved");- }-}--#[test]-fn ordinary_tool_names_are_not_reserved() {- for name in ["file_read", "web_fetch", "task_creates", "memory"] {- assert!(!is_reserved_tool_name(name), "{name} must not be reserved");- }-}diff --git a/crates/openhuman-core/src/medulla/ops.rs b/crates/openhuman-core/src/medulla/ops.rsdeleted file mode 100644index 06ed2f413a..0000000000--- a/crates/openhuman-core/src/medulla/ops.rs+++ /dev/null@@ -1,235 +0,0 @@-//! Business logic for the `medulla` RPC namespace.-//!-//! Each function resolves a client from ambient config, performs one backend-//! call, and returns an [`RpcOutcome`]. Transport and client-construction-//! failures become [`StructuredRpcError`]s so a host can branch on a stable-//! `data.kind` instead of matching on message text.--use serde::{Deserialize, Serialize};--use crate::config::Config;-use crate::rpc::{RpcOutcome, StructuredRpcError};--use super::client::{- AbortResult, ClientError, MedullaClient, Message, RosterWorker, SendResult, SessionCreated,- SessionDetail, SessionSummary, WireEventEnvelope,-};-use super::resolve::{self, NotConfigured};--/// Whether the Medulla integration is usable, and why not when it isn't.-///-/// `Deserialize` as well as `Serialize` because this type round-trips: ops-/// serializes it onto the RPC boundary and the embed facade deserializes it-/// back on the other side. An output-only derive compiles until the facade-/// tries to read it.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-#[serde(rename_all = "camelCase")]-pub struct MedullaStatus {- /// True when a base URL and a session token are both available.- pub configured: bool,- /// The resolved base URL, when one is configured.- ///- /// Safe to surface: it is an operator-supplied endpoint, never a credential.- #[serde(skip_serializing_if = "Option::is_none")]- pub base_url: Option<String>,- /// Whether a session token was resolved. The token itself is never returned.- pub has_session_token: bool,- /// Stable reason discriminator when `configured` is false.- #[serde(skip_serializing_if = "Option::is_none")]- pub reason: Option<String>,-}--/// Report integration readiness without making a network call.-///-/// Deliberately infallible: "not configured" is a state to render, not an error-/// to raise, and a host polls this to decide whether to show the surface at all.-pub async fn status(config: &Config) -> Result<RpcOutcome<MedullaStatus>, String> {- let base = resolve::base_url(config);- let status = match resolve::client(config) {- Ok(_) => MedullaStatus {- configured: true,- base_url: base,- has_session_token: true,- reason: None,- },- Err(reason) => MedullaStatus {- configured: false,- has_session_token: !matches!(reason, NotConfigured::NoSessionToken),- base_url: base,- reason: Some(reason.kind().to_string()),- },- };- log::debug!(- "[medulla] status configured={} reason={:?}",- status.configured,- status.reason- );- Ok(RpcOutcome::new(status, Vec::new()))-}--/// List the operator's durable sessions.-pub async fn list_sessions(config: &Config) -> Result<RpcOutcome<Vec<SessionSummary>>, String> {- let client = resolved(config)?;- let sessions = call(client.list_sessions().await, "medulla_list_sessions")?;- log::debug!("[medulla] list_sessions count={}", sessions.len());- Ok(RpcOutcome::new(sessions, Vec::new()))-}--/// Create a durable session.-///-/// `title` is optional; the backend names an untitled session itself rather-/// than this host inventing one.-pub async fn create_session(- config: &Config,- title: Option<&str>,-) -> Result<RpcOutcome<SessionCreated>, String> {- let client = resolved(config)?;- let created = call(client.create_session(title).await, "medulla_create_session")?;- log::debug!("[medulla] create_session id={}", created.session_id);- Ok(RpcOutcome::new(created, Vec::new()))-}--/// Fetch one session's state.-pub async fn get_session(- config: &Config,- session_id: &str,-) -> Result<RpcOutcome<SessionDetail>, String> {- let client = resolved(config)?;- let detail = call(client.get_session(session_id).await, "medulla_get_session")?;- Ok(RpcOutcome::new(detail, Vec::new()))-}--/// Send a message to a session.-///-/// `sync = false` returns as soon as the backend accepts the turn; `true`-/// blocks until it replies. The caller chooses, because a TUI wants the former-/// (so it can render streaming progress) while a scripted client wants the-/// latter.-pub async fn send_message(- config: &Config,- session_id: &str,- body: &str,- sync: bool,-) -> Result<RpcOutcome<SendResult>, String> {- let client = resolved(config)?;- let result = call(- client.send_message(session_id, body, sync).await,- "medulla_send_message",- )?;- log::debug!(- "[medulla] send_message session={session_id} sync={sync} cycle={} seq={}",- result.cycle_id,- result.seq- );- Ok(RpcOutcome::new(result, Vec::new()))-}--/// Abort a session's running cycle.-pub async fn abort(config: &Config, session_id: &str) -> Result<RpcOutcome<AbortResult>, String> {- let client = resolved(config)?;- let result = call(client.abort(session_id).await, "medulla_abort")?;- log::debug!(- "[medulla] abort session={session_id} aborted={}",- result.aborted- );- Ok(RpcOutcome::new(result, Vec::new()))-}--/// Replay a session's messages after `after`.-///-/// `after` is a cursor, not a page offset: passing the last seq already seen-/// returns only what is new, which is what makes a reconnect cheap.-pub async fn list_messages(- config: &Config,- session_id: &str,- after: Option<i64>,-) -> Result<RpcOutcome<Vec<Message>>, String> {- let client = resolved(config)?;- let messages = call(- client.list_messages(session_id, after).await,- "medulla_list_messages",- )?;- log::debug!(- "[medulla] list_messages session={session_id} after={after:?} count={}",- messages.len()- );- Ok(RpcOutcome::new(messages, Vec::new()))-}--/// Replay a session's events after `after`.-///-/// Same cursor semantics as [`list_messages`].-pub async fn list_events(- config: &Config,- session_id: &str,- after: Option<i64>,-) -> Result<RpcOutcome<Vec<WireEventEnvelope>>, String> {- let client = resolved(config)?;- let events = call(- client.list_events(session_id, after).await,- "medulla_list_events",- )?;- log::debug!(- "[medulla] list_events session={session_id} after={after:?} count={}",- events.len()- );- Ok(RpcOutcome::new(events, Vec::new()))-}--/// Read the connected worker roster.-pub async fn roster(config: &Config) -> Result<RpcOutcome<Vec<RosterWorker>>, String> {- let client = resolved(config)?;- let workers = call(client.roster().await, "medulla_roster")?;- log::debug!("[medulla] roster count={}", workers.len());- Ok(RpcOutcome::new(workers, Vec::new()))-}--/// Resolve a client, mapping "not configured" to a structured error.-///-/// Both reasons are flagged `expected_user_state`: a signed-out or unconfigured-/// host is a state the operator can fix, not an internal fault, so the RPC-/// boundary suppresses Sentry for them.-fn resolved(config: &Config) -> Result<MedullaClient, String> {- resolve::client(config).map_err(|reason| {- StructuredRpcError {- message: reason.message().to_string(),- data: Some(serde_json::json!({ "kind": reason.kind() })),- expected_user_state: true,- }- .encode()- })-}--/// Map a client error into a structured RPC error.-///-/// The backend's own `errorCode` becomes `data.kind` when present, so a host-/// branches on the backend's vocabulary rather than on prose. HTTP 401/403 are-/// marked `expected_user_state` — an expired session is a sign-in prompt, not a-/// bug report.-fn call<T>(result: Result<T, ClientError>, method: &'static str) -> Result<T, String> {- result.map_err(|err| {- let (kind, status, expected) = match &err {- ClientError::Api {- status, error_code, ..- } => {- let expected = matches!(status, Some(401) | Some(403));- (error_code.clone(), *status, expected)- }- _ => (None, None, false),- };- log::debug!("[medulla] rpc_failed method={method} status={status:?} kind={kind:?}");- StructuredRpcError {- message: err.to_string(),- data: Some(serde_json::json!({- "kind": kind.unwrap_or_else(|| "MedullaRequestFailed".to_string()),- "status": status,- })),- expected_user_state: expected,- }- .encode()- })-}--#[cfg(test)]-#[path = "ops_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/medulla/ops_tests.rs b/crates/openhuman-core/src/medulla/ops_tests.rsdeleted file mode 100644index 044111a139..0000000000--- a/crates/openhuman-core/src/medulla/ops_tests.rs+++ /dev/null@@ -1,149 +0,0 @@-use super::*;--/// RAII guard to snapshot and restore a process-global environment variable.-struct EnvGuard {- key: &'static str,- prev: Option<String>,-}--impl EnvGuard {- fn remove(key: &'static str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds ENV_LOCK guard.- unsafe { std::env::remove_var(key) };- Self { key, prev }- }-}--impl Drop for EnvGuard {- fn drop(&mut self) {- match &self.prev {- // SAFETY: caller's ENV_LOCK guard is still alive during drop.- Some(v) => unsafe { std::env::set_var(self.key, v) },- None => unsafe { std::env::remove_var(self.key) },- }- }-}--/// Serialize env mutation via the crate-wide backend env lock: these-/// tests remove `BACKEND_URL`/`VITE_BACKEND_URL`, which `api::config`-/// and `core::cli_tests` tests concurrently set — a module-local lock-/// cannot prevent that cross-module race (it deterministically broke-/// these assertions under the full-suite coverage lane).-fn env_lock() -> std::sync::MutexGuard<'static, ()> {- crate::api::config::backend_env_test_lock()-}--/// A config whose workspace is an empty temp dir, so `get_session_token`-/// deterministically finds nothing regardless of the developer's real-/// sign-in state.-fn signed_out_config(tmp: &tempfile::TempDir) -> Config {- Config {- workspace_dir: tmp.path().join("workspace"),- ..Config::default()- }-}--/// Clearing every base-URL env var no longer produces `MedullaNoBaseUrl`.-///-/// Since #5245 `resolve::base_url` falls back to-/// `effective_backend_api_url`, which ends at the compiled-in-/// `DEFAULT_API_BASE_URL` — so it never returns `None` and the-/// `NoBaseUrl` arm is unreachable. "No backend configured" stopped being a-/// state the product can be in; the unconfigured state that remains is-/// "signed out", which is what this now pins. The env isolation is kept-/// because it is what proves the fallback, rather than an override, is-/// answering.-#[test]-fn not_configured_encodes_an_expected_user_state_envelope() {- let tmp = tempfile::tempdir().unwrap();- let config = signed_out_config(&tmp);- // Isolate environment to ensure BACKEND_URL and VITE_BACKEND_URL do not- // provide a fallback through effective_backend_api_url.- let _guard = env_lock();- let _env_medulla = EnvGuard::remove(resolve::MEDULLA_BASE_URL_ENV);- let _env_backend = EnvGuard::remove("BACKEND_URL");- let _env_vite = EnvGuard::remove("VITE_BACKEND_URL");- let err = resolved(&config).expect_err("must not resolve");- let decoded = StructuredRpcError::decode(&err).expect("structured envelope");- assert!(- decoded.expected_user_state,- "an unconfigured host is a user state, not an internal fault"- );- // With every override cleared, `base_url` still resolves to the hosted- // backend default by design (`resolve.rs`'s- // `an_unconfigured_install_falls_back_to_the_hosted_backend` pins- // that), so `MedullaNoBaseUrl` is unreachable from a cleared env — the- // unconfigured state actually produced is the missing session token- // (signed out).- assert_eq!(- decoded- .data- .and_then(|d| d["kind"].as_str().map(String::from)),- Some("MedullaNoSessionToken".to_string())- );-}--#[test]-fn api_error_preserves_the_backend_error_code_as_kind() {- let err = call::<()>(- Err(ClientError::Api {- status: Some(409),- message: "already archived".into(),- error_code: Some("SessionArchived".into()),- details: None,- }),- "medulla_test",- )- .expect_err("must be an error");- let decoded = StructuredRpcError::decode(&err).expect("structured envelope");- assert_eq!(decoded.data.unwrap()["kind"], "SessionArchived");- assert!(!decoded.expected_user_state, "409 is not a sign-in prompt");-}--#[test]-fn unauthorized_is_marked_expected_user_state() {- for status in [401, 403] {- let err = call::<()>(- Err(ClientError::Api {- status: Some(status),- message: "nope".into(),- error_code: None,- details: None,- }),- "medulla_test",- )- .expect_err("must be an error");- let decoded = StructuredRpcError::decode(&err).expect("structured envelope");- assert!(- decoded.expected_user_state,- "{status} should read as a sign-in prompt, not a bug"- );- }-}--#[test]-fn missing_error_code_falls_back_to_a_stable_kind() {- let err = call::<()>(Err(ClientError::Decode("bad json".into())), "medulla_test")- .expect_err("must be an error");- let decoded = StructuredRpcError::decode(&err).expect("structured envelope");- assert_eq!(decoded.data.unwrap()["kind"], "MedullaRequestFailed");-}--#[tokio::test]-async fn status_reports_unconfigured_rather_than_failing() {- let tmp = tempfile::tempdir().unwrap();- let config = signed_out_config(&tmp);- // Isolate environment to ensure BACKEND_URL and VITE_BACKEND_URL do not- // provide a fallback through effective_backend_api_url.- let _guard = env_lock();- let _env_medulla = EnvGuard::remove(resolve::MEDULLA_BASE_URL_ENV);- let _env_backend = EnvGuard::remove("BACKEND_URL");- let _env_vite = EnvGuard::remove("VITE_BACKEND_URL");- let out = status(&config).await.expect("status never errors");- assert!(!out.value.configured);- // See `not_configured_encodes_an_expected_user_state_envelope`: the- // base URL always falls back to the hosted default, so the reason a- // cleared env reports is the missing session token, never NoBaseUrl.- assert_eq!(out.value.reason.as_deref(), Some("MedullaNoSessionToken"));-}diff --git a/crates/openhuman-core/src/medulla/resolve.rs b/crates/openhuman-core/src/medulla/resolve.rsdeleted file mode 100644index 829a6c8d51..0000000000--- a/crates/openhuman-core/src/medulla/resolve.rs+++ /dev/null@@ -1,128 +0,0 @@-//! Resolve a configured [`MedullaClient`] from ambient config and credentials.-//!-//! # Why there is no `[medulla]` config section-//!-//! There does not need to be one. The Medulla orchestration API and the-//! OpenHuman backend are the **same deployment**, so `api_url` already-//! addresses it and the existing session token already authenticates against-//! it. A separate `[medulla]` section would be a second source of truth for one-//! endpoint and one credential — exactly the drift this migration exists to-//! remove.-//!-//! `OPENHUMAN_MEDULLA_BASE_URL` remains as an override for pointing a-//! development host at a different Medulla deployment than its OpenHuman one.-//! Unset — the normal case — everything resolves through-//! [`effective_backend_api_url`], the same chain every other hosted-backend-//! call uses: `api_url`, then the `BACKEND_URL` keys, then the prod or staging-//! default selected by `OPENHUMAN_APP_ENV`. Resolving from the raw `api_url`-//! instead would leave Medulla as the one backend surface with no default,-//! reporting itself unconfigured on an install where every other call works.--use crate::api::config::effective_backend_api_url;-use crate::config::Config;-use crate::security::credentials::session_support::get_session_token;--use super::client::MedullaClient;--/// Environment override for the Medulla backend base URL.-pub const MEDULLA_BASE_URL_ENV: &str = "OPENHUMAN_MEDULLA_BASE_URL";--/// Why a Medulla client could not be built.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum NotConfigured {- /// Neither the env override nor `api_url` yielded a base URL.- NoBaseUrl,- /// No session token is available — the user is signed out.- NoSessionToken,-}--impl NotConfigured {- /// A message safe to surface to an operator.- ///- /// Deliberately free of URLs and tokens: this text reaches logs and the RPC- /// error channel.- pub fn message(&self) -> &'static str {- match self {- NotConfigured::NoBaseUrl => {- "no Medulla backend configured; set OPENHUMAN_MEDULLA_BASE_URL or api_url"- }- NotConfigured::NoSessionToken => "not signed in; no session token available",- }- }-- /// Stable discriminator for the structured RPC error `data.kind`.- pub fn kind(&self) -> &'static str {- match self {- NotConfigured::NoBaseUrl => "MedullaNoBaseUrl",- NotConfigured::NoSessionToken => "MedullaNoSessionToken",- }- }-}--/// The configured base URL, if any.-///-/// Precedence: `OPENHUMAN_MEDULLA_BASE_URL`, then whatever every other-/// hosted-backend call resolves to — [`effective_backend_api_url`], which-/// applies `config.api_url`, the `BACKEND_URL` env/compile-time keys, and-/// finally the environment-aware default (prod or staging by-/// `OPENHUMAN_APP_ENV`).-///-/// Reading `config.api_url` directly, as this used to, made Medulla the one-/// hosted-backend surface with no default: an install that had never written an-/// explicit `api_url` — the normal case, since every other call falls through-/// to the default — reported "no Medulla backend configured" while auth,-/// billing and integrations all worked. Same deployment, so it resolves the-/// same way. It also inherits the local-AI guard for free: a user whose-/// `api_url` points at Ollama gets the hosted backend here rather than a-/// Medulla client aimed at a model runner.-///-/// Empty or whitespace-only values count as unset, so an exported-but-blank env-/// var does not shadow a working config value.-pub fn base_url(config: &Config) -> Option<String> {- let from_env = std::env::var(MEDULLA_BASE_URL_ENV)- .ok()- .filter(|v| !v.trim().is_empty());-- let source_ident = if from_env.is_some() {- "env_override"- } else {- "effective_backend_api_url"- };- log::debug!(- "[medulla] base_url source={} (URL redacted for security)",- source_ident- );-- from_env- .or_else(|| Some(effective_backend_api_url(&config.api_url)))- .map(|v| v.trim().trim_end_matches('/').to_string())- .filter(|v| !v.is_empty())-}--/// Build a client from ambient config + credentials.-///-/// Returns [`NotConfigured`] rather than an opaque error so callers can tell-/// "signed out" (an expected user state the host should render as a notice)-/// from "misconfigured".-pub fn client(config: &Config) -> Result<MedullaClient, NotConfigured> {- let Some(base) = base_url(config) else {- log::debug!("[medulla] resolve_client outcome=no_base_url");- return Err(NotConfigured::NoBaseUrl);- };-- let token = get_session_token(config)- .ok()- .flatten()- .filter(|t| !t.trim().is_empty());- let Some(token) = token else {- log::debug!("[medulla] resolve_client outcome=no_session_token");- return Err(NotConfigured::NoSessionToken);- };-- log::debug!("[medulla] resolve_client outcome=ok");- Ok(MedullaClient::new(base, token))-}--#[cfg(test)]-#[path = "resolve_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/medulla/resolve_tests.rs b/crates/openhuman-core/src/medulla/resolve_tests.rsdeleted file mode 100644index e91bcb8f4a..0000000000--- a/crates/openhuman-core/src/medulla/resolve_tests.rs+++ /dev/null@@ -1,124 +0,0 @@-use super::*;--/// Serialize env mutation via the crate-wide backend env lock:-/// `base_url` reads process-globals that `api::config`, `core::cli_tests`,-/// and `medulla::ops` tests also mutate — a module-local lock cannot-/// prevent that cross-module race.-fn env_lock() -> std::sync::MutexGuard<'static, ()> {- crate::api::config::backend_env_test_lock()-}--/// RAII guard to snapshot and restore a process-global environment variable.-struct EnvGuard {- key: &'static str,- prev: Option<String>,-}--impl EnvGuard {- fn set(key: &'static str, val: &str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds ENV_LOCK guard.- unsafe { std::env::set_var(key, val) };- Self { key, prev }- }-- fn remove(key: &'static str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds ENV_LOCK guard.- unsafe { std::env::remove_var(key) };- Self { key, prev }- }-}--impl Drop for EnvGuard {- fn drop(&mut self) {- match &self.prev {- // SAFETY: caller's ENV_LOCK guard is still alive during drop.- Some(v) => unsafe { std::env::set_var(self.key, v) },- None => unsafe { std::env::remove_var(self.key) },- }- }-}--fn config_with_api_url(url: Option<&str>) -> Config {- let mut config = Config::default();- config.api_url = url.map(str::to_string);- config-}--#[test]-fn env_override_wins_over_api_url() {- let _guard = env_lock();- let _env = EnvGuard::set(MEDULLA_BASE_URL_ENV, "https://medulla.example");- let resolved = base_url(&config_with_api_url(Some("https://api.example")));- assert_eq!(resolved.as_deref(), Some("https://medulla.example"));-}--#[test]-fn falls_back_to_api_url_when_env_unset() {- let _guard = env_lock();- let _env = EnvGuard::remove(MEDULLA_BASE_URL_ENV);- let resolved = base_url(&config_with_api_url(Some("https://api.example/")));- assert_eq!(resolved.as_deref(), Some("https://api.example"));-}--#[test]-fn blank_env_does_not_shadow_api_url() {- // An exported-but-empty var is a common shell accident; treating it as- // "configured" would break an otherwise-working setup.- let _guard = env_lock();- let _env = EnvGuard::set(MEDULLA_BASE_URL_ENV, " ");- let resolved = base_url(&config_with_api_url(Some("https://api.example")));- assert_eq!(resolved.as_deref(), Some("https://api.example"));-}--#[test]-fn an_unconfigured_install_falls_back_to_the_hosted_backend() {- // Medulla and the OpenHuman backend are one deployment, so an install- // that never wrote an explicit `api_url` — the normal case — must reach- // the same host every other backend call defaults to, not report itself- // unconfigured while auth and billing work.- let _guard = env_lock();- let _env_medulla = EnvGuard::remove(MEDULLA_BASE_URL_ENV);- let _env_backend = EnvGuard::remove("BACKEND_URL");- let _env_vite = EnvGuard::remove("VITE_BACKEND_URL");- assert_eq!(- base_url(&config_with_api_url(None)),- Some(crate::api::config::effective_backend_api_url(&None))- );-}--#[test]-fn a_local_model_runner_url_does_not_become_the_medulla_host() {- // `api_url` doubles as the inference endpoint. Pointing it at Ollama- // must not aim the Medulla client at a model runner that 404s every- // path it speaks — the same guard every other backend call gets.- let _guard = env_lock();- let _env_medulla = EnvGuard::remove(MEDULLA_BASE_URL_ENV);- let _env_backend = EnvGuard::remove("BACKEND_URL");- let _env_vite = EnvGuard::remove("VITE_BACKEND_URL");- let resolved = base_url(&config_with_api_url(Some("http://localhost:11434")));- // Assert that the local model runner URL does not become the Medulla host;- // instead, it falls back to the effective backend URL (same as all other backend calls).- assert_eq!(- resolved,- Some(crate::api::config::effective_backend_api_url(&None))- );-}--#[test]-fn trailing_slashes_are_trimmed_so_paths_do_not_double_up() {- let _guard = env_lock();- let _env = EnvGuard::set(MEDULLA_BASE_URL_ENV, "https://medulla.example///");- let resolved = base_url(&config_with_api_url(None));- assert_eq!(resolved.as_deref(), Some("https://medulla.example"));-}--#[test]-fn not_configured_messages_carry_no_secrets() {- for reason in [NotConfigured::NoBaseUrl, NotConfigured::NoSessionToken] {- let msg = reason.message();- assert!(!msg.contains("http"), "message must not leak a URL: {msg}");- assert!(!reason.kind().is_empty());- }-}diff --git a/crates/openhuman-core/src/medulla/schemas.rs b/crates/openhuman-core/src/medulla/schemas.rsdeleted file mode 100644index 98bd0b199b..0000000000--- a/crates/openhuman-core/src/medulla/schemas.rs+++ /dev/null@@ -1,332 +0,0 @@-//! Controller schemas for the `medulla` RPC namespace.-//!-//! Handlers delegate straight to [`super::ops`]; no business logic lives here.-//! Registered under [`DomainGroup::Medulla`](crate::core::all::DomainGroup) at-//! the single site in `crates/openhuman-core/src/core/all.rs`, so a host that switches the family off-//! sees these methods as unknown rather than as failing.--use serde::de::DeserializeOwned;-use serde::Deserialize;-use serde_json::{Map, Value};--use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};--use super::ops;--#[derive(Debug, Deserialize, Default)]-#[serde(rename_all = "camelCase")]-struct CreateSessionParams {- #[serde(default)]- title: Option<String>,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-struct SessionIdParams {- session_id: String,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-struct SendMessageParams {- session_id: String,- body: String,- /// Block until the backend replies. Defaults to false so a caller that- /// omits it gets the non-blocking behaviour a UI wants.- #[serde(default)]- sync: bool,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-struct ReplayParams {- session_id: String,- /// Replay cursor: the last seq already seen. Absent replays from the start.- #[serde(default)]- after: Option<i64>,-}--/// Every schema in the namespace, for `/schema` introspection.-pub fn all_medulla_controller_schemas() -> Vec<ControllerSchema> {- vec![- medulla_schemas("medulla_status"),- medulla_schemas("medulla_list_sessions"),- medulla_schemas("medulla_create_session"),- medulla_schemas("medulla_get_session"),- medulla_schemas("medulla_send_message"),- medulla_schemas("medulla_abort"),- medulla_schemas("medulla_list_messages"),- medulla_schemas("medulla_list_events"),- medulla_schemas("medulla_roster"),- ]-}--/// Every controller in the namespace, for dispatch.-pub fn all_medulla_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: medulla_schemas("medulla_status"),- handler: handle_status,- },- RegisteredController {- schema: medulla_schemas("medulla_list_sessions"),- handler: handle_list_sessions,- },- RegisteredController {- schema: medulla_schemas("medulla_create_session"),- handler: handle_create_session,- },- RegisteredController {- schema: medulla_schemas("medulla_get_session"),- handler: handle_get_session,- },- RegisteredController {- schema: medulla_schemas("medulla_send_message"),- handler: handle_send_message,- },- RegisteredController {- schema: medulla_schemas("medulla_abort"),- handler: handle_abort,- },- RegisteredController {- schema: medulla_schemas("medulla_list_messages"),- handler: handle_list_messages,- },- RegisteredController {- schema: medulla_schemas("medulla_list_events"),- handler: handle_list_events,- },- RegisteredController {- schema: medulla_schemas("medulla_roster"),- handler: handle_roster,- },- ]-}--/// Schema for one function in the namespace.-pub fn medulla_schemas(function: &str) -> ControllerSchema {- match function {- "medulla_status" => ControllerSchema {- namespace: "medulla",- function: "status",- description: "Whether the Medulla integration is configured and signed in. Never performs a network call.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "status",- ty: TypeSchema::Json,- comment: "Readiness: configured flag, resolved base URL, session-token presence, and a stable reason when unconfigured.",- required: true,- }],- },- "medulla_list_sessions" => ControllerSchema {- namespace: "medulla",- function: "list_sessions",- description: "List the operator's durable Medulla sessions.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "sessions",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "Session summaries ordered by the backend.",- required: true,- }],- },- "medulla_create_session" => ControllerSchema {- namespace: "medulla",- function: "create_session",- description: "Create a durable Medulla session.",- inputs: vec![FieldSchema {- name: "title",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional title. Omitted lets the backend name the session.",- required: false,- }],- outputs: vec![FieldSchema {- name: "session",- ty: TypeSchema::Json,- comment: "The created session's identifier.",- required: true,- }],- },- "medulla_get_session" => ControllerSchema {- namespace: "medulla",- function: "get_session",- description: "Fetch one session's current state.",- inputs: vec![session_id_input()],- outputs: vec![FieldSchema {- name: "session",- ty: TypeSchema::Json,- comment: "Full session detail.",- required: true,- }],- },- "medulla_send_message" => ControllerSchema {- namespace: "medulla",- function: "send_message",- description: "Send a message to a session, optionally blocking until it replies.",- inputs: vec![- session_id_input(),- FieldSchema {- name: "body",- ty: TypeSchema::String,- comment: "Message text.",- required: true,- },- FieldSchema {- name: "sync",- ty: TypeSchema::Bool,- comment: "Block until the backend replies. Defaults to false.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Cycle id and sequence, plus the reply when sync was set.",- required: true,- }],- },- "medulla_abort" => ControllerSchema {- namespace: "medulla",- function: "abort",- description: "Abort a session's running cycle.",- inputs: vec![session_id_input()],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Whether a cycle was actually aborted.",- required: true,- }],- },- "medulla_list_messages" => ControllerSchema {- namespace: "medulla",- function: "list_messages",- description: "Replay a session's messages after a sequence cursor.",- inputs: vec![session_id_input(), after_input()],- outputs: vec![FieldSchema {- name: "messages",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "Messages newer than the cursor.",- required: true,- }],- },- "medulla_list_events" => ControllerSchema {- namespace: "medulla",- function: "list_events",- description: "Replay a session's events after a sequence cursor.",- inputs: vec![session_id_input(), after_input()],- outputs: vec![FieldSchema {- name: "events",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "Sequenced events newer than the cursor.",- required: true,- }],- },- "medulla_roster" => ControllerSchema {- namespace: "medulla",- function: "roster",- description: "Read the roster of workers currently connected to the Medulla backend.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "workers",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "Connected worker entries.",- required: true,- }],- },- other => panic!("unknown medulla controller function: {other}"),- }-}--/// The session identifier every per-session method takes.-fn session_id_input() -> FieldSchema {- FieldSchema {- name: "sessionId",- ty: TypeSchema::String,- comment: "Target session identifier.",- required: true,- }-}--/// The replay cursor shared by the two list methods.-fn after_input() -> FieldSchema {- FieldSchema {- name: "after",- ty: TypeSchema::Option(Box::new(TypeSchema::I64)),- comment: "Last sequence already seen. Absent replays from the start.",- required: false,- }-}--fn handle_status(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { to_json(ops::status(&load_config().await?).await?) })-}--fn handle_list_sessions(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { to_json(ops::list_sessions(&load_config().await?).await?) })-}--fn handle_create_session(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: CreateSessionParams = deserialize_params(params)?;- to_json(ops::create_session(&load_config().await?, p.title.as_deref()).await?)- })-}--fn handle_get_session(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: SessionIdParams = deserialize_params(params)?;- to_json(ops::get_session(&load_config().await?, &p.session_id).await?)- })-}--fn handle_send_message(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: SendMessageParams = deserialize_params(params)?;- to_json(ops::send_message(&load_config().await?, &p.session_id, &p.body, p.sync).await?)- })-}--fn handle_abort(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: SessionIdParams = deserialize_params(params)?;- to_json(ops::abort(&load_config().await?, &p.session_id).await?)- })-}--fn handle_list_messages(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: ReplayParams = deserialize_params(params)?;- to_json(ops::list_messages(&load_config().await?, &p.session_id, p.after).await?)- })-}--fn handle_list_events(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p: ReplayParams = deserialize_params(params)?;- to_json(ops::list_events(&load_config().await?, &p.session_id, p.after).await?)- })-}--fn handle_roster(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { to_json(ops::roster(&load_config().await?).await?) })-}--/// Load the ambient config for a handler.-async fn load_config() -> Result<crate::config::Config, String> {- crate::config::ops::load_config_with_timeout().await-}--/// Decode a controller's params into its typed shape.-fn deserialize_params<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {- serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))-}--/// Serialize an outcome through the shared CLI-compatible envelope.-fn to_json<T: serde::Serialize>(outcome: crate::rpc::RpcOutcome<T>) -> Result<Value, String> {- outcome.into_cli_compatible_json()-}--#[cfg(test)]-#[path = "schemas_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/medulla/schemas_tests.rs b/crates/openhuman-core/src/medulla/schemas_tests.rsdeleted file mode 100644index 6ee67c6a41..0000000000--- a/crates/openhuman-core/src/medulla/schemas_tests.rs+++ /dev/null@@ -1,46 +0,0 @@-use super::*;--#[test]-fn every_declared_schema_has_a_registered_controller() {- let schemas = all_medulla_controller_schemas();- let controllers = all_medulla_registered_controllers();- assert_eq!(- schemas.len(),- controllers.len(),- "a declared schema without a handler is unreachable, and vice versa"- );- for (schema, controller) in schemas.iter().zip(controllers.iter()) {- assert_eq!(schema.namespace, controller.schema.namespace);- assert_eq!(schema.function, controller.schema.function);- }-}--#[test]-fn all_schemas_share_the_medulla_namespace() {- for schema in all_medulla_controller_schemas() {- assert_eq!(schema.namespace, "medulla");- assert!(!schema.description.is_empty());- }-}--#[test]-fn rpc_method_names_follow_the_crate_convention() {- let names: Vec<String> = all_medulla_registered_controllers()- .iter()- .map(|c| c.rpc_method_name())- .collect();- assert_eq!(- names,- vec![- "openhuman.medulla_status",- "openhuman.medulla_list_sessions",- "openhuman.medulla_create_session",- "openhuman.medulla_get_session",- "openhuman.medulla_send_message",- "openhuman.medulla_abort",- "openhuman.medulla_list_messages",- "openhuman.medulla_list_events",- "openhuman.medulla_roster",- ]- );-}diff --git a/crates/openhuman-core/src/platform/socket/README.md b/crates/openhuman-core/src/platform/socket/README.mdindex 6fbc2d1579..13e26873ed 100644--- a/crates/openhuman-core/src/platform/socket/README.md+++ b/crates/openhuman-core/src/platform/socket/README.md@@ -24,8 +24,7 @@ Persistent, Rust-native Socket.IO client to the OpenHuman backend. The `socket`| `crates/openhuman-core/src/platform/socket/token_provider.rs` | `TokenProvider` type alias + `static_token_provider`, `token_provider_from_config`, and `is_invalid_token_error` (strict double-anchor matcher). || `crates/openhuman-core/src/platform/socket/schemas.rs` | Controller schemas + RPC handlers for the `socket` namespace. || `crates/openhuman-core/src/platform/socket/types.rs` | `WsStream` alias, `ConnectionOutcome` enum, observability event-name constants; re-exports `ConnectionStatus` / `SocketState` from `crate::api::models::socket`. |-| `crates/openhuman-core/src/platform/socket/ops.rs` | RPC operations behind `schemas.rs` (`connect_with_session` and the live-socket reuse path that reinstalls the medulla workflow bridge). |-| `crates/openhuman-core/src/platform/socket/medulla/` | The Medulla harness plane: `medulla:task_*`, capability probes, and workflow round trips bound to an agent session. See [`medulla/README.md`](medulla/README.md). |+| `crates/openhuman-core/src/platform/socket/ops.rs` | RPC operations behind `schemas.rs` (`connect_with_session` and live-socket reuse). || `crates/openhuman-core/src/platform/socket/*_tests.rs` | Sibling test suites, included via `#[path]`. |## Public surface@@ -63,7 +62,6 @@ All handlers go through `require_manager()` and error with `"SocketManager not i| `tunnel:evicted` | `DevicePeerOffline` | devices || `*:message` (suffix match) | `ChannelInboundMessage { event_name, channel, message, sender, reply_target, thread_ts, raw_data }` | channels |-`medulla:task_run` / `task_send` / `task_abort` / `capabilities_request` / `workflow_request` are not published to the bus; `handle_sio_event` hands them straight to `medulla/` (see its README), and on `ready` it advertises the agent roster and workflow set through `medulla::emit_register_agents` / `medulla::workflows::emit_register_workflows`.This module is a **publisher only** — it owns no `bus.rs` / `EventHandler` impls.diff --git a/crates/openhuman-core/src/platform/socket/event_handlers.rs b/crates/openhuman-core/src/platform/socket/event_handlers.rsindex fea88ba32f..901327ddb5 100644--- a/crates/openhuman-core/src/platform/socket/event_handlers.rs+++ b/crates/openhuman-core/src/platform/socket/event_handlers.rs@@ -60,19 +60,8 @@ pub(super) fn handle_sio_event(match event_name {"ready" => {log::info!("[socket] Server ready — auth successful");- super::medulla::workflows::begin_connection_generation();*shared.status.write() = ConnectionStatus::Connected;emit_state_change(shared);- // Advertise this core's agent roster to the backend so a medulla- // operator can delegate `medulla:task_run` to a named agent. The- // backend clears the roster on socket disconnect.- super::medulla::emit_register_agents();- // Advertise the saved workflow graphs this host can be asked to run,- // so the orchestrator can name one when delegating. Same- // per-connection lifetime as the roster: rebuilt on every reconnect,- // dropped server-side on disconnect. A no-op until a host installs a- // `WorkflowBridge`.- super::medulla::workflows::emit_register_workflows();}"error" => {log::error!("[socket] Server error event: {}", data);@@ -268,88 +257,6 @@ pub(super) fn handle_sio_event(}}- // ── Medulla harness plane ────────────────────────────────────────- // A medulla operator (running in the backend) drives an openhuman agent- // session as a delegated sub-agent. See `socket::medulla`.- "medulla:task_run" => {- match serde_json::from_value::<super::medulla::payloads::TaskRun>(data) {- Ok(run) => {- log::info!(- "[socket] medulla:task_run task_id={} cycle_id={} agent_id={:?}",- run.task_id,- run.cycle_id,- run.agent_id- );- super::medulla::manager().start_task(run);- }- Err(e) => log::warn!("[socket] failed to parse medulla:task_run: {e}"),- }- }- "medulla:task_send" => {- match serde_json::from_value::<super::medulla::payloads::TaskSend>(data) {- Ok(send) => {- log::info!("[socket] medulla:task_send task_id={}", send.task_id);- super::medulla::manager().steer_task(send);- }- Err(e) => log::warn!("[socket] failed to parse medulla:task_send: {e}"),- }- }- "medulla:task_abort" => {- match serde_json::from_value::<super::medulla::payloads::TaskAbort>(data) {- Ok(abort) => {- log::info!("[socket] medulla:task_abort task_id={}", abort.task_id);- super::medulla::manager().abort_task(abort);- }- Err(e) => log::warn!("[socket] failed to parse medulla:task_abort: {e}"),- }- }- // Capability handshake. The backend waits 10s per probe, so an- // unanswered one is not a graceful degradation — it is a stall on the- // first delegation to this agent.- "medulla:capabilities_request" => {- match serde_json::from_value::<super::medulla::payloads::CapabilitiesRequest>(- data.clone(),- ) {- Ok(request) => {- log::info!(- "[socket] medulla:capabilities_request probe_id={} agent_id={}",- request.probe_id,- request.agent_id- );- super::medulla::handle_capabilities_request(request);- }- // An undecodable probe still has to be answered when it named- // itself, for the same reason a decodable one does: silence- // spends the backend's whole 10s window.- Err(e) => {- log::warn!("[socket] failed to parse medulla:capabilities_request: {e}");- super::medulla::reject_unparsed_capabilities_request(&data, &e.to_string());- }- }- }- // Workflow round trip: a read of, or an authoring turn on, this host's- // own workflow store.- "medulla:workflow_request" => {- match serde_json::from_value::<super::medulla::payloads::WorkflowRequest>(data.clone())- {- Ok(request) => {- log::info!(- "[socket] medulla:workflow_request request_id={} op={:?}",- request.request_id,- request.op- );- super::medulla::workflows::handle_workflow_request(request);- }- // An undecodable frame still has to be answered when it named- // itself: staying silent would cost the backend the op's whole- // deadline (up to ten minutes for `copilot`).- Err(e) => {- log::warn!("[socket] failed to parse medulla:workflow_request: {e}");- super::medulla::workflows::reject_unparsed_request(&data, &e.to_string());- }- }- }-// Channel inbound message — publish to event bus for ChannelInboundSubscriber_ if event_name.ends_with(":message") => {log::info!(diff --git a/crates/openhuman-core/src/platform/socket/manager.rs b/crates/openhuman-core/src/platform/socket/manager.rsindex eb1600a4ea..707dd21ce0 100644--- a/crates/openhuman-core/src/platform/socket/manager.rs+++ b/crates/openhuman-core/src/platform/socket/manager.rs@@ -456,7 +456,6 @@ impl SocketManager {/// Disconnect from the server and shut down the background loop.pub async fn disconnect(&self) -> Result<(), String> {- super::medulla::workflows::end_connection_generation();if let Some(tx) = self.shutdown_tx.lock().await.take() {let _ = tx.send(true);}diff --git a/crates/openhuman-core/src/platform/socket/manager_tests.rs b/crates/openhuman-core/src/platform/socket/manager_tests.rsindex 68decaa478..33aec777b0 100644--- a/crates/openhuman-core/src/platform/socket/manager_tests.rs+++ b/crates/openhuman-core/src/platform/socket/manager_tests.rs@@ -208,8 +208,7 @@ async fn emit_still_succeeds_after_server_error_on_live_connection() {/// mutually exclusive, an `emit` that observed `ready == true` can have its/// `tx.send` land *after* the drain — leaving a stale message in the channel/// that the next reconnect (a fresh sid whose roster the backend cleared)-/// forwards. This is the exact race `medulla::workflows::with_live_connection`-/// already guards for the medulla handlers; the bare `emit` path is closed by+/// forwards. This is the same connection race the bare `emit` path closes by/// making both critical sections take the connection's `ready` lock.////// The barrier: the test task takes the `ready` lock (standing in for teardowndiff --git a/crates/openhuman-core/src/platform/socket/medulla/README.md b/crates/openhuman-core/src/platform/socket/medulla/README.mddeleted file mode 100644index 4a586f8b11..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/README.md+++ /dev/null@@ -1,128 +0,0 @@-# socket/medulla--The Medulla **harness plane**: binds the backend's `medulla:*` Socket.IO-events to an OpenHuman agent session so a Medulla operator running in the-backend can drive this core as a delegated sub-agent, probe its capabilities,-and read or author its saved workflow graphs.--It rides the existing authenticated backend socket owned by-`crate::platform::socket::SocketManager`; transport, handshake auth, and-reconnection live there. Inbound events are dispatched from-`crates/openhuman-core/src/platform/socket/event_handlers.rs`; outbound events-go through `global_socket_manager().emit`.--Not to be confused with `crates/openhuman-core/src/medulla/`, which is-OpenHuman as a Medulla **client** (HTTP/SSE to the Medulla backend). This-directory is the opposite direction: OpenHuman as a Medulla **worker**. One-binary can be both.--## Key files--| File | Role |-| --- | --- |-| `crates/openhuman-core/src/platform/socket/medulla/mod.rs` | `MedullaTaskManager` (`start_task` / `steer_task` / `abort_task` / `abort_all`), the per-task driver, `emit_register_agents`, `handle_capabilities_request`, and the `emit` helpers. |-| `crates/openhuman-core/src/platform/socket/medulla/payloads.rs` | Serde wire types for every event (camelCase on the wire) and the `EVENT_*` name constants. |-| `crates/openhuman-core/src/platform/socket/medulla/envelope.rs` | `HarnessEnvelope` / `HarnessEventKind` and `progress_to_event_kind`, mapping `AgentProgress` onto the Medulla harness envelope (`tinyplace.harness.session.v2`). |-| `crates/openhuman-core/src/platform/socket/medulla/workflows.rs` | The workflow plane: the host-supplied `WorkflowBridge` trait, `set_workflow_bridge` / `clear_workflow_bridge`, `emit_register_workflows`, `handle_workflow_request`, and the bridge/connection generation tokens. |-| `*_tests.rs` | Sibling test suites, included via `#[path]`. |--## Protocol--Down (backend → OpenHuman), matched by name in `event_handlers::handle_sio_event`:--| Event | Payload | Handler |-| --- | --- | --- |-| `medulla:task_run` | `TaskRun { task_id, cycle_id, session_id?, instruction, agent_id?, timeout_ms }` | `MedullaTaskManager::start_task` |-| `medulla:task_send` | `TaskSend { task_id, input }` | `MedullaTaskManager::steer_task` |-| `medulla:task_abort` | `TaskAbort { task_id }` | `MedullaTaskManager::abort_task` |-| `medulla:capabilities_request` | `CapabilitiesRequest { probe_id, agent_id }` | `handle_capabilities_request` |-| `medulla:workflow_request` | `WorkflowRequest { request_id, op, workflow_id?, kind?, instruction?, agent_id? }` | `workflows::handle_workflow_request` |--Up (OpenHuman → backend):--| Event | Payload | When |-| --- | --- | --- |-| `medulla:task_envelope` | `TaskEnvelope { task_id, envelope }` | Each mapped `AgentProgress` item during a task, plus terminal error envelopes. |-| `medulla:task_result` | `TaskResult { task_id, ok, reply, usage?, error? }` | Once per task, always. |-| `medulla:register_agents` | `RegisterAgents { agents }` | On every socket `ready` (`agent::registry::default_agents`); the backend drops the roster on disconnect. |-| `medulla:register_workflows` | `RegisterWorkflows` | On every `ready` and whenever a `WorkflowBridge` is (re)installed or the flows store changes; same lifetime as the roster. |-| `medulla:capabilities_result` | `CapabilitiesResult { probe_id, capabilities }` | Answer to a probe: `ready`, `summary`, `cwd` (bridge `action_dir`), advertised `workflows`. |-| `medulla:workflow_result` | `WorkflowResult { request_id, ok, data?, error? }` | Answer to a workflow round trip, `ok: false` with a readable message on any failure. |--Every down event is request/response against a server-side deadline (ten-seconds for a probe or workflow read, ten minutes for a `copilot` turn), so-silence is never free. Both request handlers always reply, even when the-answer is an error: an undecodable `capabilities_request` or-`workflow_request` is answered from the raw `probeId` / `requestId` via-`reject_unparsed_capabilities_request` / `workflows::reject_unparsed_request`.-The only path that stays silent is a socket that is already gone, which the-server handles by retiring the waiter on disconnect.--## Task lifecycle--`start_task` registers the task (a latching `CancellationToken` for abort and-an unbounded steering channel) and spawns `drive`:--1. `build_agent` loads config, initialises `AgentDefinitionRegistry`, builds- `Agent::from_config_for_agent(agent_id)` (default `orchestrator`), tags- the event context `medulla:<task_id>` / `medulla_harness`, and refreshes- integrations and delegation tools. A build failure still emits a fatal- error envelope and a `task_result { ok: false }`.-2. `timeout_ms` is one wall-clock budget for the whole task, not per turn.- Each turn runs `agent.run_single` under `AgentTurnOrigin::ExternalChannel- { channel: "medulla_harness", reply_target: task_id }`, raced (`biased`)- against the abort token and the remaining budget.-3. A forwarder task maps `AgentProgress` to envelopes with a monotonically- increasing `seq`; `TurnStarted` / `IterationStarted` / `TurnCompleted`- become `status`, text and thinking deltas become `agent_message` /- `agent_thinking`, tool calls become `tool_call` / `tool_result`, and- `SubagentAwaitingUser` becomes `approval_request`. Unmapped variants are- dropped.-4. After a completed turn, steering input already queued (or arriving within- `STEER_DRAIN_GRACE`, 50 ms) runs as a follow-up turn on the same session;- otherwise the task settles with the reply and `take_last_turn_usage_totals`.-5. Abort, timeout, and turn errors settle as `ok: false` with `error` =- `"aborted"` / `"timeout"` / the error text; timeout and error also emit a- fatal `error` envelope first.--A `task_run` for an already-running `task_id` is ignored; `task_send` and-`task_abort` for unknown ids are logged and dropped.--## Workflow plane--`WorkflowBridge` is the store side, supplied by the host at startup so this-module never parses a graph, node, or config field; graphs, node-kind-catalogs, and run lists cross as opaque `serde_json::Value`. OpenHuman-installs `crates/openhuman-core/src/flows/medulla_bridge.rs`-(`FlowsWorkflowBridge` over the SQLite flows store) from-`core/runtime/services.rs` at boot and again on the-`socket.connect_with_session` path (`platform/socket/ops.rs`); `flows` also-re-advertises on store changes. Synchronous reads (`get`, `node_kinds`,-`runs`) run on a blocking thread; `copilot` is async because it is a whole-authoring turn, and its outcome is derived from a re-read of the store rather-than the model's claim.--Two cancellation generations guard stale work: a bridge generation (rotated by-`set_workflow_bridge` / `clear_workflow_bridge`) and a connection generation-(begun on `ready`, ended on disconnect), so a registration, probe, or request-spawned against an old bridge or a closed socket is discarded instead of-answered on the wrong connection. `emit_register_workflows` also sequences-its reads so a slower, older snapshot never overwrites a newer advert.--## Dependencies--- `crate::agent::{Agent, progress::AgentProgress, turn_origin, registry, harness::AgentDefinitionRegistry}`-- `crate::platform::socket::{global_socket_manager, SocketManager}` for emits-- `crate::config::rpc::load_config_with_timeout` when building a task agent-- `tokio_util::sync::CancellationToken`, `parking_lot`, `futures` (panic- isolation around bridge methods)--## Used by--- `crates/openhuman-core/src/platform/socket/event_handlers.rs` — dispatches- every down event and calls `emit_register_agents` /- `emit_register_workflows` on `ready`.-- `crates/openhuman-core/src/platform/socket/manager.rs` — ends the- connection generation on disconnect.-- `crates/openhuman-core/src/flows/medulla_bridge.rs` and- `flows/ops/definitions.rs` — install the bridge and re-advertise workflows.diff --git a/crates/openhuman-core/src/platform/socket/medulla/envelope.rs b/crates/openhuman-core/src/platform/socket/medulla/envelope.rsdeleted file mode 100644index a92cfe9633..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/envelope.rs+++ /dev/null@@ -1,381 +0,0 @@-//! Maps the agent's per-turn [`AgentProgress`] stream onto Medulla's native-//! harness-event envelope.--use serde::{Deserialize, Serialize};--use crate::agent::progress::AgentProgress;--// The backend validates this discriminator. Keep the established v2 wire value-// even though the Rust types are now owned here instead of by the retired-// TinyPlace crate.-const MEDULLA_ENVELOPE_VERSION: &str = "tinyplace.harness.session.v2";--pub type HarnessBucketUnit = String;-pub type HarnessProvider = String;-pub type HarnessEnvelopeScope = String;-pub type HarnessEventRole = String;--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessBucket {- #[serde(default)]- pub unit: HarnessBucketUnit,- #[serde(default)]- pub start: String,- #[serde(default)]- pub end: String,-}--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessInfo {- #[serde(default)]- pub provider: HarnessProvider,- #[serde(default)]- pub command: String,- #[serde(default)]- pub argv: Vec<String>,-}--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessSource {- #[serde(default)]- pub path: String,- #[serde(default)]- pub record_type: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub source_role: Option<String>,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct UserPromptPayload {- #[serde(default)]- pub text: String,- #[serde(default)]- pub source: String,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct TextPayload {- #[serde(default)]- pub text: String,-}--#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]-pub struct ToolCallPayload {- #[serde(default)]- pub call_id: String,- #[serde(default)]- pub tool_name: String,- #[serde(default)]- pub tool_kind: String,- #[serde(default)]- pub display: String,- #[serde(default)]- pub input: serde_json::Value,-}--#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]-pub struct ToolResultPayload {- #[serde(default)]- pub call_id: String,- #[serde(default)]- pub ok: bool,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub exit_code: Option<i64>,- #[serde(default)]- pub is_error: bool,- #[serde(default)]- pub output: String,- #[serde(default)]- pub output_bytes: i64,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct ApprovalRequestPayload {- #[serde(default, skip_serializing_if = "Option::is_none")]- pub call_id: Option<String>,- #[serde(default)]- pub tool_name: String,- #[serde(default)]- pub display: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub reason: Option<String>,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct StatusPayload {- #[serde(default)]- pub state: String,- #[serde(default)]- pub detail: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub active_call_id: Option<String>,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct LifecyclePayload {- #[serde(default)]- pub phase: String,-}--#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct ErrorPayload {- #[serde(default)]- pub message: String,- #[serde(default)]- pub fatal: bool,-}--#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]-pub struct UnknownPayload {- #[serde(default)]- pub raw: serde_json::Value,-}--#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(tag = "kind", content = "payload", rename_all = "snake_case")]-pub enum HarnessEventKind {- UserPrompt(UserPromptPayload),- AgentMessage(TextPayload),- AgentThinking(TextPayload),- ToolCall(ToolCallPayload),- ToolResult(ToolResultPayload),- ApprovalRequest(ApprovalRequestPayload),- Status(StatusPayload),- Lifecycle(LifecyclePayload),- Error(ErrorPayload),- Unknown(UnknownPayload),-}--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessScope {- #[serde(rename = "type", default)]- pub scope_type: HarnessEnvelopeScope,- #[serde(default)]- pub key: String,- #[serde(default)]- pub cwd: String,- #[serde(default)]- pub wrapper_session_id: String,- #[serde(default)]- pub harness_session_id: String,-}--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessEvent {- #[serde(default)]- pub id: String,- #[serde(default)]- pub seq: i64,- #[serde(default)]- pub ts: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub turn_id: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub model: Option<String>,- #[serde(default)]- pub role: HarnessEventRole,- #[serde(default)]- pub kind: String,- #[serde(default)]- pub payload: serde_json::Value,-}--impl HarnessEvent {- pub fn decoded(&self) -> HarnessEventKind {- serde_json::from_value(serde_json::json!({- "kind": self.kind,- "payload": self.payload,- }))- .unwrap_or_else(|_| {- HarnessEventKind::Unknown(UnknownPayload {- raw: self.payload.clone(),- })- })- }-}--#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct HarnessEnvelope {- #[serde(default)]- pub envelope_version: String,- #[serde(default)]- pub version: u32,- #[serde(default)]- pub bucket: HarnessBucket,- #[serde(default)]- pub scope: HarnessScope,- #[serde(default)]- pub harness: HarnessInfo,- #[serde(default)]- pub event: HarnessEvent,- #[serde(default)]- pub source: HarnessSource,-}--impl HarnessEnvelope {- pub fn is_valid(&self) -> bool {- self.envelope_version == MEDULLA_ENVELOPE_VERSION- && !self.scope.harness_session_id.is_empty()- }-- pub fn parse(body: &str) -> Option<Self> {- let envelope: Self = serde_json::from_str(body).ok()?;- envelope.is_valid().then_some(envelope)- }-}--/// `role` stamped on every openhuman-produced event: these are agent-side-/// stream frames (`owner` is reserved for `user_prompt`, which the agent never-/// emits about itself).-const AGENT_ROLE: &str = "agent";--/// Translate one [`AgentProgress`] event into a typed v2 event kind.-///-/// Returns `None` for progress variants that carry no user-facing stream frame-/// (cost rollups, per-call token accounting, arg-delta fragments, …) so the-/// forwarded stream stays close to the `agent_message / agent_thinking /-/// tool_call / tool_result / status / approval_request / error` vocabulary the-/// spec enumerates.-pub fn progress_to_event_kind(progress: &AgentProgress) -> Option<HarnessEventKind> {- let kind = match progress {- AgentProgress::TurnStarted => HarnessEventKind::Status(StatusPayload {- state: "running".to_string(),- detail: "turn started".to_string(),- active_call_id: None,- }),- AgentProgress::IterationStarted {- iteration,- max_iterations,- } => HarnessEventKind::Status(StatusPayload {- state: "running".to_string(),- detail: format!("iteration {iteration}/{max_iterations}"),- active_call_id: None,- }),- AgentProgress::TextDelta { delta, .. } => HarnessEventKind::AgentMessage(TextPayload {- text: delta.clone(),- }),- AgentProgress::ThinkingDelta { delta, .. } => {- HarnessEventKind::AgentThinking(TextPayload {- text: delta.clone(),- })- }- AgentProgress::ToolCallStarted {- call_id,- tool_name,- arguments,- display_label,- ..- } => HarnessEventKind::ToolCall(ToolCallPayload {- call_id: call_id.clone(),- tool_name: tool_name.clone(),- tool_kind: "other".to_string(),- display: display_label.clone().unwrap_or_else(|| tool_name.clone()),- input: arguments.clone(),- }),- AgentProgress::ToolCallCompleted {- call_id,- success,- output,- output_chars,- ..- } => HarnessEventKind::ToolResult(ToolResultPayload {- call_id: call_id.clone(),- ok: *success,- exit_code: None,- is_error: !*success,- output: output.clone(),- output_bytes: *output_chars as i64,- }),- AgentProgress::SubagentAwaitingUser {- task_id, question, ..- } => HarnessEventKind::ApprovalRequest(ApprovalRequestPayload {- call_id: Some(task_id.clone()),- tool_name: "subagent".to_string(),- display: question.clone(),- reason: None,- }),- AgentProgress::TurnCompleted { .. } => HarnessEventKind::Status(StatusPayload {- state: "idle".to_string(),- detail: "turn completed".to_string(),- active_call_id: None,- }),- // Everything else (arg deltas, cost/usage rollups, per-call model- // accounting, subagent-internal frames, todo writes, raw- // TurnContent) carries no distinct stream frame in this vocabulary.- _ => return None,- };- Some(kind)-}--/// Wrap a typed [`HarnessEventKind`] in a full [`HarnessEnvelope`] anchored to-/// `session_id`, ready to serialize into a `medulla:task_envelope` frame.-///-/// `seq` is the monotonic per-session ordering counter; `ts` is an ISO-8601-/// timestamp.-pub fn envelope_for_kind(session_id: &str, seq: i64, kind: &HarnessEventKind) -> HarnessEnvelope {- // `HarnessEventKind` is adjacently tagged (`{ "kind": .., "payload": .. }`),- // so serializing it yields exactly the `kind`/`payload` pair `HarnessEvent`- // stores — extract them rather than hand-writing the discriminator strings.- let tagged = serde_json::to_value(kind).unwrap_or_default();- let kind_str = tagged- .get("kind")- .and_then(|v| v.as_str())- .unwrap_or("unknown")- .to_string();- let payload = tagged- .get("payload")- .cloned()- .unwrap_or(serde_json::Value::Null);-- HarnessEnvelope {- envelope_version: MEDULLA_ENVELOPE_VERSION.to_string(),- version: 2,- bucket: HarnessBucket::default(),- scope: HarnessScope {- scope_type: "session".to_string(),- wrapper_session_id: session_id.to_string(),- harness_session_id: session_id.to_string(),- ..Default::default()- },- harness: HarnessInfo::default(),- event: HarnessEvent {- id: format!("{session_id}-{seq}"),- seq,- ts: chrono::Utc::now().to_rfc3339(),- role: AGENT_ROLE.to_string(),- kind: kind_str,- payload,- ..Default::default()- },- source: HarnessSource::default(),- }-}--/// Convenience: build a bare `status` envelope (used to bookend a task run).-pub fn status_envelope(session_id: &str, seq: i64, state: &str, detail: &str) -> HarnessEnvelope {- envelope_for_kind(- session_id,- seq,- &HarnessEventKind::Status(StatusPayload {- state: state.to_string(),- detail: detail.to_string(),- active_call_id: None,- }),- )-}--/// Convenience: build an `error` envelope.-pub fn error_envelope(session_id: &str, seq: i64, message: &str, fatal: bool) -> HarnessEnvelope {- envelope_for_kind(- session_id,- seq,- &HarnessEventKind::Error(ErrorPayload {- message: message.to_string(),- fatal,- }),- )-}--#[cfg(test)]-#[path = "envelope_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/platform/socket/medulla/envelope_tests.rs b/crates/openhuman-core/src/platform/socket/medulla/envelope_tests.rsdeleted file mode 100644index 3f26378d9d..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/envelope_tests.rs+++ /dev/null@@ -1,147 +0,0 @@-use super::*;--#[test]-fn maps_text_delta_to_agent_message() {- let p = AgentProgress::TextDelta {- delta: "hello".to_string(),- iteration: 1,- };- let kind = progress_to_event_kind(&p).expect("mapped");- assert!(matches!(kind, HarnessEventKind::AgentMessage(ref t) if t.text == "hello"));-}--#[test]-fn maps_thinking_delta_to_agent_thinking() {- let p = AgentProgress::ThinkingDelta {- delta: "hmm".to_string(),- iteration: 1,- };- assert!(matches!(- progress_to_event_kind(&p),- Some(HarnessEventKind::AgentThinking(_))- ));-}--#[test]-fn drops_non_stream_variants() {- let p = AgentProgress::TurnContent {- input: Some("q".to_string()),- output: Some("a".to_string()),- };- assert!(progress_to_event_kind(&p).is_none());-}--#[test]-fn envelope_is_valid_and_round_trips_through_the_wire() {- let kind = HarnessEventKind::AgentMessage(TextPayload {- text: "done".to_string(),- });- let env = envelope_for_kind("sess-1", 7, &kind);- assert!(env.is_valid());- assert_eq!(env.envelope_version, "tinyplace.harness.session.v2");- assert_eq!(env.version, 2);- assert_eq!(env.event.kind, "agent_message");- assert_eq!(env.event.seq, 7);-- // Serialize and parse back through the Medulla decoder.- let wire_value = serde_json::to_value(&env).unwrap();- assert_eq!(- wire_value["bucket"],- serde_json::json!({"unit":"","start":"","end":""})- );- assert_eq!(- wire_value["harness"],- serde_json::json!({"provider":"","command":"","argv":[]})- );- assert_eq!(- wire_value["source"],- serde_json::json!({"path":"","record_type":""})- );- assert_eq!(wire_value["scope"]["type"], "session");- assert_eq!(wire_value["event"]["kind"], "agent_message");- let wrapper = super::super::payloads::TaskEnvelope {- task_id: "task-1".to_string(),- envelope: wire_value.clone(),- };- let wrapper_wire = serde_json::to_value(wrapper).unwrap();- assert_eq!(wrapper_wire["taskId"], "task-1");- assert_eq!(wrapper_wire["envelope"], wire_value);-- let wire = serde_json::to_string(&env).unwrap();- let parsed = HarnessEnvelope::parse(&wire).expect("valid Medulla wire");- match parsed.event.decoded() {- HarnessEventKind::AgentMessage(t) => assert_eq!(t.text, "done"),- other => panic!("unexpected decoded kind: {other:?}"),- }-}--#[test]-fn established_event_tags_and_unknown_fallback_are_preserved() {- let user = serde_json::to_value(HarnessEventKind::UserPrompt(UserPromptPayload {- text: "hello".to_string(),- source: "human".to_string(),- }))- .unwrap();- assert_eq!(user["kind"], "user_prompt");- assert_eq!(user["payload"]["source"], "human");-- let lifecycle = serde_json::to_value(HarnessEventKind::Lifecycle(LifecyclePayload {- phase: "turn_end".to_string(),- }))- .unwrap();- assert_eq!(lifecycle["kind"], "lifecycle");-- let raw = serde_json::json!({"future": true});- let event = HarnessEvent {- kind: "future_kind".to_string(),- payload: raw.clone(),- ..Default::default()- };- assert!(matches!(- event.decoded(),- HarnessEventKind::Unknown(UnknownPayload { raw: value }) if value == raw- ));-}--#[test]-fn tool_call_and_result_map_to_their_kinds() {- let started = AgentProgress::ToolCallStarted {- call_id: "c1".to_string(),- tool_name: "Bash".to_string(),- arguments: serde_json::json!({ "cmd": "ls" }),- iteration: 1,- display_label: Some("List files".to_string()),- display_detail: None,- };- match progress_to_event_kind(&started) {- Some(HarnessEventKind::ToolCall(tc)) => {- assert_eq!(tc.call_id, "c1");- assert_eq!(tc.tool_name, "Bash");- assert_eq!(tc.display, "List files");- }- other => panic!("expected ToolCall, got {other:?}"),- }-- let completed = AgentProgress::ToolCallCompleted {- call_id: "c1".to_string(),- tool_name: "Bash".to_string(),- success: true,- output_chars: 3,- output: "ok\n".to_string(),- arguments: None,- elapsed_ms: 5,- iteration: 1,- failure: None,- display_label: None,- display_detail: None,- structured: None,- };- match progress_to_event_kind(&completed) {- Some(HarnessEventKind::ToolResult(tr)) => {- assert!(tr.ok);- assert!(!tr.is_error);- assert_eq!(tr.output, "ok\n");- }- other => panic!("expected ToolResult, got {other:?}"),- }-}diff --git a/crates/openhuman-core/src/platform/socket/medulla/mod.rs b/crates/openhuman-core/src/platform/socket/medulla/mod.rsdeleted file mode 100644index 6181f1b542..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/mod.rs+++ /dev/null@@ -1,685 +0,0 @@-//! Medulla "harness plane" — binds the backend's `medulla:task_*` Socket.IO-//! protocol to an OpenHuman agent session so a medulla operator (running in the-//! backend) can drive an openhuman agent as a delegated sub-agent.-//!-//! This rides the *existing* authenticated backend socket owned by-//! [`crate::platform::socket::SocketManager`] — the transport, handshake auth-//! (`socket.handshake.auth.token`), and reconnection are already handled there,-//! so this module only adds the task/envelope binding on top:-//!-//! Down (backend → openhuman), handled in [`crate::platform::socket::event_handlers`]:-//! - `medulla:task_run` → [`MedullaTaskManager::start_task`]-//! - `medulla:task_send` → [`MedullaTaskManager::steer_task`]-//! - `medulla:task_abort` → [`MedullaTaskManager::abort_task`]-//!-//! - `medulla:capabilities_request` → [`handle_capabilities_request`]-//! - `medulla:workflow_request` → [`workflows::handle_workflow_request`]-//!-//! Up (openhuman → backend):-//! - `medulla:task_envelope` — the live session stream, as-//! native Medulla harness envelopes (see [`envelope`]).-//! - `medulla:task_result` — explicit completion.-//! - `medulla:register_agents` — roster advertised on connect-//! ([`emit_register_agents`]); the backend clears it on disconnect.-//! - `medulla:register_workflows` — the saved workflow graphs this host can be-//! asked to run ([`workflows::emit_register_workflows`]), same lifetime.-//! - `medulla:capabilities_result` — the answer to a capability probe.-//! - `medulla:workflow_result` — the answer to a workflow round trip.-//!-//! Every *down* event here is request/response with a server-side deadline, so-//! silence is never free: an unanswered probe costs the backend ten seconds and-//! an unanswered workflow request up to ten minutes. Both handlers therefore-//! always reply, even when the answer is an error.--pub mod envelope;-pub mod payloads;-pub mod workflows;--use std::collections::HashMap;-use std::sync::atomic::{AtomicI64, Ordering};-use std::sync::{Arc, OnceLock};--use parking_lot::Mutex;-use tokio::sync::mpsc;-use tokio::time::{Duration, Instant};-use tokio_util::sync::CancellationToken;--use crate::agent::progress::AgentProgress;-use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};-use crate::agent::OpenHumanSessionHost;--use payloads::{- AgentDescriptor, CapabilitiesRequest, CapabilitiesResult, RegisterAgents, TaskResult,- EVENT_CAPABILITIES_RESULT, EVENT_REGISTER_AGENTS, EVENT_TASK_ENVELOPE, EVENT_TASK_RESULT,-};--/// Default agent an unspecified `medulla:task_run` runs as.-const DEFAULT_AGENT_ID: &str = "orchestrator";--/// How long we wait, after a turn settles, for a `medulla:task_send` follow-up-/// that arrived *during* the turn to be drained before declaring the task done.-/// Steering is inherently best-effort; this only catches input already queued.-const STEER_DRAIN_GRACE: Duration = Duration::from_millis(50);--// ─────────────────────────────────────────────────────────────────────────────-// Global manager-// ─────────────────────────────────────────────────────────────────────────────--static GLOBAL: OnceLock<Arc<MedullaTaskManager>> = OnceLock::new();--/// The process-wide medulla task manager (lazily created).-pub fn manager() -> &'static Arc<MedullaTaskManager> {- GLOBAL.get_or_init(|| Arc::new(MedullaTaskManager::new()))-}--/// One in-flight task: a cooperative abort signal and a steering input channel.-struct RunningTask {- /// Fired by `medulla:task_abort` to cancel the task. A- /// [`CancellationToken`] *latches*: an abort that arrives before the run- /// path starts awaiting it (e.g. while the driver is still building the- /// agent) is still observed when the turn checks it, so no cancellation is- /// lost.- abort: CancellationToken,- /// Mid-task steering input (`medulla:task_send`) delivered as follow-up- /// turns on the same agent session.- steer_tx: mpsc::UnboundedSender<String>,-}--/// Tracks the openhuman side of every medulla-driven task.-pub struct MedullaTaskManager {- tasks: Mutex<HashMap<String, RunningTask>>,-}--impl Default for MedullaTaskManager {- fn default() -> Self {- Self::new()- }-}--impl MedullaTaskManager {- pub fn new() -> Self {- Self {- tasks: Mutex::new(HashMap::new()),- }- }-- /// Handle `medulla:task_run`: register the task and spawn its driver.- pub fn start_task(self: &Arc<Self>, run: payloads::TaskRun) {- let task_id = run.task_id.clone();- if self.tasks.lock().contains_key(&task_id) {- log::warn!("[medulla] task_run for already-running task_id={task_id} — ignoring");- return;- }-- let abort = CancellationToken::new();- let (steer_tx, steer_rx) = mpsc::unbounded_channel::<String>();- self.tasks.lock().insert(- task_id.clone(),- RunningTask {- abort: abort.clone(),- steer_tx,- },- );-- let manager = Arc::clone(self);- tokio::spawn(async move {- manager.drive(run, abort, steer_rx).await;- });- }-- /// Handle `medulla:task_send`: deliver steering input into the session.- pub fn steer_task(&self, send: payloads::TaskSend) {- match self.tasks.lock().get(&send.task_id) {- Some(task) => {- if task.steer_tx.send(send.input).is_err() {- log::warn!(- "[medulla] task_send for task_id={} whose driver has exited",- send.task_id- );- }- }- None => log::warn!(- "[medulla] task_send for unknown task_id={} — dropping",- send.task_id- ),- }- }-- /// Handle `medulla:task_abort`: cancel the in-flight turn.- pub fn abort_task(&self, abort: payloads::TaskAbort) {- match self.tasks.lock().get(&abort.task_id) {- Some(task) => {- log::info!("[medulla] aborting task_id={}", abort.task_id);- task.abort.cancel();- }- None => log::warn!(- "[medulla] task_abort for unknown task_id={} — dropping",- abort.task_id- ),- }- }-- /// Abort every in-flight task (used when the backend socket drops).- pub fn abort_all(&self) {- let tasks = self.tasks.lock();- for (task_id, task) in tasks.iter() {- log::debug!("[medulla] socket down — aborting task_id={task_id}");- task.abort.cancel();- }- }-- fn finish(&self, task_id: &str) {- self.tasks.lock().remove(task_id);- }-- /// Drive a task to completion: build/resume an agent session, run the- /// instruction (plus any queued steering follow-ups) as turns, stream the- /// progress as `medulla:task_envelope` frames, and emit a terminal- /// `medulla:task_result`.- async fn drive(- &self,- run: payloads::TaskRun,- abort: CancellationToken,- mut steer_rx: mpsc::UnboundedReceiver<String>,- ) {- let task_id = run.task_id.clone();- // Session key: reuse the caller-supplied session id when resuming, else- // fall back to the task id so the envelope stream is still anchored.- let session_id = run.session_id.clone().unwrap_or_else(|| task_id.clone());- let agent_id = run- .agent_id- .clone()- .unwrap_or_else(|| DEFAULT_AGENT_ID.to_string());- let seq = Arc::new(AtomicI64::new(0));-- let mut agent = match build_agent(&agent_id, &task_id, &session_id).await {- Ok(agent) => agent,- Err(err) => {- log::error!("[medulla] task_id={task_id} failed to build agent: {err}");- emit_envelope(- &task_id,- envelope::error_envelope(&session_id, next_seq(&seq), &err, true),- );- emit_result(TaskResult {- task_id: task_id.clone(),- ok: false,- reply: String::new(),- usage: None,- error: Some(err),- });- self.finish(&task_id);- return;- }- };-- // `timeout_ms` is a hard wall-clock budget for the WHOLE task, not- // per turn: anchor a single deadline now and charge every turn- // (initial + steering follow-ups) against the time remaining until it.- let deadline =- (run.timeout_ms > 0).then(|| Instant::now() + Duration::from_millis(run.timeout_ms));- let mut next_input = run.instruction.clone();- let result;-- 'outer: loop {- // Charge this turn against the remaining task budget; if it's- // already spent, settle the whole task as timed out.- let remaining = match remaining_budget(deadline, Instant::now()) {- Ok(remaining) => remaining,- Err(()) => {- result = timeout_result(&task_id, &session_id, &seq);- break 'outer;- }- };-- let (progress_tx, progress_rx) = mpsc::channel::<AgentProgress>(256);- agent.set_on_progress(Some(progress_tx));- let forwarder = spawn_forwarder(- task_id.clone(),- session_id.clone(),- Arc::clone(&seq),- progress_rx,- );-- let origin = AgentTurnOrigin::ExternalChannel {- channel: "medulla_harness".to_string(),- sender: None,- reply_target: task_id.clone(),- message_id: uuid::Uuid::new_v4().to_string(),- };- let turn = Box::pin(with_origin(origin, agent.run_single(&next_input)));-- let turn_result = run_with_optional_timeout(remaining, &abort, turn).await;- // The forwarder ends when `progress_tx` drops; make sure it's flushed.- agent.set_on_progress(None);- let _ = forwarder.await;-- match turn_result {- TurnOutcome::Aborted => {- result = TaskResult {- task_id: task_id.clone(),- ok: false,- reply: String::new(),- usage: None,- error: Some("aborted".to_string()),- };- break 'outer;- }- TurnOutcome::TimedOut => {- result = timeout_result(&task_id, &session_id, &seq);- break 'outer;- }- TurnOutcome::Errored(err) => {- emit_envelope(- &task_id,- envelope::error_envelope(&session_id, next_seq(&seq), &err, true),- );- result = TaskResult {- task_id: task_id.clone(),- ok: false,- reply: String::new(),- usage: None,- error: Some(err),- };- break 'outer;- }- TurnOutcome::Completed(reply) => {- // Drain any steering input that arrived during the turn and,- // if present, run it as a follow-up turn on the same session.- match drain_steer(&mut steer_rx).await {- Some(next) => {- next_input = next;- continue 'outer;- }- None => {- let usage = agent.take_last_turn_usage_totals().map(usage_to_json);- result = TaskResult {- task_id: task_id.clone(),- ok: true,- reply,- usage,- error: None,- };- break 'outer;- }- }- }- }- }-- emit_result(result);- self.finish(&task_id);- }-}--/// Outcome of a single driven turn.-enum TurnOutcome {- Completed(String),- Errored(String),- Aborted,- TimedOut,-}--/// Race the agent turn against the cooperative abort signal and the remaining-/// slice of the task's wall-clock budget.-///-/// `abort` is a [`CancellationToken`], so a cancellation that landed *before*-/// this call starts polling is not lost: `cancelled()` resolves immediately for-/// an already-cancelled token, and the `biased` select settles the turn as-/// [`TurnOutcome::Aborted`] before the agent future is ever polled.-async fn run_with_optional_timeout(- remaining: Option<Duration>,- abort: &CancellationToken,- turn: std::pin::Pin<Box<impl std::future::Future<Output = anyhow::Result<String>>>>,-) -> TurnOutcome {- let run = async {- tokio::select! {- biased;- _ = abort.cancelled() => TurnOutcome::Aborted,- res = turn => match res {- Ok(reply) => TurnOutcome::Completed(reply),- Err(err) => TurnOutcome::Errored(err.to_string()),- },- }- };-- match remaining {- Some(d) => match tokio::time::timeout(d, run).await {- Ok(outcome) => outcome,- Err(_) => TurnOutcome::TimedOut,- },- None => run.await,- }-}--/// Remaining wall-clock budget until the task `deadline`.-///-/// `Ok(None)` = no deadline configured (run unbounded); `Ok(Some(d))` = `d`-/// left before the deadline; `Err(())` = the deadline has already passed, so-/// the caller must settle the task as timed out instead of starting a turn.-fn remaining_budget(deadline: Option<Instant>, now: Instant) -> Result<Option<Duration>, ()> {- match deadline {- Some(d) if now >= d => Err(()),- Some(d) => Ok(Some(d - now)),- None => Ok(None),- }-}--/// Build the terminal timeout [`TaskResult`], emitting the fatal `error`-/// envelope that bookends a timed-out task's stream.-fn timeout_result(task_id: &str, session_id: &str, seq: &AtomicI64) -> TaskResult {- emit_envelope(- task_id,- envelope::error_envelope(session_id, next_seq(seq), "task timed out", true),- );- TaskResult {- task_id: task_id.to_string(),- ok: false,- reply: String::new(),- usage: None,- error: Some("timeout".to_string()),- }-}--/// Return queued steering input (if any) after briefly waiting for input that-/// was sent while the turn was still in flight.-async fn drain_steer(steer_rx: &mut mpsc::UnboundedReceiver<String>) -> Option<String> {- if let Ok(msg) = steer_rx.try_recv() {- return Some(msg);- }- tokio::time::timeout(STEER_DRAIN_GRACE, steer_rx.recv())- .await- .unwrap_or_default()-}--/// Build (or resume) an agent session for a medulla task.-///-/// The transcript identity is scoped by `session_id` (which the caller has-/// already resolved to the medulla `sessionId`, falling back to the `taskId`),-/// not the bare `agent_definition_name`. Without this, two `medulla:task_run`s-/// on the same `agentId` would collide onto one shared transcript and the-/// second would resume the first's history.-async fn build_agent(- agent_id: &str,- task_id: &str,- session_id: &str,-) -> Result<OpenHumanSessionHost, String> {- let config = crate::config::rpc::load_config_with_timeout().await?;- crate::agent::harness::AgentDefinitionRegistry::init_global(&config.workspace_dir)- .map_err(|err| format!("failed to init agent definition registry: {err}"))?;- let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, agent_id)- .map_err(|err| format!("failed to build agent `{agent_id}`: {err}"))?;- agent.set_event_context(format!("medulla:{task_id}"), "medulla_harness");- // Scope the transcript/session key per medulla session so distinct sessions- // on the same agent get isolated history (mirrors the web channel's- // per-thread `set_agent_definition_name`).- agent.set_agent_definition_name(medulla_session_key(agent_id, session_id));- agent.fetch_connected_integrations().await;- agent.refresh_delegation_tools();- Ok(agent)-}--/// Derive a per-session agent-definition (transcript) key from the medulla-/// `session_id`, namespaced by `agent_id`. The session id is truncated on a-/// char boundary to keep transcript filenames bounded; the underlying-/// [`OpenHumanSessionHost::set_agent_definition_name`] sanitizes any remaining non-filename-/// characters.-fn medulla_session_key(agent_id: &str, session_id: &str) -> String {- let short: String = session_id.chars().take(32).collect();- format!("{agent_id}_{short}")-}--/// Spawn the per-turn progress → `medulla:task_envelope` forwarder. Returns its-/// join handle so the driver can flush it before the next turn.-fn spawn_forwarder(- task_id: String,- session_id: String,- seq: Arc<AtomicI64>,- mut progress_rx: mpsc::Receiver<AgentProgress>,-) -> tokio::task::JoinHandle<()> {- tokio::spawn(async move {- while let Some(progress) = progress_rx.recv().await {- if let Some(kind) = envelope::progress_to_event_kind(&progress) {- let env = envelope::envelope_for_kind(&session_id, next_seq(&seq), &kind);- emit_envelope(&task_id, env);- }- }- })-}--fn next_seq(seq: &AtomicI64) -> i64 {- seq.fetch_add(1, Ordering::Relaxed)-}--/// Project the crate-private [`LastTurnUsage`] into a compact JSON usage block-/// for `medulla:task_result` (the type itself isn't `Serialize`).-fn usage_to_json(usage: crate::agent::tinyagents::host::LastTurnUsage) -> serde_json::Value {- serde_json::json!({- "inputTokens": usage.input_tokens,- "outputTokens": usage.output_tokens,- "cachedInputTokens": usage.cached_input_tokens,- "costUsd": usage.cost_usd,- "contextWindow": usage.context_window,- })-}--/// Emit a `medulla:task_envelope` frame up the backend socket.-fn emit_envelope(task_id: &str, env: envelope::HarnessEnvelope) {- let envelope = match serde_json::to_value(&env) {- Ok(v) => v,- Err(err) => {- log::warn!("[medulla] failed to serialize envelope for task_id={task_id}: {err}");- return;- }- };- let frame = payloads::TaskEnvelope {- task_id: task_id.to_string(),- envelope,- };- emit(EVENT_TASK_ENVELOPE, frame);-}--/// Emit a terminal `medulla:task_result`.-fn emit_result(result: TaskResult) {- emit(EVENT_TASK_RESULT, result);-}--/// Emit `medulla:register_agents` — the roster advertised on (re)connect.-///-/// Built from the shipped default agent definitions. The backend clears the-/// roster on socket disconnect.-pub fn emit_register_agents() {- let agents: Vec<AgentDescriptor> = crate::agent::registry::default_agents()- .into_iter()- .map(|entry| AgentDescriptor {- id: entry.id,- name: entry.name,- description: entry.description,- })- .collect();- log::info!("[medulla] advertising {} agents to backend", agents.len());- emit(EVENT_REGISTER_AGENTS, RegisterAgents { agents });-}--/// Handle `medulla:capabilities_request`: self-report for one probe.-///-/// The backend's roster calls this lazily before first delegating to an agent it-/// has not cached, fans the frame out to every harness socket the user holds,-/// and waits ten seconds. An agent that never answers does not degrade-/// gracefully — it spends that whole window on every first delegation. So this-/// always emits a `medulla:capabilities_result`, even when the only thing it can-/// truthfully say is `ready`.-///-/// Runs on its own task: building the report loads config and reads the workflow-/// store, neither of which belongs on the socket read loop.-pub fn handle_capabilities_request(request: CapabilitiesRequest) {- let workflows::BridgeGeneration { bridge, cancel } = workflows::bridge_generation();- let connection_cancel = workflows::connection_generation();- tokio::spawn(async move {- tokio::select! {- biased;- _ = cancel.cancelled() => {- log::debug!("[medulla] discarded capability probe from an old bridge");- }- _ = connection_cancel.cancelled() => {- log::debug!("[medulla] discarded capability probe from a closed socket");- }- _ = async move {- let capabilities = describe_self(&request.agent_id, bridge).await;- emit_awaited(- EVENT_CAPABILITIES_RESULT,- CapabilitiesResult {- probe_id: request.probe_id,- capabilities,- },- )- .await;- } => {}- }- });-}--/// Answer a `medulla:capabilities_request` this build could not decode.-///-/// A frame from a newer backend (an added required field, a retyped one) would-/// otherwise be dropped, and a dropped probe costs the backend its full-/// ten-second deadline on the *first* delegation to this agent. The `probeId` is-/// recovered from the raw JSON — without one there is nothing to correlate, so-/// the frame really is unanswerable and is only logged.-pub fn reject_unparsed_capabilities_request(raw: &serde_json::Value, reason: &str) {- let Some(result) = unparsed_capabilities_result(raw, reason) else {- log::warn!("[medulla] undecodable capabilities_request carries no probeId — cannot answer");- return;- };- log::info!(- "[medulla] answering undecodable capabilities_request probe_id={} as not ready",- result.probe_id- );- emit(EVENT_CAPABILITIES_RESULT, result);-}--/// Project an undecodable probe onto its reply frame. Split out so the recovery-/// (which `probeId` is answerable, and what the answer says) is testable without-/// a socket.-///-/// The report is `ready: false` plus a reason rather than an empty bag: those-/// two fields are on the backend's `sanitizeCapabilities` allowlist, and a-/// payload with nothing on that allowlist sanitizes away into the same-/// non-answer as silence.-fn unparsed_capabilities_result(- raw: &serde_json::Value,- reason: &str,-) -> Option<CapabilitiesResult> {- let probe_id = raw.get("probeId").and_then(serde_json::Value::as_str)?;- Some(CapabilitiesResult {- probe_id: probe_id.to_string(),- capabilities: serde_json::json!({- "ready": false,- "readyReason": format!("this agent could not read the probe: {reason}"),- }),- })-}--/// Build this host's capability report for `agent_id`.-///-/// Only fields on the backend's allowlist (`sanitizeCapabilities`) are worth-/// sending — anything else is dropped there — and each is best-effort: a field-/// this host cannot resolve is omitted rather than guessed, because the-/// orchestrator reasons about placement from these values.-async fn describe_self(- agent_id: &str,- bridge: Option<Arc<dyn workflows::WorkflowBridge>>,-) -> serde_json::Value {- let mut caps = serde_json::Map::new();- // Advisory readiness. A connected core that answered the probe at all is- // ready by definition; per-agent gating lives in the task path, not here.- caps.insert("ready".to_string(), serde_json::Value::Bool(true));-- if let Some(entry) = crate::agent::registry::default_agents()- .into_iter()- .find(|entry| entry.id == agent_id)- {- if !entry.description.is_empty() {- caps.insert("summary".to_string(), entry.description.into());- }- }-- // `cwd` is the agent's read/write root (`action_dir`), which is what the- // orchestrator actually means by "where does this agent work".- if let Some(action_dir) = bridge.as_ref().and_then(|bridge| bridge.action_dir()) {- caps.insert("cwd".to_string(), action_dir.into());- }-- // The workflow adverts ride the probe as well as the push registration, so a- // backend that only probes still learns this host's graphs.- let workflows = workflows::advertised_workflows_for(bridge).await;- if !workflows.is_empty() {- match serde_json::to_value(workflows) {- Ok(value) => {- caps.insert("workflows".to_string(), value);- }- Err(err) => log::warn!("[medulla] failed to serialize workflow adverts: {err}"),- }- }-- serde_json::Value::Object(caps)-}--/// Serialize `payload` and emit it as a Socket.IO event on the global backend-/// socket. Best-effort: a missing/disconnected socket is logged, not fatal.-fn emit<T: serde::Serialize>(event: &str, payload: T) {- let data = match serde_json::to_value(&payload) {- Ok(v) => v,- Err(err) => {- log::warn!("[medulla] failed to serialize payload for {event}: {err}");- return;- }- };- let Some(mgr) = crate::platform::socket::global_socket_manager() else {- log::debug!("[medulla] no socket manager — dropping {event}");- return;- };- // `emit` is reachable from synchronous callers (socket event handlers,- // unit tests). `tokio::spawn` panics outside a runtime, so resolve the- // handle first and treat "no runtime" like "no socket": best-effort drop.- let Ok(handle) = tokio::runtime::Handle::try_current() else {- log::debug!("[medulla] no tokio runtime — dropping {event}");- return;- };- let mgr = Arc::clone(mgr);- let event = event.to_string();- handle.spawn(async move {- if let Err(err) = mgr.emit(&event, data).await {- log::warn!("[medulla] failed to emit {event}: {err}");- }- });-}--/// Serialize and enqueue one medulla event before returning.-///-/// Registration snapshots use this awaited form because their full-replacement-/// ordering must extend through `SocketManager::emit`'s channel send, not stop-/// at spawning a task that may be scheduled later.-async fn emit_awaited<T: serde::Serialize>(event: &str, payload: T) -> bool {- let data = match serde_json::to_value(&payload) {- Ok(value) => value,- Err(err) => {- log::warn!("[medulla] failed to serialize payload for {event}: {err}");- return false;- }- };- let Some(manager) = crate::platform::socket::global_socket_manager() else {- log::debug!("[medulla] no socket manager — dropping {event}");- return false;- };- match manager.emit(event, data).await {- Ok(()) => true,- Err(err) => {- log::warn!("[medulla] failed to emit {event}: {err}");- false- }- }-}--#[cfg(test)]-#[path = "mod_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/platform/socket/medulla/mod_tests.rs b/crates/openhuman-core/src/platform/socket/medulla/mod_tests.rsdeleted file mode 100644index 0a77b392b3..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/mod_tests.rs+++ /dev/null@@ -1,96 +0,0 @@-use super::*;--#[test]-fn unknown_task_send_and_abort_are_noops() {- let mgr = MedullaTaskManager::new();- // Neither should panic when the task id is unknown.- mgr.steer_task(payloads::TaskSend {- task_id: "nope".into(),- input: "hi".into(),- });- mgr.abort_task(payloads::TaskAbort {- task_id: "nope".into(),- });-}--#[test]-fn duplicate_task_registration_is_rejected() {- let mgr = Arc::new(MedullaTaskManager::new());- // Manually seed a running task to simulate an in-flight run, then prove- // a second registration under the same id is ignored.- let abort = CancellationToken::new();- let (steer_tx, _rx) = mpsc::unbounded_channel();- mgr.tasks- .lock()- .insert("dup".to_string(), RunningTask { abort, steer_tx });- assert!(mgr.tasks.lock().contains_key("dup"));- // A second start_task for "dup" must not overwrite / spawn.- mgr.start_task(payloads::TaskRun {- task_id: "dup".into(),- cycle_id: "c".into(),- session_id: None,- instruction: "x".into(),- agent_id: None,- timeout_ms: 0,- });- assert_eq!(mgr.tasks.lock().len(), 1);-}--#[test]-fn session_key_scopes_transcript_by_session_id() {- // Same agent id + distinct session ids => distinct transcript keys, so- // two medulla sessions can't collide onto one shared transcript.- let a = medulla_session_key("orchestrator", "sess-abc");- let b = medulla_session_key("orchestrator", "sess-xyz");- assert_ne!(a, b);- assert_eq!(a, "orchestrator_sess-abc");- assert!(a.starts_with("orchestrator_"));- // Overlong session ids are truncated on a char boundary.- let long = "x".repeat(100);- let key = medulla_session_key("orchestrator", &long);- assert_eq!(key, format!("orchestrator_{}", "x".repeat(32)));-}--#[test]-fn an_undecodable_probe_answers_not_ready_when_it_names_itself() {- let raw = serde_json::json!({ "probeId": "p-1", "agentId": 7 });- let result = unparsed_capabilities_result(&raw, "invalid type: integer")- .expect("a probe that names itself is answerable");- assert_eq!(result.probe_id, "p-1");- // `ready` + `readyReason` are the two fields the backend's allowlist- // keeps; an answer outside them sanitizes to an empty bag, which the- // probe treats as no answer at all.- assert_eq!(result.capabilities["ready"], false);- assert!(result.capabilities["readyReason"]- .as_str()- .expect("a readable reason")- .contains("invalid type: integer"));-}--#[test]-fn an_undecodable_probe_without_a_probe_id_is_unanswerable() {- // Nothing to correlate, so nothing can be answered — and the socket read- // loop must not panic over it either.- let raw = serde_json::json!({ "agentId": "orchestrator" });- assert!(unparsed_capabilities_result(&raw, "missing field `probeId`").is_none());- reject_unparsed_capabilities_request(&raw, "missing field `probeId`");-}--#[test]-fn remaining_budget_reports_time_left_and_exhaustion() {- let now = Instant::now();- // No deadline configured => unbounded.- assert_eq!(remaining_budget(None, now), Ok(None));- // Deadline in the future => remaining time until it.- let future = now + Duration::from_secs(10);- match remaining_budget(Some(future), now) {- Ok(Some(d)) => assert!(d <= Duration::from_secs(10) && d > Duration::from_secs(9)),- other => panic!("expected some remaining budget, got {other:?}"),- }- // Deadline already reached / passed => exhausted.- assert_eq!(remaining_budget(Some(now), now), Err(()));- assert_eq!(- remaining_budget(Some(now), now + Duration::from_secs(1)),- Err(())- );-}diff --git a/crates/openhuman-core/src/platform/socket/medulla/payloads.rs b/crates/openhuman-core/src/platform/socket/medulla/payloads.rsdeleted file mode 100644index 84c76e6d0f..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/payloads.rs+++ /dev/null@@ -1,325 +0,0 @@-//! Wire payloads for the medulla "harness plane" — the `medulla:task_*`-//! Socket.IO protocol that lets a medulla operator (running in the backend)-//! drive an OpenHuman agent session as a delegated sub-agent.-//!-//! See `docs/specs/session-streaming-api-spec.md` §6 in the medulla repo. All-//! payloads are camelCase on the wire to match the backend's Socket.IO-//! conventions (the harness envelope they carry stays snake_case).--use serde::{Deserialize, Serialize};--// ─────────────────────────────────────────────────────────────────────────────-// Down: backend / medulla → openhuman agent-// ─────────────────────────────────────────────────────────────────────────────--/// `medulla:task_run` — start a task in an openhuman agent session.-///-/// Creates (or resumes, when `session_id` is supplied) a session and sends-/// `instruction` as the opening prompt.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskRun {- pub task_id: String,- pub cycle_id: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub session_id: Option<String>,- pub instruction: String,- /// Which openhuman agent to run the task as (defaults to the orchestrator).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,- /// Hard wall-clock budget for the whole task, in milliseconds.- #[serde(default)]- pub timeout_ms: u64,-}--/// `medulla:task_send` — mid-task steering (answer a question / approval-/// decision / follow-up); `input` is delivered into the running session.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskSend {- pub task_id: String,- pub input: String,-}--/// `medulla:task_abort` — cancel the session/task.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskAbort {- pub task_id: String,-}--// ─────────────────────────────────────────────────────────────────────────────-// Up: openhuman agent → backend / medulla-// ─────────────────────────────────────────────────────────────────────────────--/// `medulla:task_envelope` — one live-stream frame for a task, carrying a-/// native Medulla harness envelope (see [`super::envelope`]).-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskEnvelope {- pub task_id: String,- /// A serialized [`super::envelope::HarnessEnvelope`].- pub envelope: serde_json::Value,-}--/// `medulla:task_result` — explicit completion (preferred over idle-detection).-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TaskResult {- pub task_id: String,- pub ok: bool,- #[serde(default)]- pub reply: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub usage: Option<serde_json::Value>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub error: Option<String>,-}--/// A single agent descriptor advertised in the roster.-///-/// The identity key is `id`, NOT `agentId`: the backend's roster registry keys-/// and validates on `id` (`agentRegistry.ts` `hasValidId`), and medulla-v1's-/// `AgentDescriptor` port declares the same field. An advert that names its-/// agent under any other key is silently dropped at the backend boundary, so-/// this must stay `id` on the wire.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct AgentDescriptor {- pub id: String,- pub name: String,- #[serde(default, skip_serializing_if = "String::is_empty")]- pub description: String,-}--/// `medulla:register_agents` — roster advertisement sent on connect. The-/// backend clears the roster when this socket disconnects.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct RegisterAgents {- pub agents: Vec<AgentDescriptor>,-}--// ─────────────────────────────────────────────────────────────────────────────-// Capability handshake-// ─────────────────────────────────────────────────────────────────────────────--/// `medulla:capabilities_request` — the backend asks one agent to self-report.-///-/// The backend fans this out to every harness socket the user holds and-/// correlates the answer by `probe_id`; an agent that never answers costs the-/// probe its full ten-second deadline, so [`super::emit_capabilities_result`]-/// always replies, even when it has nothing interesting to say.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct CapabilitiesRequest {- pub probe_id: String,- #[serde(default)]- pub agent_id: String,-}--/// `medulla:capabilities_result` — the self-report for one probe.-///-/// `capabilities` is an open bag the backend narrows through its own allowlist-/// (`sanitizeCapabilities`), so it stays raw JSON here rather than a struct this-/// side would have to keep in lockstep with the server's allowlist.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct CapabilitiesResult {- pub probe_id: String,- pub capabilities: serde_json::Value,-}--// ─────────────────────────────────────────────────────────────────────────────-// Workflow plane-// ─────────────────────────────────────────────────────────────────────────────--/// One saved workflow graph as advertised to the backend — enough to choose it-/// and explain the choice, never the graph itself.-///-/// Field-compatible with the `WorkflowDescriptor` port in medulla-v1, so an-/// advert crossing this boundary needs no translation layer on either side.-/// `name`/`description` skip-/// serialization when empty for exactly that reason: the Rust advert already-/// omits its empty strings, the port therefore declares them optional, and the-/// backend passes an absent key through as absent rather than fabricating `""`.-///-/// Not `Eq`: a declared input's `default` is free-form JSON, which has no total-/// equality (floats, and `NaN` among them). `PartialEq` is what comparisons here-/// actually use.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkflowDescriptor {- /// Stable identity — the only field the wire always carries and the only one- /// anything routes on (delegation, `get`, `runs`).- pub id: String,- /// Display name; omitted from the wire when blank.- #[serde(default, skip_serializing_if = "String::is_empty")]- pub name: String,- /// Prompt surface — written like a tool description; omitted when blank.- #[serde(default, skip_serializing_if = "String::is_empty")]- pub description: String,- /// How many steps the graph has: a rough cost signal, rendered verbatim.- #[serde(default)]- pub node_count: u32,- /// Whether this host considers the workflow runnable right now. Advisory —- /// the reader applies no policy, this host is the one that refuses.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub enabled: Option<bool>,- /// Open vocabulary for what starts the workflow ("manual", "cron", …).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub trigger_kind: Option<String>,- /// Provenance: which roster agent owns this workflow. Usually left unset —- /// the backend stamps the batch-level `agentId` onto any advert without one.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,- /// Provenance: the workspace the owning agent is deployed into.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub workspace_id: Option<String>,- /// The workflow's declared inputs — its callable signature. Lets the reader- /// know what it must collect before asking for a run, rather than having to- /// fetch the whole graph to find out. Empty for a workflow taking none, and- /// omitted from the wire in that case.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub inputs: Vec<WorkflowInputDescriptor>,-}--/// One declared input of an advertised workflow — what a caller must supply to-/// run it.-///-/// Mirrors `tinyflows::model::WorkflowInput` field-for-field rather than-/// re-exporting it, for the same reason [`TaskEnvelope`] keeps its envelope as-/// raw JSON: this module is a transport vocabulary and is compiled in every-/// build, while the engine is behind the `flows` feature gate. Naming the engine-/// type here would make the medulla plane fail to build whenever flows is off.-/// The mapping from the engine type lives in `flows::medulla_bridge`, which is-/// gated and may name it.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkflowInputDescriptor {- /// The input's name — the key a caller supplies it under.- pub name: String,- /// Declared JSON type: `string` | `number` | `boolean` | `json`.- #[serde(default, rename = "type", skip_serializing_if = "String::is_empty")]- pub ty: String,- /// Human-readable explanation; omitted when blank.- #[serde(default, skip_serializing_if = "String::is_empty")]- pub description: String,- /// Whether a caller must supply it.- #[serde(default)]- pub required: bool,- /// Value used when the caller supplies none; omitted when there is none.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub default: Option<serde_json::Value>,-}--/// `medulla:register_workflows` — the workflow advert batch, sent on connect and-/// re-sent whenever the host's store changes. The backend replaces this socket's-/// whole entry each time and drops it on disconnect, so a shrinking store is-/// communicated by re-sending the smaller list (never by a delete event).-///-/// Not `Eq` for the same reason as [`WorkflowDescriptor`], which it contains.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct RegisterWorkflows {- pub workflows: Vec<WorkflowDescriptor>,- /// Batch-level provenance stamped onto adverts that do not name their own- /// owner. Absent means "this host, agent unspecified".- #[serde(default, skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,-}--/// Which read (or the one authoring turn) a `medulla:workflow_request` asks for.-///-/// Snake-case on the wire to match the backend's `WorkflowRequestOp` union.-/// Unknown ops are a decode failure rather than a silent no-op, so a version-/// skew shows up as a reported error instead of a ten-second server timeout.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum WorkflowOp {- /// Fetch one workflow's detail, including its graph.- Get,- /// The node-kind catalog, optionally filtered to one `kind`.- NodeKinds,- /// Recent runs of one workflow.- Runs,- /// A whole authoring turn on this host's own copilot.- Copilot,-}--/// `medulla:workflow_request` — one round trip addressed to the host that-/// advertised the workflow. Which optional fields matter depends on `op`:-/// `get`/`runs` read `workflow_id`, `node_kinds` reads `kind`, `copilot` reads-/// `instruction` plus an optional `workflow_id` (absent ⇒ create).-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkflowRequest {- pub request_id: String,- pub op: WorkflowOp,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub workflow_id: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub kind: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub instruction: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,-}--/// `medulla:workflow_result` — the answer to one round trip.-///-/// `data` is OPAQUE: a graph, a node-kind catalog and a copilot outcome are all-/// host-shaped and pass through the backend verbatim (only size-bounded, at-/// 1 MiB). `ok: false` carries a readable message the orchestrator renders as a-/// tool error — a failed read must still be *answered*, because a dropped-/// request costs the server its whole deadline instead.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkflowResult {- pub request_id: String,- pub ok: bool,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub data: Option<serde_json::Value>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub error: Option<String>,-}--/// What a copilot turn reports back: the assistant's reply, the changes it-/// actually made (derived by the host from a re-read of its own store, never-/// from the model's claim), and the id of a workflow it created.-///-/// Mirrors the `CopilotOutcome` medulla-public's authoring copilot already-/// returns and the `WorkflowCopilotOutcome` the library port declares, so it-/// crosses the seam unchanged.-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct CopilotOutcome {- pub reply: String,- #[serde(default)]- pub changes: Vec<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub created: Option<String>,-}--// ─────────────────────────────────────────────────────────────────────────────-// Socket.IO event names-// ─────────────────────────────────────────────────────────────────────────────--/// Down events handled by openhuman.-pub const EVENT_TASK_RUN: &str = "medulla:task_run";-pub const EVENT_TASK_SEND: &str = "medulla:task_send";-pub const EVENT_TASK_ABORT: &str = "medulla:task_abort";-pub const EVENT_CAPABILITIES_REQUEST: &str = "medulla:capabilities_request";-pub const EVENT_WORKFLOW_REQUEST: &str = "medulla:workflow_request";--/// Up events emitted by openhuman.-pub const EVENT_TASK_ENVELOPE: &str = "medulla:task_envelope";-pub const EVENT_TASK_RESULT: &str = "medulla:task_result";-pub const EVENT_REGISTER_AGENTS: &str = "medulla:register_agents";-pub const EVENT_REGISTER_WORKFLOWS: &str = "medulla:register_workflows";-pub const EVENT_CAPABILITIES_RESULT: &str = "medulla:capabilities_result";-pub const EVENT_WORKFLOW_RESULT: &str = "medulla:workflow_result";--#[cfg(test)]-#[path = "payloads_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/platform/socket/medulla/payloads_tests.rs b/crates/openhuman-core/src/platform/socket/medulla/payloads_tests.rsdeleted file mode 100644index b93d47869d..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/payloads_tests.rs+++ /dev/null@@ -1,242 +0,0 @@-use super::*;-use serde_json::json;--#[test]-fn task_run_round_trips_and_reads_camel_case_wire() {- let wire = json!({- "taskId": "t1",- "cycleId": "c1",- "sessionId": "s1",- "instruction": "summarize the doc",- "agentId": "orchestrator",- "timeoutMs": 60000,- });- let parsed: TaskRun = serde_json::from_value(wire.clone()).unwrap();- assert_eq!(parsed.task_id, "t1");- assert_eq!(parsed.cycle_id, "c1");- assert_eq!(parsed.session_id.as_deref(), Some("s1"));- assert_eq!(parsed.agent_id.as_deref(), Some("orchestrator"));- assert_eq!(parsed.timeout_ms, 60000);- // Re-serialize and confirm it decodes back to the same value.- let again: TaskRun = serde_json::from_value(serde_json::to_value(&parsed).unwrap()).unwrap();- assert_eq!(parsed, again);-}--#[test]-fn task_run_defaults_optional_fields() {- let wire = json!({- "taskId": "t2",- "cycleId": "c2",- "instruction": "go",- });- let parsed: TaskRun = serde_json::from_value(wire).unwrap();- assert!(parsed.session_id.is_none());- assert!(parsed.agent_id.is_none());- assert_eq!(parsed.timeout_ms, 0);-}--#[test]-fn task_send_and_abort_round_trip() {- let send: TaskSend = serde_json::from_value(json!({ "taskId": "t", "input": "yes" })).unwrap();- assert_eq!(send.input, "yes");- let abort: TaskAbort = serde_json::from_value(json!({ "taskId": "t" })).unwrap();- assert_eq!(abort.task_id, "t");-}--#[test]-fn task_result_omits_none_and_round_trips() {- let res = TaskResult {- task_id: "t".into(),- ok: true,- reply: "done".into(),- usage: None,- error: None,- };- let v = serde_json::to_value(&res).unwrap();- assert!(v.get("usage").is_none());- assert!(v.get("error").is_none());- assert_eq!(v["taskId"], "t");- assert_eq!(v["ok"], true);-}--#[test]-fn register_agents_advertises_the_id_key_the_backend_validates() {- let roster = RegisterAgents {- agents: vec![AgentDescriptor {- id: "orchestrator".into(),- name: "Orchestrator".into(),- description: "default".into(),- }],- };- let wire = serde_json::to_value(&roster).unwrap();- // `agentRegistry.hasValidId` keys on `id`; an `agentId` key here would- // make the whole roster vanish server-side.- assert_eq!(wire["agents"][0]["id"], "orchestrator");- assert!(wire["agents"][0].get("agentId").is_none());- let back: RegisterAgents = serde_json::from_value(wire).unwrap();- assert_eq!(roster, back);-}--#[test]-fn workflow_descriptor_advertises_declared_inputs_and_omits_them_when_none() {- // The reader needs to know what to collect before asking for a run;- // without this it would have to fetch the whole graph to find out.- let advert = WorkflowDescriptor {- id: "wf-1".into(),- name: "Review".into(),- description: String::new(),- node_count: 2,- enabled: Some(true),- trigger_kind: None,- agent_id: None,- workspace_id: None,- inputs: vec![WorkflowInputDescriptor {- name: "repo".into(),- ty: "string".into(),- description: String::new(),- required: true,- default: None,- }],- };- let wire = serde_json::to_value(&advert).unwrap();- assert_eq!(wire["inputs"][0]["name"], "repo");- assert_eq!(wire["inputs"][0]["type"], "string");- assert_eq!(wire["inputs"][0]["required"], true);-- let none = WorkflowDescriptor {- inputs: Vec::new(),- ..advert- };- let wire = serde_json::to_value(&none).unwrap();- assert!(- wire.get("inputs").is_none(),- "a workflow taking no inputs must not send an empty key"- );-}--#[test]-fn workflow_descriptor_omits_blank_name_and_description() {- let advert = WorkflowDescriptor {- id: "wf-1".into(),- name: String::new(),- description: String::new(),- node_count: 5,- enabled: Some(true),- trigger_kind: Some("cron".into()),- agent_id: None,- workspace_id: None,- inputs: Vec::new(),- };- let wire = serde_json::to_value(&advert).unwrap();- assert_eq!(wire["id"], "wf-1");- assert_eq!(wire["nodeCount"], 5);- assert_eq!(wire["enabled"], true);- assert_eq!(wire["triggerKind"], "cron");- // Absent, never `""` — the port declares these optional precisely- // because the wire omits them.- assert!(wire.get("name").is_none());- assert!(wire.get("description").is_none());- assert!(wire.get("agentId").is_none());- let back: WorkflowDescriptor = serde_json::from_value(wire).unwrap();- assert_eq!(advert, back);-}--#[test]-fn register_workflows_omits_absent_batch_agent_id() {- let batch = RegisterWorkflows {- workflows: vec![],- agent_id: None,- };- let wire = serde_json::to_value(&batch).unwrap();- assert!(wire["workflows"].as_array().unwrap().is_empty());- assert!(wire.get("agentId").is_none());-}--#[test]-fn workflow_request_reads_every_op_from_the_wire() {- for (wire_op, expected) in [- ("get", WorkflowOp::Get),- ("node_kinds", WorkflowOp::NodeKinds),- ("runs", WorkflowOp::Runs),- ("copilot", WorkflowOp::Copilot),- ] {- let parsed: WorkflowRequest =- serde_json::from_value(json!({ "requestId": "r1", "op": wire_op })).unwrap();- assert_eq!(parsed.op, expected);- assert_eq!(parsed.request_id, "r1");- assert!(parsed.workflow_id.is_none());- }- // An op this build does not know is a decode error, not a silent drop.- assert!(serde_json::from_value::<WorkflowRequest>(- json!({ "requestId": "r1", "op": "apply_ops" })- )- .is_err());-}--#[test]-fn workflow_request_reads_the_op_specific_fields() {- let parsed: WorkflowRequest = serde_json::from_value(json!({- "requestId": "r2",- "op": "copilot",- "instruction": "add a slack step",- "workflowId": "wf-1",- "agentId": "orchestrator",- }))- .unwrap();- assert_eq!(parsed.op, WorkflowOp::Copilot);- assert_eq!(parsed.instruction.as_deref(), Some("add a slack step"));- assert_eq!(parsed.workflow_id.as_deref(), Some("wf-1"));- assert_eq!(parsed.agent_id.as_deref(), Some("orchestrator"));-}--#[test]-fn workflow_result_omits_the_unused_arm() {- let ok = WorkflowResult {- request_id: "r".into(),- ok: true,- data: Some(json!({ "graph": [] })),- error: None,- };- let wire = serde_json::to_value(&ok).unwrap();- assert_eq!(wire["requestId"], "r");- assert_eq!(wire["ok"], true);- assert!(wire.get("error").is_none());-- let failed = WorkflowResult {- request_id: "r".into(),- ok: false,- data: None,- error: Some("unknown workflow".into()),- };- let wire = serde_json::to_value(&failed).unwrap();- assert_eq!(wire["ok"], false);- assert_eq!(wire["error"], "unknown workflow");- assert!(wire.get("data").is_none());-}--#[test]-fn copilot_outcome_matches_the_library_shape() {- let outcome = CopilotOutcome {- reply: "added the step".into(),- changes: vec!["node:slack added".into()],- created: None,- };- let wire = serde_json::to_value(&outcome).unwrap();- assert_eq!(wire["reply"], "added the step");- assert_eq!(wire["changes"][0], "node:slack added");- assert!(wire.get("created").is_none());-}--#[test]-fn capabilities_request_defaults_a_missing_agent_id() {- let parsed: CapabilitiesRequest = serde_json::from_value(json!({ "probeId": "p1" })).unwrap();- assert_eq!(parsed.probe_id, "p1");- assert!(parsed.agent_id.is_empty());- let wire = serde_json::to_value(CapabilitiesResult {- probe_id: "p1".into(),- capabilities: json!({ "ready": true }),- })- .unwrap();- assert_eq!(wire["probeId"], "p1");- assert_eq!(wire["capabilities"]["ready"], true);-}diff --git a/crates/openhuman-core/src/platform/socket/medulla/workflows.rs b/crates/openhuman-core/src/platform/socket/medulla/workflows.rsdeleted file mode 100644index 76a251bcea..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/workflows.rs+++ /dev/null@@ -1,576 +0,0 @@-//! The workflow plane of the medulla harness protocol: advertising this host's-//! saved workflow graphs, and serving the reads (and the one authoring turn)-//! the orchestrator round-trips back to whoever owns them.-//!-//! **Why a trait and not a direct call into `flows`.** Two different hosts embed-//! this transport — openhuman over its SQLite `flows` store, and medulla-public-//! over its own layered JSON workflow store — and they share nothing but the-//! wire shape. So the store side is a host-supplied [`WorkflowBridge`] the host-//! installs once at startup ([`set_workflow_bridge`]), and the engine types stay-//! entirely on the host's side of the seam: a graph, a node-kind catalog and a-//! run list all cross as opaque [`serde_json::Value`], exactly as they do in-//! medulla-v1's `WorkflowCatalog` port. Nothing in this module parses a node, an-//! edge, or a config field.-//!-//! **Why every path answers.** The server correlates a request by `requestId`-//! and waits on a deadline — ten seconds for a read, ten *minutes* for a copilot-//! turn. A dropped request is therefore not a cheap no-op: it burns that whole-//! window and, for `copilot`, holds a promise open for the rest of the cycle. So-//! a missing bridge, an unknown op argument, a bridge error and even a panicking-//! bridge method all become a `medulla:workflow_result` with `ok: false` and a-//! readable message. The only way to stay silent is for the socket to be gone,-//! which the server already handles by retiring the waiter on disconnect.--use std::future::Future;-use std::panic::AssertUnwindSafe;-use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, OnceLock};--use async_trait::async_trait;-use futures::FutureExt;-use parking_lot::RwLock;-use serde_json::Value;-use tokio_util::sync::CancellationToken;--use super::payloads::{- CopilotOutcome, RegisterWorkflows, WorkflowDescriptor, WorkflowOp, WorkflowRequest,- WorkflowResult, EVENT_REGISTER_WORKFLOWS, EVENT_WORKFLOW_RESULT,-};--/// The store side of the workflow plane, supplied by the embedding host.-///-/// The reads are synchronous because every host backs them with a local store;-/// they are dispatched on a blocking thread so a slow store cannot stall the-/// socket runtime. `copilot` is `async` because it is not a read at all — it is-/// a whole agent turn on the host's own authoring copilot.-///-/// Every method returns `Result<_, String>` rather than a host error type: the-/// error is going straight onto a model's prompt surface as a tool result, so it-/// must already be a sentence a reader can act on.-#[async_trait]-pub trait WorkflowBridge: Send + Sync {- /// The adverts this host publishes. Cheap and side-effect free — it is- /// called on every (re)connect and on every store change.- fn list(&self) -> Vec<WorkflowDescriptor>;-- /// Fallible advert read used by registration.- ///- /// The default preserves compatibility for hosts whose list cannot fail.- /// Store-backed hosts override it so a transient read failure does not look- /// like a successful empty replacement batch.- fn try_list(&self) -> Result<Vec<WorkflowDescriptor>, String> {- Ok(self.list())- }-- /// One workflow's detail, graph included, as the host's own JSON shape.- fn get(&self, id: &str) -> Result<Value, String>;-- /// The node-kind catalog, optionally narrowed to a single `kind`. This is an- /// authoring aid: a manager reads it to brief the copilot accurately.- fn node_kinds(&self, kind: Option<&str>) -> Result<Value, String>;-- /// Recent runs of one workflow, for visibility into a delegated graph.- fn runs(&self, id: &str) -> Result<Value, String>;-- /// Run one authoring turn on the host's copilot. `workflow_id` absent means- /// "create a new workflow". The outcome must be derived from a re-read of- /// the host's own store rather than from the model's claim about what it- /// did — that is the accountability property the whole delegation rests on.- async fn copilot(- &self,- instruction: &str,- workflow_id: Option<&str>,- ) -> Result<CopilotOutcome, String>;-- /// Which roster agent owns these workflows, when the host runs more than- /// one identity. Stamped onto the advert batch so the backend can route a- /// delegated workflow to its owner. Defaults to unset — the backend then- /// treats the whole socket as the owner.- fn agent_id(&self) -> Option<String> {- None- }-- /// The action directory associated with this bridge's authenticated- /// identity, when the host has one. Capability probes use this instead of- /// reloading process-global active-user state.- fn action_dir(&self) -> Option<String> {- None- }-}--#[derive(Clone)]-pub(super) struct BridgeGeneration {- pub(super) bridge: Option<Arc<dyn WorkflowBridge>>,- pub(super) cancel: CancellationToken,-}--struct BridgeState {- bridge: Option<Arc<dyn WorkflowBridge>>,- generation: CancellationToken,-}--struct ConnectionGeneration {- current: CancellationToken,-}--impl ConnectionGeneration {- fn disconnected() -> Self {- let current = CancellationToken::new();- current.cancel();- Self { current }- }-- fn snapshot(&self) -> CancellationToken {- self.current.clone()- }-- fn begin(&mut self) {- self.current.cancel();- self.current = CancellationToken::new();- }-- fn end(&mut self) {- self.current.cancel();- *self = Self::disconnected();- }-}--static BRIDGE_STATE: OnceLock<RwLock<BridgeState>> = OnceLock::new();-static CONNECTION_GENERATION: OnceLock<RwLock<ConnectionGeneration>> = OnceLock::new();--fn bridge_state() -> &'static RwLock<BridgeState> {- BRIDGE_STATE.get_or_init(|| {- RwLock::new(BridgeState {- bridge: None,- generation: CancellationToken::new(),- })- })-}--fn connection_generation_state() -> &'static RwLock<ConnectionGeneration> {- CONNECTION_GENERATION.get_or_init(|| RwLock::new(ConnectionGeneration::disconnected()))-}--pub(super) fn bridge_generation() -> BridgeGeneration {- let state = bridge_state().read();- BridgeGeneration {- bridge: state.bridge.clone(),- cancel: state.generation.clone(),- }-}--/// A snapshot of the token for the currently-authenticated socket lifetime.-///-/// Visible to the whole `socket` module, not just `medulla`: `event_handlers`-/// spawns hosted-brain work that must not emit its result onto a *later*-/// connection, and it is a sibling of this module rather than a child.-pub(in crate::platform::socket) fn connection_generation() -> CancellationToken {- connection_generation_state().read().snapshot()-}--/// Run `deliver` only while `token`'s generation is still live, holding the-/// generation lock across the decision.-///-/// A plain `token.is_cancelled()` followed by a send is a race: the socket loop-/// can end the generation and drain the emit channel in the gap, after which the-/// handler's send lands in an empty channel and is flushed onto the *next*-/// connection — exactly what the check was meant to prevent.-///-/// Taking the read guard closes it, because [`end_connection_generation`] needs-/// the write guard to cancel. Either this runs first, and the message is queued-/// before the drain that will discard it; or the end runs first, and `token` is-/// already cancelled here. `deliver` must therefore stay cheap and must not-/// block, await, or re-enter this module — the one caller does a JSON encode and-/// an unbounded send.-///-/// Returns `None` when the generation has ended.-pub(in crate::platform::socket) fn with_live_connection<R>(- token: &CancellationToken,- deliver: impl FnOnce() -> R,-) -> Option<R> {- let _generation = connection_generation_state().read();- if token.is_cancelled() {- return None;- }- Some(deliver())-}--/// Start a new authenticated-socket lifetime.-///-/// Called by the `ready` handler before it advertises workflows. Work received-/// before `ready`, while reconnecting, or after a disconnect sees a cancelled-/// generation and is discarded instead of outliving the backend waiter that-/// sent it.-pub(in crate::platform::socket) fn begin_connection_generation() {- connection_generation_state().write().begin();-}--/// End the current authenticated-socket lifetime and cancel its work.-pub(in crate::platform::socket) fn end_connection_generation() {- connection_generation_state().write().end();-}--fn replace_bridge(bridge: Option<Arc<dyn WorkflowBridge>>) -> CancellationToken {- let mut state = bridge_state().write();- state.generation.cancel();- let generation = CancellationToken::new();- state.bridge = bridge;- state.generation = generation.clone();- generation-}--/// Orders overlapping snapshot emissions by successful registration revision.-///-/// Reads stay concurrent and off the socket runtime. A newer successful read-/// supersedes every older one, while a newer failed read does not suppress an-/// older successful snapshot. The mutex makes the revision check plus the-/// awaited socket enqueue one ordered operation.-struct RegistrationSequencer {- next_revision: AtomicU64,- last_emitted: tokio::sync::Mutex<u64>,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum SequencedEmit {- Emitted,- Superseded,- Failed,-}--impl RegistrationSequencer {- const fn new() -> Self {- Self {- next_revision: AtomicU64::new(0),- last_emitted: tokio::sync::Mutex::const_new(0),- }- }-- fn begin(&self) -> u64 {- self.next_revision.fetch_add(1, Ordering::Relaxed) + 1- }-- async fn emit_if_newer<F, Fut>(&self, revision: u64, emit: F) -> SequencedEmit- where- F: FnOnce() -> Fut,- Fut: Future<Output = bool>,- {- let mut last_emitted = self.last_emitted.lock().await;- if revision <= *last_emitted {- return SequencedEmit::Superseded;- }- if !emit().await {- return SequencedEmit::Failed;- }- *last_emitted = revision;- SequencedEmit::Emitted- }-}--static REGISTRATION_SEQUENCE: RegistrationSequencer = RegistrationSequencer::new();--/// Install (or replace) the host's workflow bridge, and advertise what it holds.-///-/// Registering re-advertises immediately so a bridge installed after connect-/// still reaches a backend that has already seen this socket's `ready`.-pub fn set_workflow_bridge(bridge: Arc<dyn WorkflowBridge>) {- replace_bridge(Some(bridge));- emit_register_workflows();-}--/// Remove the installed bridge and tell the backend this socket now advertises-/// nothing. Sending an empty batch is the only way to retract: the backend-/// replaces a socket's whole entry on each registration and has no delete event.-pub fn clear_workflow_bridge() {- let generation = replace_bridge(None);- let connection_cancel = connection_generation();- let revision = REGISTRATION_SEQUENCE.begin();- tokio::spawn(async move {- tokio::select! {- biased;- _ = generation.cancelled() => {}- _ = connection_cancel.cancelled() => {}- _ = async move {- let batch = RegisterWorkflows {- workflows: Vec::new(),- agent_id: None,- };- REGISTRATION_SEQUENCE- .emit_if_newer(revision, || emit_batch(batch))- .await;- } => {}- }- });-}--/// Emit `medulla:register_workflows` — the advert batch, sent on connect and-/// whenever the host signals its workflow set changed.-///-/// A host without a bridge stays silent rather than advertising an empty list:-/// "I have no workflow plane" and "my store is empty" are different claims, and-/// only the second one should clear a previously registered set.-pub fn emit_register_workflows() {- let generation = bridge_generation();- let Some(bridge) = generation.bridge else {- log::debug!("[medulla] no workflow bridge installed — not advertising workflows");- return;- };- let revision = REGISTRATION_SEQUENCE.begin();- let cancel = generation.cancel;- let connection_cancel = connection_generation();- // `list()` reads the host's store, so keep it off the socket runtime; a- // panicking bridge surfaces as a `JoinError` here instead of unwinding.- tokio::spawn(async move {- tokio::select! {- biased;- _ = cancel.cancelled() => {- log::debug!("[medulla] discarded workflow registration from an old bridge");- }- _ = connection_cancel.cancelled() => {- log::debug!("[medulla] discarded workflow registration from a closed socket");- }- _ = async move {- match read_batch(bridge).await {- Ok(batch) => {- let count = batch.workflows.len();- match REGISTRATION_SEQUENCE- .emit_if_newer(revision, || emit_batch(batch))- .await- {- SequencedEmit::Emitted => {- log::info!("[medulla] advertised {count} workflows to backend");- }- SequencedEmit::Superseded => log::debug!(- "[medulla] workflow registration snapshot already superseded by a newer \- successful read — not advertising"- ),- SequencedEmit::Failed => {- log::debug!("[medulla] workflow registration enqueue failed")- }- }- }- Err(err) => {- log::warn!("[medulla] workflow bridge list() failed — not advertising: {err}")- }- }- } => {}- }- });-}--/// The adverts this host currently publishes, for callers that need the list-/// itself rather than the registration frame — today the capability probe, which-/// carries the same descriptors in its reply bag. Empty when no bridge is-/// installed or the bridge failed, so a probe still answers.-pub async fn advertised_workflows() -> Vec<WorkflowDescriptor> {- advertised_workflows_for(bridge_generation().bridge).await-}--pub(super) async fn advertised_workflows_for(- bridge: Option<Arc<dyn WorkflowBridge>>,-) -> Vec<WorkflowDescriptor> {- let Some(bridge) = bridge else {- return Vec::new();- };- read_batch(bridge)- .await- .map(|batch| batch.workflows)- .unwrap_or_default()-}--/// Read one advert batch off the bridge on a blocking thread. An error or panic-/// remains a failed read — never an empty replacement or a partial batch.-async fn read_batch(bridge: Arc<dyn WorkflowBridge>) -> Result<RegisterWorkflows, String> {- match tokio::task::spawn_blocking(move || {- Ok(RegisterWorkflows {- workflows: bridge.try_list()?,- agent_id: bridge.agent_id(),- })- })- .await- {- Ok(batch) => batch,- Err(err) => Err(format!("the workflow store failed to list: {err}")),- }-}--async fn emit_batch(batch: RegisterWorkflows) -> bool {- super::emit_awaited(EVENT_REGISTER_WORKFLOWS, batch).await-}--/// Handle an inbound `medulla:workflow_request`.-///-/// Returns immediately: the work runs on its own task so a `copilot` turn (up to-/// ten minutes of agent time) cannot hold the socket read loop, the same shape-/// `medulla:task_run` and `orch:tool_call` already use.-pub fn handle_workflow_request(request: WorkflowRequest) {- let BridgeGeneration { bridge, cancel } = bridge_generation();- let connection_cancel = connection_generation();- tokio::spawn(async move {- tokio::select! {- biased;- _ = cancel.cancelled() => {- log::debug!("[medulla] discarded workflow request from an old bridge");- }- _ = connection_cancel.cancelled() => {- log::debug!("[medulla] discarded workflow request from a closed socket");- }- _ = async move {- let request_id = request.request_id.clone();- let op = request.op;- let outcome = match bridge {- Some(bridge) => dispatch(bridge, request).await,- None => Err("this agent has no workflow store installed".to_string()),- };- match &outcome {- Ok(_) => log::debug!("[medulla] workflow {op:?} request_id={request_id} ok"),- Err(err) => {- log::warn!("[medulla] workflow {op:?} request_id={request_id} failed: {err}")- }- }- super::emit_awaited(- EVENT_WORKFLOW_RESULT,- result_frame(request_id, outcome),- )- .await;- } => {}- }- });-}--/// Answer a `medulla:workflow_request` this build could not decode.-///-/// A frame with an unknown `op` (a newer backend) or a missing field would-/// otherwise be dropped, and a dropped request costs the backend the op's whole-/// deadline. The `requestId` is recovered from the raw JSON — without one there-/// is nothing to correlate, so the frame really is unanswerable and is only-/// logged.-pub fn reject_unparsed_request(raw: &Value, reason: &str) {- let Some(request_id) = raw.get("requestId").and_then(Value::as_str) else {- log::warn!("[medulla] undecodable workflow_request carries no requestId — cannot answer");- return;- };- super::emit(- EVENT_WORKFLOW_RESULT,- result_frame(- request_id.to_string(),- Err(format!("this agent could not read the request: {reason}")),- ),- );-}--/// Project a dispatch outcome onto the wire frame. Split out so the mapping-/// (which arm is populated, and that exactly one of them is) is directly-/// testable without a socket or a runtime.-fn result_frame(request_id: String, outcome: Result<Value, String>) -> WorkflowResult {- match outcome {- Ok(data) => WorkflowResult {- request_id,- ok: true,- data: Some(data),- error: None,- },- Err(error) => WorkflowResult {- request_id,- ok: false,- data: None,- error: Some(error),- },- }-}--/// Route one request to `bridge`. Every failure mode — a missing op argument, a-/// bridge error, a panicking bridge method — comes back as an `Err(String)` the-/// caller turns into `ok: false`.-///-/// The bridge is a parameter rather than read from the registry here so the-/// whole dispatch table is exercisable against a scripted bridge without-/// touching process-global state.-async fn dispatch(- bridge: Arc<dyn WorkflowBridge>,- request: WorkflowRequest,-) -> Result<Value, String> {- match request.op {- WorkflowOp::Get => {- let id = require_workflow_id(&request, "get")?;- blocking(move || bridge.get(&id)).await- }- WorkflowOp::NodeKinds => {- let kind = request.kind.clone();- blocking(move || bridge.node_kinds(kind.as_deref())).await- }- WorkflowOp::Runs => {- let id = require_workflow_id(&request, "runs")?;- blocking(move || bridge.runs(&id)).await- }- WorkflowOp::Copilot => {- let instruction = request- .instruction- .as_deref()- .map(str::trim)- .filter(|value| !value.is_empty())- .ok_or_else(|| "workflow copilot requires a non-empty instruction".to_string())?;- let turn = bridge.copilot(instruction, request.workflow_id.as_deref());- let outcome = catching_panics(turn).await??;- serde_json::to_value(outcome)- .map_err(|err| format!("failed to serialize the copilot outcome: {err}"))- }- }-}--/// The `workflowId` an op needs, or a message naming what was missing. Blank is-/// treated as absent: an empty id could only ever miss in the host's store, and-/// saying so up front beats a "not found" the reader cannot interpret.-fn require_workflow_id(request: &WorkflowRequest, op: &str) -> Result<String, String> {- request- .workflow_id- .as_deref()- .map(str::trim)- .filter(|id| !id.is_empty())- .map(str::to_string)- .ok_or_else(|| format!("workflow {op} requires a workflowId"))-}--/// Run a synchronous bridge read on a blocking thread, mapping a panic inside it-/// to an error rather than letting it unwind through the task.-async fn blocking<F>(read: F) -> Result<Value, String>-where- F: FnOnce() -> Result<Value, String> + Send + 'static,-{- match tokio::task::spawn_blocking(read).await {- Ok(result) => result,- Err(err) => Err(format!("the workflow store failed to answer: {err}")),- }-}--/// The async twin of [`blocking`]: run a bridge turn that must be awaited on the-/// socket runtime — today only `copilot` — and map a panic inside it to an error.-///-/// `copilot` cannot go on a blocking thread (it is a whole agent turn, not a-/// store read), so it does not inherit `spawn_blocking`'s `JoinError` net. Left-/// bare, a panicking `copilot` would abort the task that owes the backend a-/// `workflow_result` and cost it the op's whole ten-minute deadline. Caught-/// in-place rather than on a supervised child task so cancelling the answering-/// task still cancels the turn.-async fn catching_panics<F, T>(turn: F) -> Result<T, String>-where- F: Future<Output = T>,-{- match AssertUnwindSafe(turn).catch_unwind().await {- Ok(value) => Ok(value),- Err(panic) => {- let reason = panic- .downcast_ref::<&str>()- .copied()- .or_else(|| panic.downcast_ref::<String>().map(String::as_str))- .unwrap_or("unknown panic");- log::error!("[medulla] workflow copilot panicked: {reason}");- Err(format!(- "the workflow store failed to answer: the copilot panicked: {reason}"- ))- }- }-}--#[cfg(test)]-#[path = "workflows_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/platform/socket/medulla/workflows_tests.rs b/crates/openhuman-core/src/platform/socket/medulla/workflows_tests.rsdeleted file mode 100644index e17b154ef9..0000000000--- a/crates/openhuman-core/src/platform/socket/medulla/workflows_tests.rs+++ /dev/null@@ -1,329 +0,0 @@-use super::*;-use serde_json::json;--/// A bridge whose every read is scripted, so the dispatch table can be-/// exercised without a store.-#[derive(Default)]-struct FakeBridge {- fail: bool,- fail_list: bool,- panic_on_get: bool,- panic_on_copilot: bool,-}--#[async_trait]-impl WorkflowBridge for FakeBridge {- fn list(&self) -> Vec<WorkflowDescriptor> {- vec![WorkflowDescriptor {- id: "wf-1".into(),- name: "Deploy".into(),- description: String::new(),- node_count: 3,- enabled: None,- trigger_kind: None,- agent_id: None,- workspace_id: None,- inputs: Vec::new(),- }]- }-- fn try_list(&self) -> Result<Vec<WorkflowDescriptor>, String> {- if self.fail_list {- return Err("store unavailable".into());- }- Ok(self.list())- }-- fn get(&self, id: &str) -> Result<Value, String> {- if self.panic_on_get {- panic!("store exploded");- }- if self.fail {- return Err("no such workflow".into());- }- Ok(json!({ "id": id, "graph": [] }))- }-- fn node_kinds(&self, kind: Option<&str>) -> Result<Value, String> {- Ok(json!({ "kind": kind }))- }-- fn runs(&self, id: &str) -> Result<Value, String> {- Ok(json!({ "runs": [id] }))- }-- async fn copilot(- &self,- instruction: &str,- workflow_id: Option<&str>,- ) -> Result<CopilotOutcome, String> {- if self.panic_on_copilot {- panic!("copilot exploded");- }- if self.fail {- return Err("copilot refused".into());- }- Ok(CopilotOutcome {- reply: instruction.to_string(),- changes: vec![],- created: workflow_id.is_none().then(|| "wf-new".to_string()),- })- }-- fn agent_id(&self) -> Option<String> {- Some("orchestrator".into())- }-}--/// A scripted bridge, handed straight to `dispatch` — the tests never touch-/// the process-global registry, so they stay order- and thread-independent.-fn bridge_of(fail: bool, panic_on_get: bool) -> Arc<dyn WorkflowBridge> {- Arc::new(FakeBridge {- fail,- panic_on_get,- ..FakeBridge::default()- })-}--/// A bridge whose authoring turn panics mid-`await` — the async twin of-/// `panic_on_get`, and the one arm `blocking()` does not cover.-fn panicking_copilot_bridge() -> Arc<dyn WorkflowBridge> {- Arc::new(FakeBridge {- panic_on_copilot: true,- ..FakeBridge::default()- })-}--fn request(op: WorkflowOp) -> WorkflowRequest {- WorkflowRequest {- request_id: "r1".into(),- op,- workflow_id: None,- kind: None,- instruction: None,- agent_id: None,- }-}--#[test]-fn result_frame_populates_exactly_one_arm() {- let ok = result_frame("r1".into(), Ok(json!({ "a": 1 })));- assert!(ok.ok);- assert_eq!(ok.data, Some(json!({ "a": 1 })));- assert!(ok.error.is_none());-- let failed = result_frame("r1".into(), Err("boom".into()));- assert!(!failed.ok);- assert!(failed.data.is_none());- assert_eq!(failed.error.as_deref(), Some("boom"));-}--#[test]-fn connection_generation_cancels_work_at_each_lifetime_boundary() {- let mut generation = ConnectionGeneration::disconnected();- assert!(generation.snapshot().is_cancelled());-- generation.begin();- let connected = generation.snapshot();- assert!(!connected.is_cancelled());-- generation.end();- assert!(connected.is_cancelled());- assert!(generation.snapshot().is_cancelled());-}--#[test]-fn missing_workflow_id_is_reported_not_guessed() {- let mut req = request(WorkflowOp::Get);- assert_eq!(- require_workflow_id(&req, "get"),- Err("workflow get requires a workflowId".to_string())- );- // Blank is absent, not an id that will merely miss in the store.- req.workflow_id = Some(" ".into());- assert!(require_workflow_id(&req, "get").is_err());- req.workflow_id = Some(" wf-1 ".into());- assert_eq!(require_workflow_id(&req, "get"), Ok("wf-1".to_string()));-}--#[tokio::test]-async fn dispatch_routes_each_read_to_the_bridge() {- let bridge = bridge_of(false, false);- let mut get = request(WorkflowOp::Get);- get.workflow_id = Some("wf-1".into());- assert_eq!(- dispatch(Arc::clone(&bridge), get).await.unwrap(),- json!({ "id": "wf-1", "graph": [] })- );-- let mut kinds = request(WorkflowOp::NodeKinds);- kinds.kind = Some("agent".into());- assert_eq!(- dispatch(Arc::clone(&bridge), kinds).await.unwrap(),- json!({ "kind": "agent" })- );-- let mut runs = request(WorkflowOp::Runs);- runs.workflow_id = Some("wf-1".into());- assert_eq!(- dispatch(bridge, runs).await.unwrap(),- json!({ "runs": ["wf-1"] })- );-}--#[tokio::test]-async fn a_read_missing_its_workflow_id_fails_without_reaching_the_store() {- let outcome = dispatch(bridge_of(false, true), request(WorkflowOp::Get)).await;- // `panic_on_get` proves the store was never consulted.- assert_eq!(- outcome,- Err("workflow get requires a workflowId".to_string())- );-}--#[tokio::test]-async fn copilot_requires_an_instruction_and_reports_creation() {- let bridge = bridge_of(false, false);- // A blank instruction never reaches the host's agent.- let mut blank = request(WorkflowOp::Copilot);- blank.instruction = Some(" ".into());- assert!(dispatch(Arc::clone(&bridge), blank).await.is_err());-- let mut create = request(WorkflowOp::Copilot);- create.instruction = Some("build a deploy flow".into());- let data = dispatch(bridge, create).await.unwrap();- assert_eq!(data["reply"], "build a deploy flow");- assert_eq!(data["created"], "wf-new");-}--#[tokio::test]-async fn a_bridge_error_becomes_a_readable_failure() {- let bridge = bridge_of(true, false);- let mut get = request(WorkflowOp::Get);- get.workflow_id = Some("wf-1".into());- assert_eq!(- dispatch(Arc::clone(&bridge), get).await,- Err("no such workflow".to_string())- );-- let mut copilot = request(WorkflowOp::Copilot);- copilot.instruction = Some("change it".into());- assert_eq!(- dispatch(bridge, copilot).await,- Err("copilot refused".to_string())- );-}--#[tokio::test]-async fn a_list_error_is_not_converted_to_an_empty_registration() {- let bridge: Arc<dyn WorkflowBridge> = Arc::new(FakeBridge {- fail_list: true,- ..FakeBridge::default()- });- assert_eq!(- read_batch(bridge).await.unwrap_err(),- "store unavailable".to_string()- );-}--#[tokio::test]-async fn a_newer_registration_suppresses_an_older_snapshot() {- let sequencer = RegistrationSequencer::new();- let older = sequencer.begin();- let newer = sequencer.begin();- let emitted = std::sync::Mutex::new(Vec::new());-- assert_eq!(- sequencer- .emit_if_newer(newer, || async {- emitted.lock().unwrap().push("newer");- true- })- .await,- SequencedEmit::Emitted- );- assert_eq!(- sequencer- .emit_if_newer(older, || async {- emitted.lock().unwrap().push("older");- true- })- .await,- SequencedEmit::Superseded- );- assert_eq!(*emitted.lock().unwrap(), vec!["newer"]);-}--#[tokio::test]-async fn a_failed_newer_read_does_not_suppress_an_older_success() {- let sequencer = RegistrationSequencer::new();- let older = sequencer.begin();- let _newer = sequencer.begin();- let emitted = std::sync::Mutex::new(Vec::new());-- // The newer read failed, so it never calls `emit_if_newer`. The older- // successful snapshot must still advance the backend from its- // pre-mutation state.- assert_eq!(- sequencer- .emit_if_newer(older, || async {- emitted.lock().unwrap().push("older");- true- })- .await,- SequencedEmit::Emitted- );- assert_eq!(*emitted.lock().unwrap(), vec!["older"]);-}--#[tokio::test]-async fn a_failed_enqueue_does_not_advance_the_success_watermark() {- let sequencer = RegistrationSequencer::new();- let older = sequencer.begin();- let newer = sequencer.begin();-- assert_eq!(- sequencer.emit_if_newer(newer, || async { false }).await,- SequencedEmit::Failed- );- assert_eq!(- sequencer.emit_if_newer(older, || async { true }).await,- SequencedEmit::Emitted- );-}--#[tokio::test]-async fn a_panicking_bridge_still_answers() {- let mut get = request(WorkflowOp::Get);- get.workflow_id = Some("wf-1".into());- let outcome = dispatch(bridge_of(false, true), get).await;- // The request must not be dropped — a dropped one costs the server its- // whole deadline.- assert!(outcome- .unwrap_err()- .starts_with("the workflow store failed to answer"));-}--#[tokio::test]-async fn a_panicking_copilot_still_answers() {- let mut copilot = request(WorkflowOp::Copilot);- copilot.instruction = Some("build a deploy flow".into());- let outcome = dispatch(panicking_copilot_bridge(), copilot).await;- // A panic inside the authoring turn must come back as an answer, not- // abort the task that owes the backend a frame: an unanswered copilot- // costs the server its whole ten-minute deadline.- assert!(outcome- .clone()- .unwrap_err()- .starts_with("the workflow store failed to answer"));- let frame = result_frame("r1".into(), outcome);- assert!(!frame.ok);- assert!(frame.error.is_some());-}--#[test]-fn an_undecodable_frame_without_a_request_id_is_only_logged() {- // Nothing to correlate, so nothing can be answered — but it must not- // panic on the socket read path either.- reject_unparsed_request(&json!({ "op": "apply_ops" }), "unknown variant");-}diff --git a/crates/openhuman-core/src/platform/socket/mod.rs b/crates/openhuman-core/src/platform/socket/mod.rsindex e76996cdbb..9579859e79 100644--- a/crates/openhuman-core/src/platform/socket/mod.rs+++ b/crates/openhuman-core/src/platform/socket/mod.rs@@ -6,7 +6,6 @@mod event_handlers;pub mod manager;-pub mod medulla;mod ops;mod schemas;pub(crate) mod token_provider;diff --git a/crates/openhuman-core/src/platform/socket/ops.rs b/crates/openhuman-core/src/platform/socket/ops.rsindex eb1aa890e7..869a94d85d 100644--- a/crates/openhuman-core/src/platform/socket/ops.rs+++ b/crates/openhuman-core/src/platform/socket/ops.rs@@ -6,11 +6,9 @@ async fn connect_static_using(manager: &SocketManager,url: &str,token: &str,- clear_workflows: impl FnOnce(),) -> Result<SocketState, String> {let _rebind = manager.lock_identity_rebind().await;manager.disconnect().await?;- clear_workflows();manager.connect(url, token).await?;Ok(manager.get_state())}@@ -20,14 +18,8 @@ pub async fn connect_static(url: &str,token: &str,) -> Result<SocketState, String> {- log::info!("[socket:rpc] connect — disabling identity-bound workflow plane");- connect_static_using(- manager,- url,- token,- super::medulla::workflows::clear_workflow_bridge,- )- .await+ log::info!("[socket:rpc] connect");+ connect_static_using(manager, url, token).await}pub async fn disconnect(manager: &SocketManager) -> Result<SocketState, String> {@@ -37,40 +29,22 @@ pub async fn disconnect(manager: &SocketManager) -> Result<SocketState, String>Ok(manager.get_state())}-/// Shared body of [`connect_with_session`], with the credential lookup and the-/// workflow-bridge install lifted out so the transaction can be driven directly-/// from tests.-///-/// The `manager.is_live_for` short-circuit is the fix for #6181: the core's-/// bootstrap auto-connect and this RPC both fire on a cold start, roughly two-/// seconds apart, and each used to tear the other's freshly handshaked socket-/// down. When the live connection already serves this exact url+token there is-/// no second EIO session to open.-///-/// The socket is reusable; the workflow bridge is not. It is pinned to a-/// `Config` that a workspace switch invalidates, and `connect_static` clears it-/// outright while leaving a matching connection identity behind — so skipping-/// `install_bridge` on the reuse path would leave the workflow plane pointing at-/// a stale workspace, or disabled entirely. `set_workflow_bridge` re-advertises-/// over an already-`ready` socket by design, so the install runs on both paths-/// and only the handshake is skipped.+/// Connect with a session token, reusing a live socket for the same identity.+/// The identity lock serializes concurrent bootstrap and RPC connections.async fn connect_with_session_using(manager: &SocketManager,url: &str,token: &str,provider: super::token_provider::TokenProvider,- install_bridge: impl FnOnce(),) -> Result<SocketState, String> {let _rebind = manager.lock_identity_rebind().await;if manager.is_live_for(url, token) {- install_bridge();log::info!("[socket:rpc] connect_with_session — {url} already connected with this session; reusing the live socket");return Ok(manager.get_state());}manager.disconnect().await?;- install_bridge();manager.connect_with_provider(url, provider).await?;Ok(manager.get_state())}@@ -85,15 +59,7 @@ pub async fn connect_with_session(manager: &SocketManager) -> Result<SocketStatelet provider =super::token_provider::token_provider_from_config(std::sync::Arc::clone(&config));- connect_with_session_using(manager, &api_url, &token, provider, move || {- #[cfg(feature = "flows")]- if crate::core::runtime::context::CoreContext::current()- .is_some_and(|context| context.domains().flows)- {- crate::flows::medulla_bridge::install(config);- }- })- .await+ connect_with_session_using(manager, &api_url, &token, provider).await}#[cfg(test)]diff --git a/crates/openhuman-core/src/platform/socket/ops_tests.rs b/crates/openhuman-core/src/platform/socket/ops_tests.rsindex e97cfb75cb..351da2c66f 100644--- a/crates/openhuman-core/src/platform/socket/ops_tests.rs+++ b/crates/openhuman-core/src/platform/socket/ops_tests.rs@@ -2,26 +2,6 @@ use std::sync::atomic::{AtomicBool, Ordering};use super::*;-#[tokio::test]-async fn static_token_connection_clears_identity_state_after_disconnect() {- let manager = SocketManager::new();- manager- .connect("http://127.0.0.1:1", "opaque-token")- .await- .unwrap();- let cleared = AtomicBool::new(false);- connect_static_using(&manager, "http://127.0.0.1:1", "replacement", || {- assert_eq!(- manager.get_state().status,- crate::platform::socket::types::ConnectionStatus::Disconnected- );- cleared.store(true, Ordering::SeqCst);- })- .await- .unwrap();- assert!(cleared.load(Ordering::SeqCst));-}-// ── Redundant-connect suppression (#6181) ──────────────────────────use std::sync::atomic::AtomicUsize;use std::sync::Arc;@@ -157,13 +137,11 @@ async fn a_redundant_session_connect_reuses_the_live_socket() {bootstrap_auto_connect(&manager, &url, TOKEN_A).await;- let bridge_installed = AtomicBool::new(false);let state = connect_with_session_using(&manager,&url,TOKEN_A,static_token_provider(TOKEN_A.to_string()),- || bridge_installed.store(true, Ordering::SeqCst),).await.unwrap();@@ -177,55 +155,6 @@ async fn a_redundant_session_connect_reuses_the_live_socket() {// The caller gets the live socket's state back, not the `Connecting` of a// handshake that has only just been kicked off.assert_eq!(state.status, ConnectionStatus::Connected);- // Reusing the socket must not skip the bridge: it is pinned to a `Config`,- // and `connect_static` can have cleared it while leaving a matching identity- // behind, so the workflow plane would be left stale or disabled.- assert!(- bridge_installed.load(Ordering::SeqCst),- "reusing the socket skipped the workflow-bridge install"- );-}--/// The bridge half of the reuse path, end to end through the operation that-/// clears it: `openhuman.socket_connect` disables the identity-bound workflow-/// plane and leaves a matching connection identity behind, so a following-/// `connect_with_session` for the same url+token must still restore it.-#[tokio::test]-async fn a_reused_socket_still_restores_a_bridge_a_static_connect_cleared() {- let (accepts, addr) = spawn_accept_counting_eio_server().await;- let url = format!("http://{addr}");- let manager = SocketManager::new();-- let cleared = AtomicBool::new(false);- connect_static_using(&manager, &url, TOKEN_A, || {- cleared.store(true, Ordering::SeqCst)- })- .await- .unwrap();- wait_for_connected(&manager).await;- assert!(cleared.load(Ordering::SeqCst));-- let bridge_installed = AtomicBool::new(false);- connect_with_session_using(- &manager,- &url,- TOKEN_A,- static_token_provider(TOKEN_A.to_string()),- || bridge_installed.store(true, Ordering::SeqCst),- )- .await- .unwrap();-- settle_for_a_second_accept(&accepts).await;- assert!(- bridge_installed.load(Ordering::SeqCst),- "the workflow plane stayed disabled after a static connect cleared it"- );- assert_eq!(- accepts.load(Ordering::SeqCst),- 1,- "restoring the bridge should not cost a fresh EIO session"- );}/// `ws_loop` re-reads the token provider before every attempt, so a session@@ -270,7 +199,7 @@ async fn a_token_refreshed_mid_loop_updates_the_recorded_identity() {/// The other half of the guard: an account switch keeps the same backend URL but/// arrives with a different token, and must still disconnect, rebind the-/// identity-bound workflow plane, and reconnect.+/// socket identity, and reconnect.#[tokio::test]async fn a_session_connect_with_a_different_token_still_rebinds() {let (accepts, addr) = spawn_accept_counting_eio_server().await;@@ -279,22 +208,16 @@ async fn a_session_connect_with_a_different_token_still_rebinds() {bootstrap_auto_connect(&manager, &url, TOKEN_A).await;- let bridge_installed = AtomicBool::new(false);connect_with_session_using(&manager,&url,TOKEN_B,static_token_provider(TOKEN_B.to_string()),- || bridge_installed.store(true, Ordering::SeqCst),).await.unwrap();wait_for_connected(&manager).await;- assert!(- bridge_installed.load(Ordering::SeqCst),- "a new session token must still rebind the identity-bound workflow plane"- );assert_eq!(accepts.load(Ordering::SeqCst),2,@@ -418,13 +341,11 @@ async fn a_session_connect_during_the_boot_handshake_does_not_restart_it() {wait_for_mid_handshake(&manager, &accepts).await;// The renderer's RPC lands in that window with the same url+token.- let bridge_installed = AtomicBool::new(false);connect_with_session_using(&manager,&url,TOKEN_A,static_token_provider(TOKEN_A.to_string()),- || bridge_installed.store(true, Ordering::SeqCst),).await.unwrap();@@ -444,12 +365,6 @@ async fn a_session_connect_during_the_boot_handshake_does_not_restart_it() {1,"a connect arriving mid-handshake opened a second EIO session");- // The socket is reused, but the bridge is pinned to a `Config` and must- // still be installed on the reuse path.- assert!(- bridge_installed.load(Ordering::SeqCst),- "reusing an in-flight handshake skipped the workflow-bridge install"- );}/// The guard widened to `Connecting`, so it must not be satisfied by a stalediff --git a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rsindex 2f89137a27..b853ed596d 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs@@ -2,7 +2,6 @@//! parsing.use crate::platform::socket::manager::emit_state_change;-use crate::platform::socket::medulla::workflows;use crate::platform::socket::types::ConnectionStatus;use std::sync::Arc;@@ -104,7 +103,6 @@ pub(super) fn handle_sio_packet(b'1' => {// Socket.IO DISCONNECTlog::info!("[socket] SIO DISCONNECT from server");- workflows::end_connection_generation();*shared.status.write() = ConnectionStatus::Disconnected;*shared.socket_id.write() = None;emit_state_change(shared);diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rsindex 29d01520d2..aaff387983 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs@@ -1,7 +1,6 @@//! The reconnect loop: [`ws_loop`], its failure-escalation logging, the//! invalid-token retry decision, and the emit-queue drain used on shutdown.-use crate::platform::socket::medulla::workflows;use std::sync::atomic::Ordering;use std::sync::Arc;@@ -213,7 +212,6 @@ pub(crate) async fn ws_loop(// session-expired escalation below — not just explicit// `SocketManager::disconnect()` (CodeRabbit #4355).shared.ack_registry.cancel_all();- workflows::end_connection_generation();match &outcome {ConnectionOutcome::Lost(_) => {diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rsindex 2e7541b62d..8e332a21c6 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@ -480,7 +480,6 @@ async fn clear_session_credential(config: &Config) -> Result<RpcOutcome<bool>, Stracing::warn!(%error, "{LOG_PREFIX} failed to disconnect backend socket on sign-out");}}- crate::platform::socket::medulla::workflows::clear_workflow_bridge();deactivate_user_scope()?;stop_credential_gated_services(config).await;diff --git a/crates/openhuman-core/src/security/keyring/README.md b/crates/openhuman-core/src/security/keyring/README.mdindex 151b4e81cc..7d346b7646 100644--- a/crates/openhuman-core/src/security/keyring/README.md+++ b/crates/openhuman-core/src/security/keyring/README.md@@ -66,7 +66,7 @@ Secret storage backend, selected once and frozen in a `OnceLock`:Workspace dir resolves from `init_workspace`, else `OPENHUMAN_WORKSPACE`, else `~/.openhuman` (or `~/.openhuman-staging` under `OPENHUMAN_APP_ENV=staging`). **In `cfg(test)` builds only**, that rule is bypassed — see the test-isolation note below.-Both file backends keep every secret in one file, so a `set` of one key rewrites all of them. That read-modify-write cycle is guarded by `file_store::lock_for_write` — an in-process mutex is not sufficient, because a desktop core, a `medulla` TUI embedding the same core, and a `cargo test` run that inherited `OPENHUMAN_WORKSPACE` all address the same path.+Both file backends keep every secret in one file, so a `set` of one key rewrites all of them. That read-modify-write cycle is guarded by `file_store::lock_for_write` — an in-process mutex is not sufficient, because a desktop core, another process embedding the same core, and a `cargo test` run that inherited `OPENHUMAN_WORKSPACE` all address the same path.## Dependenciesdiff --git a/crates/openhuman-core/src/security/keyring/backend.rs b/crates/openhuman-core/src/security/keyring/backend.rsindex 6149ade446..55ccf48f36 100644--- a/crates/openhuman-core/src/security/keyring/backend.rs+++ b/crates/openhuman-core/src/security/keyring/backend.rs@@ -109,7 +109,7 @@ impl KeyringBackend for OsBackend {/// Every secret lives in this one file, so a `set` or `delete` is a read →/// modify → write cycle over *all* of them. That cycle is guarded by the/// cross-process advisory lock in [`file_store::lock_for_write`] — an in-process-/// mutex is not enough, because a desktop core, a `medulla` TUI embedding the+/// mutex is not enough, because a desktop core, another process embedding the/// same core, and a `cargo test` run that inherited `OPENHUMAN_WORKSPACE` all/// address the same path. Unguarded, the later writer's map (read before the/// earlier writer landed) silently discards the earlier one's secret; when thatdiff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rsindex 881542b16e..2ab63f3397 100644--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs@@ -177,7 +177,7 @@ fn master_key() -> Option<&'static [u8; KEY_LEN]> {/// whole set, guarded by the cross-process advisory lock in/// [`file_store::lock_for_write`]. An in-process mutex would not do: more than/// one process routinely addresses the same workspace (a desktop core and a-/// `medulla` TUI embedding the same core), and the later writer's snapshot —+/// second process embedding the same core), and the later writer's snapshot —/// read before the earlier writer landed — silently drops the earlier secret.pub struct EncryptedFileBackend {path: PathBuf,diff --git a/crates/openhuman-core/src/security/keyring/file_store.rs b/crates/openhuman-core/src/security/keyring/file_store.rsindex 3dc561a49d..04b93570c1 100644--- a/crates/openhuman-core/src/security/keyring/file_store.rs+++ b/crates/openhuman-core/src/security/keyring/file_store.rs@@ -4,7 +4,7 @@//! keep every secret in **one** file and mutate it with a read → modify → write//! cycle. That shape is fine within a process — a mutex covers it — and unsafe//! across processes, which is the configuration this codebase actually runs in:-//! a desktop core, a `medulla` TUI embedding the same core, and any `cargo test`+//! a desktop core, another process embedding the same core, and any `cargo test`//! run that inherits `OPENHUMAN_WORKSPACE` all address the same file.//!//! Two failures follow from doing that unguarded, and both destroy secretsdiff --git a/crates/openhuman-core/src/tools/ops_tests.rs b/crates/openhuman-core/src/tools/ops_tests.rsindex 5d874ba3be..15ec76e1ed 100644--- a/crates/openhuman-core/src/tools/ops_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests.rs@@ -358,14 +358,7 @@ const TOOL_LESS: &[crate::core::all::DomainGroup] = {// `Channels` joined this list when the three `whatsapp_data_*` tools went —// the channel runtime,// its controllers and its inbound dispatch are all still there.- &[- G::Config,- G::Security,- G::Medulla,- G::Modules,- G::Channels,- G::Hosted,- ]+ &[G::Config, G::Security, G::Modules, G::Channels, G::Hosted]};// ---- tool_capability() drift guard (M5.3) ----------------------------------diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex 8965ce6a6e..ad76661637 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -24,7 +24,6 @@ flows = ["openhuman-core/flows"]skills = ["openhuman-core/skills"]mcp = ["openhuman-core/mcp"]crash-reporting = ["openhuman-core/crash-reporting"]-medulla = ["openhuman-core/medulla"]channels = ["openhuman-core/channels"]sandbox-landlock = ["openhuman-core/sandbox-landlock"]sandbox-bubblewrap = ["openhuman-core/sandbox-bubblewrap"]diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.mdindex 1a3013dec4..3cca3715d9 100644--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@ -1,7 +1,7 @@# `openhuman-embed``openhuman-embed` is the host-facing library package for products that run the-OpenHuman core in-process, including Medulla and OpenCompany. It re-exports the+OpenHuman core in-process, including OpenCompany. It re-exports theruntime builder from `openhuman-core` and owns the typed embedding facade.Use the default contributor feature set:@@ -176,8 +176,7 @@ println!("{}", second.reply);`Core` is the typed facade shown at the top: a host that already built a`CoreRuntime` wraps it with `Core::from_runtime` and reaches sub-facades —-`config()`, `auth()`, `agent()` (a `CoreAgent` running the orchestrator),-and, behind the `medulla` feature, `medulla()`.+`config()`, `auth()`, and `agent()` (a `CoreAgent` running the orchestrator).### One runtime per process@@ -258,16 +257,12 @@ Every feature on this crate is a pass-through to the same-named feature on`openhuman-core` (package `openhuman`): `default`, `http-server`,`inference`, `documents`, `hosting`, `modules`, `voice`, `web3`,`runtime-node`, `contacts`, `media`, `flows`, `skills`, `mcp`,-`crash-reporting`, `medulla`, `channels`, `sandbox-landlock`,+`crash-reporting`, `channels`, `sandbox-landlock`,`sandbox-bubblewrap`, `browser-native`, `whatsapp-web`,`file-logging`, `scheduler-gate`.-Three of them also gate items on this crate's own public surface:+Two of them also gate items on this crate's own public surface:-- `medulla` — `Core::medulla()`, `HarnessCore::medulla()`, and the Medulla- session types (`Medulla`, `MedullaStatus`, `SessionSummary`,- `SessionDetail`, `SessionCreated`, `Message`, `SendResult`, `AbortResult`,- `RosterWorker`, `WireEventEnvelope`).- `mcp` — `HttpHeader`, `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and`HarnessBuilder::mcp`.- `skills` — `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.diff --git a/crates/openhuman-embed/src/config.rs b/crates/openhuman-embed/src/config.rsindex ef6b0da5d8..09e047a4cf 100644--- a/crates/openhuman-embed/src/config.rs+++ b/crates/openhuman-embed/src/config.rs@@ -1,6 +1,6 @@//! Config sub-facade — the first typed surface, and the proof of the pattern.//!-//! Every other sub-facade (memory, workflows, chat, medulla, …) follows the+//! Every other sub-facade (memory, workflows, chat, …) follows the//! shape established here://!//! 1. A borrowed newtype over `&Arc<CoreRuntime>` — zero-cost, no state.diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex 4c0886d0e1..31dde37ddd 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -1,7 +1,7 @@//! Error type for the embedded typed facade.//!//! Every [`super::Core`] method returns [`CoreError`]. The variants exist to let-//! an embedding host (the Medulla TUI, a CLI, a test) tell four genuinely+//! an embedding host (a TUI, a CLI, a test) tell four genuinely//! different situations apart without parsing strings://!//! - [`CoreError::Domain`] — the domain rejected the call and said why, via thediff --git a/crates/openhuman-embed/src/harness/mod.rs b/crates/openhuman-embed/src/harness/mod.rsindex 8c45026b9c..667b9ce815 100644--- a/crates/openhuman-embed/src/harness/mod.rs+++ b/crates/openhuman-embed/src/harness/mod.rs@@ -138,11 +138,6 @@ impl<'a> HarnessCore<'a> {pub fn auth(&self) -> crate::Auth<'_> {self.core.auth()}-- #[cfg(feature = "medulla")]- pub fn medulla(&self) -> crate::Medulla<'_> {- self.core.medulla()- }}impl Harness {diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 59ca4025fd..480b140069 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -92,8 +92,6 @@ mod config;mod core_agent;mod error;mod harness;-#[cfg(feature = "medulla")]-mod medulla;mod runtime;mod turn;@@ -109,11 +107,6 @@ pub use harness::{};#[cfg(feature = "mcp")]pub use harness::{HttpHeader, McpAuthConfig, McpServer};-#[cfg(feature = "medulla")]-pub use medulla::{- AbortResult, Medulla, MedullaStatus, Message, RosterWorker, SendResult, SessionCreated,- SessionDetail, SessionSummary, WireEventEnvelope,-};pub use runtime::{ApiKey, Runtime, RuntimeBuilder, RuntimeError};pub use turn::{absolute, Route, Turn, TurnOutcome, TurnRequest};@@ -170,15 +163,6 @@ impl Core {CoreAgent(&self.rt)}- /// Typed access to the Medulla orchestration backend.- ///- /// Absent unless the `medulla` feature is on, so a host built without it- /// fails to compile against this rather than meeting a runtime error.- #[cfg(feature = "medulla")]- pub fn medulla(&self) -> Medulla<'_> {- Medulla(&self.rt)- }-/// The underlying runtime, for anything this facade does not yet model.////// An escape hatch, not the intended path — every use is a candidate for adiff --git a/crates/openhuman-embed/src/medulla.rs b/crates/openhuman-embed/src/medulla.rsdeleted file mode 100644index 83b3f60f65..0000000000--- a/crates/openhuman-embed/src/medulla.rs+++ /dev/null@@ -1,165 +0,0 @@-//! Medulla sub-facade — typed access to the Medulla orchestration backend.-//!-//! Follows the shape [`super::config`] established: a borrowed newtype over the-//! runtime, and two-line methods delegating to [`call`](super::call::call).-//!-//! # Types are re-exported, not redefined-//!-//! [`MedullaStatus`], [`SessionSummary`] and [`RosterWorker`] come straight from-//! the domain rather than being mirrored here. A parallel set of facade structs-//! would be one more thing to keep in step with the wire contract, and the whole-//! point of the domain owning them is that there is a single definition.-//!-//! # Gating-//!-//! Compiled only with the `medulla` feature, like the domain it wraps. With the-//! feature off `Core::medulla()` does not exist, so a host that cannot use it-//! fails to compile against it rather than discovering an error at runtime.--use std::sync::Arc;--use super::call::call;-use super::error::CoreError;-use openhuman_core::core::runtime::CoreRuntime;--pub use openhuman_core::medulla::client::{- AbortResult, Message, RosterWorker, SendResult, SessionCreated, SessionDetail, SessionSummary,- WireEventEnvelope,-};-pub use openhuman_core::medulla::ops::MedullaStatus;--/// Typed access to the Medulla backend.-///-/// Obtained from [`Core::medulla`](super::Core::medulla); never constructed-/// directly.-pub struct Medulla<'a>(pub(super) &'a Arc<CoreRuntime>);--impl Medulla<'_> {- /// Whether the integration is configured and signed in.- ///- /// Makes no network call and does not fail on an unconfigured host — the- /// result carries a `configured` flag and a stable reason instead. A host- /// polls this to decide whether to show the Medulla surface at all, so- /// "not set up" has to be a value it can render, not an error it must- /// special-case.- pub async fn status(&self) -> Result<MedullaStatus, CoreError> {- call(self.0, "openhuman.medulla_status", serde_json::json!({})).await- }-- /// List the operator's durable sessions.- ///- /// # Errors- ///- /// [`CoreError::Domain`] with `kind = "MedullaNoBaseUrl"` or- /// `"MedullaNoSessionToken"` when the integration is not usable, both- /// flagged `expected_user_state` so a host renders a notice rather than a- /// failure. Backend rejections carry the backend's own `errorCode` as- /// `kind`, and HTTP 401/403 are likewise `expected_user_state`.- pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>, CoreError> {- call(- self.0,- "openhuman.medulla_list_sessions",- serde_json::json!({}),- )- .await- }-- /// Create a durable session.- ///- /// `title` is optional — the backend names an untitled session itself- /// rather than the host inventing one.- pub async fn create_session(&self, title: Option<&str>) -> Result<SessionCreated, CoreError> {- call(- self.0,- "openhuman.medulla_create_session",- serde_json::json!({ "title": title }),- )- .await- }-- /// Fetch one session's state.- pub async fn get_session(&self, session_id: &str) -> Result<SessionDetail, CoreError> {- call(- self.0,- "openhuman.medulla_get_session",- serde_json::json!({ "sessionId": session_id }),- )- .await- }-- /// Send a message to a session.- ///- /// `sync = false` returns as soon as the backend accepts the turn, leaving- /// the reply to arrive over the event stream; `true` blocks until it- /// replies. A UI wants the former so it can render progress, a scripted- /// caller usually wants the latter.- pub async fn send_message(- &self,- session_id: &str,- body: &str,- sync: bool,- ) -> Result<SendResult, CoreError> {- call(- self.0,- "openhuman.medulla_send_message",- serde_json::json!({ "sessionId": session_id, "body": body, "sync": sync }),- )- .await- }-- /// Abort a session's running cycle.- pub async fn abort(&self, session_id: &str) -> Result<AbortResult, CoreError> {- call(- self.0,- "openhuman.medulla_abort",- serde_json::json!({ "sessionId": session_id }),- )- .await- }-- /// Replay a session's messages after `after`.- ///- /// `after` is a cursor, not a page offset: passing the last seq already- /// seen returns only what is new, which is what makes a reconnect cheap.- pub async fn list_messages(- &self,- session_id: &str,- after: Option<i64>,- ) -> Result<Vec<Message>, CoreError> {- call(- self.0,- "openhuman.medulla_list_messages",- serde_json::json!({ "sessionId": session_id, "after": after }),- )- .await- }-- /// Replay a session's events after `after`.- ///- /// Same cursor semantics as [`list_messages`](Self::list_messages).- pub async fn list_events(- &self,- session_id: &str,- after: Option<i64>,- ) -> Result<Vec<WireEventEnvelope>, CoreError> {- call(- self.0,- "openhuman.medulla_list_events",- serde_json::json!({ "sessionId": session_id, "after": after }),- )- .await- }-- /// Read the roster of workers currently connected to the backend.- ///- /// # Errors- ///- /// Same shape as [`list_sessions`](Self::list_sessions).- pub async fn roster(&self) -> Result<Vec<RosterWorker>, CoreError> {- call(self.0, "openhuman.medulla_roster", serde_json::json!({})).await- }-}--#[cfg(test)]-#[path = "medulla_tests.rs"]-mod tests;diff --git a/crates/openhuman-embed/src/medulla_tests.rs b/crates/openhuman-embed/src/medulla_tests.rsdeleted file mode 100644index 599a856009..0000000000--- a/crates/openhuman-embed/src/medulla_tests.rs+++ /dev/null@@ -1,33 +0,0 @@-use openhuman_core::medulla::all_medulla_registered_controllers;--/// Every method this facade dispatches must name a registered controller.-///-/// The facade's method names are strings; a typo or a renamed controller-/// would otherwise surface as `CoreError::Unavailable` at runtime, which is-/// indistinguishable from a domain the host gated off on purpose. Pinning-/// them here turns that into a test failure.-#[test]-fn every_dispatched_method_is_registered() {- let registered: Vec<String> = all_medulla_registered_controllers()- .iter()- .map(|c| c.rpc_method_name())- .collect();-- for method in [- "openhuman.medulla_status",- "openhuman.medulla_list_sessions",- "openhuman.medulla_create_session",- "openhuman.medulla_get_session",- "openhuman.medulla_send_message",- "openhuman.medulla_abort",- "openhuman.medulla_list_messages",- "openhuman.medulla_list_events",- "openhuman.medulla_roster",- ] {- assert!(- registered.iter().any(|m| m == method),- "facade dispatches `{method}`, which no controller registers. \- Registered: {registered:?}"- );- }-}diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 43c1df89aa..9b4231d7af 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -245,7 +245,7 @@ impl Runtime {ids}- /// Typed access to non-turn core domains (config, auth, medulla).+ /// Typed access to non-turn core domains (config, auth).////// Turns belong to agents: this facade deliberately exposes neither the/// orchestrator agent nor the raw runtime, so no turn can bypass andiff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.tomlindex 4f6f309be4..0001244c63 100644--- a/crates/openhuman-tinyhumans/Cargo.toml+++ b/crates/openhuman-tinyhumans/Cargo.toml@@ -32,7 +32,6 @@ flows = ["openhuman-embed/flows"]skills = ["openhuman-embed/skills"]mcp = ["openhuman-embed/mcp"]crash-reporting = ["openhuman-embed/crash-reporting"]-medulla = ["openhuman-embed/medulla"]channels = ["openhuman-embed/channels"]sandbox-landlock = ["openhuman-embed/sandbox-landlock"]sandbox-bubblewrap = ["openhuman-embed/sandbox-bubblewrap"]diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 48a4ea3282..f181685073 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -83,7 +83,7 @@ Canonical mapping of every product feature to its test source(s). Drives gap-fil| 1.3.1 | Token Issuance | WD+RU+RI | `login-flow.spec.ts`, `crates/openhuman-tinyhumans/src/session/{client,manager}_tests.rs`, `json_rpc_e2e.rs` | ✅ | || 1.3.2 | Session Persistence | WD+RU | `logout-relogin-onboarding.spec.ts`, `crates/openhuman-core/src/security/credentials/ops_credential_tests.rs` | ✅ | || 1.3.3 | Refresh Token Rotation | VU | _missing_ — tracked #968 | ❌ | Slice-level refresh logic |-| 1.3.4 | Product Identity Header (`x-sdk-name`) | RU | `crates/openhuman-core/src/api/product.rs`, `crates/openhuman-core/src/api/rest_tests.rs`, `crates/openhuman-tinyhumans/src/session/client_tests.rs`, `crates/openhuman-core/src/medulla/client/tests/{integration_tests,sse_tests}.rs`, `crates/openhuman-core/src/integrations/client_tests.rs` | ✅ | #5406 — every backend-bound request is attributed to a product, defaulting to `openhuman` and overridable by an embedding product (OpenCompany, Medulla). RU covers the sanitiser (trim / allowlist / truncate / reject), the default, and the override on the wire across all four transports: the SDK path, `raw_client()`, `MedullaClient::authed`, and the SSE handshake (which authenticates by query parameter and so never reaches `authed()`). Managed embeddings go out through `tinyagents`' own clients and Socket.IO sets no HTTP headers, so neither is covered here. |+| 1.3.4 | Product Identity Header (`x-sdk-name`) | RU | `crates/openhuman-core/src/api/product.rs`, `crates/openhuman-core/src/api/rest_tests.rs`, `crates/openhuman-tinyhumans/src/session/client_tests.rs`, `crates/openhuman-core/src/integrations/client_tests.rs` | ✅ | #5406 — backend requests carry a sanitized product identity. RU covers the sanitizer, default, and override on the SDK and raw HTTP client paths. || 1.3.5 | Credential handoff to core (`auth.set_credential`) | RU+RI | `crates/openhuman-core/src/security/credentials/ops_credential_tests.rs`, `crates/openhuman-tinyhumans/src/session/link_tests.rs`, `tests/config_auth_app_state_connectivity_e2e.rs`, `tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs` | ✅ | The core takes a JWT / API key / local token as given (no `/auth/me`): expired JWTs and sessions without a user id are refused, same-token/same-user is a cheap refresh, a different user is signed out first, the snapshot reports the handed-over user and never calls the backend. |### 1.4 Logout & Revocation@@ -530,11 +530,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an| 11.2.2 | Memory Graph Controls | WD | `insights-dashboard.spec.ts` | ✅ | Brain Graph tab actions toolbar || 11.2.3 | Memory Graph Surface | WD | `insights-dashboard.spec.ts` | ✅ | Populated SVG or empty-state graph surface |-### 11.3 Local Medulla Supervision--| ID | Feature | Layer | Test path(s) | Status | Notes |-| ------ | --------------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 11.3.3 | Local medulla-serve supervision (`medulla_local` RPC, Flavor A draft) | RU+RI | — | ❌ | Removed: the `medulla_local` supervised-child draft and its `medulla-local` feature were deleted in favour of the `medulla` HTTP/SSE client (`crates/openhuman-core/src/medulla/`); row kept for the feature ID. Historical notes: behind the default-ON `medulla-local` feature. Unit tests drive the supervisor's handshake seam against a mock connector: restart-and-retry fires only on mid-request transport death of an idempotent op (exactly one respawn); the non-idempotent `instruct` is never replayed — a transport break surfaces the typed `MaybeApplied` error with no duplicate submission; an overall per-request deadline (`subconscious.medulla_local.request_deadline_secs`, default 300s) bounds a request even while the child keeps streaming frames or while a serve→host port callback (`inference.invoke`/`tools.invoke`) hangs on a stalled provider/tool — tripping as the typed transport error (`MaybeApplied` for `instruct`, restart-and-retry-once for `status`); a retry that also breaks mid-request resets the replacement connection, so the next request re-establishes cleanly instead of reusing a poisoned transport; child liveness is probed before the cached connection is trusted, so a child that dies between requests reports `running=false` and is respawned on the next request instead of misreporting `MaybeApplied`; `ok=false` serve rejections fail fast with the typed `RequestError` without killing the child; and the global cache is keyed on an order-canonical config fingerprint (map-field insertion order cannot invalidate it, a changed config rebuilds and bypasses the start-failure backoff). The transport is unix-only; non-unix targets compile a stub whose entry points report a typed unsupported-platform error (self-tested on those targets). The RI suite boots the real JSON-RPC router and asserts `medulla_local.status` returns a well-formed idle snapshot (running=false, actionable message) and `instruct` fails cleanly when no serve entry is configured — hermetic, no Node child or network. |+------ | --------------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |---diff --git a/gitbooks/developing/architecture.md b/gitbooks/developing/architecture.mdindex f82b89671c..1094cc40dd 100644--- a/gitbooks/developing/architecture.md+++ b/gitbooks/developing/architecture.md@@ -17,7 +17,7 @@ OpenHuman is a cross-platform communication and automation platform purpose-buil| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || **`app/`** | pnpm workspace **`openhuman-app`**: Vite/React UI (`app/src/`), Vitest and WDIO tests. The Tauri shell itself is the Rust crate `crates/openhuman-app/` (below). || **`crates/openhuman-app/`** | Thin Tauri v2 desktop host (Cargo package `openhuman-app`). Built from its own manifest and lockfile, excluded from the root workspace; hosts the core as an in-process tokio task (`src/core_process.rs`). |-| **`crates/openhuman-core/`** | Cargo package **`openhuman`**: library **`openhuman_core`**, with no `tinyhumans-sdk` dependency — the hosted backend is reached only through the `api::transport::BackendTransport` port. Flat domain modules directly under `src/` (`agent`, `api`, `channels`, `config`, `cron`, `desktop`, `flows`, `hooks`, `hosting`, `http_host`, `inference`, `integrations`, `json_schema`, `mcp`, `media`, `medulla`, `memory`, `modules`, `platform`, `runtime`, `sandbox`, `search`, `security`, `skills`, `threads`, `tools`, `util`, `voice`, `web3`, `web_chat`, …). `src/core/` holds the JSON-RPC server (`jsonrpc.rs`), CLI (`cli.rs`), dispatch, controller registry (`all.rs`), event bus (`bus.rs`), `runtime/` (`CoreBuilder`/`CoreRuntime`) and `subsystem/`. There is no `src/rpc/` or `src/embed/` inside this crate any more. |+| **`crates/openhuman-core/`** | Cargo package **`openhuman`**: library **`openhuman_core`**, with no `tinyhumans-sdk` dependency — the hosted backend is reached only through the `api::transport::BackendTransport` port. Flat domain modules directly under `src/` (`agent`, `api`, `channels`, `config`, `cron`, `desktop`, `flows`, `hooks`, `hosting`, `http_host`, `inference`, `integrations`, `json_schema`, `mcp`, `media`, `memory`, `modules`, `platform`, `runtime`, `sandbox`, `search`, `security`, `skills`, `threads`, `tools`, `util`, `voice`, `web3`, `web_chat`, …). `src/core/` holds the JSON-RPC server (`jsonrpc.rs`), CLI (`cli.rs`), dispatch, controller registry (`all.rs`), event bus (`bus.rs`), `runtime/` (`CoreBuilder`/`CoreRuntime`) and `subsystem/`. There is no `src/rpc/` or `src/embed/` inside this crate any more. || **`crates/openhuman-rpc/`** | Shared JSON-RPC contracts: `RpcOutcome`, `unwrap_rpc`, `apply_log_envelope`, `StructuredRpcError`. The `http-client` feature (default on; off for root-workspace consumers) adds `post_json_rpc`, `bearer_header`, `redact_url_for_log`, `HttpRpcResponse`. Used by the Tauri shell (`core_rpc.rs` → `relay_http_rpc`) and the TUI (envelope decoding); re-exported by the core as `openhuman_core::rpc`. || **`crates/openhuman-embed/`** | Typed library facade (`openhuman_embed::{Harness, Core, CoreBuilder, DomainSet, ServiceSet, HostKind}`) for embedding the core in another product; forwards the core's feature gates. Installs no backend transport itself. || **`crates/openhuman-tinyhumans/`** | The TinyHumans layer above embed: `SdkBackendTransport` (the only crate that depends on the vendored `tinyhumans-sdk`), `install()` for hosts that boot the core themselves, a `RuntimeBuilder` that boots an embed runtime connected, the hosted RPC proxies (`hosted/`: billing, team, referral, announcements — registered into the core's controller registry as an extension), and the host-side login/session owner (`session/`). |diff --git a/scripts/check-domain-e2e-coverage.mjs b/scripts/check-domain-e2e-coverage.mjsindex c194040fd3..5f701b61b9 100644--- a/scripts/check-domain-e2e-coverage.mjs+++ b/scripts/check-domain-e2e-coverage.mjs@@ -114,10 +114,8 @@ const UNREACHABLE_NAMESPACES = {//// It runs every suite with `--features "$(scripts/ci/product-features.sh)"` and// does NOT pass `--no-default-features`, so the measured configuration is-// `default` UNION the product set — not the product set alone. The distinction-// decides real cases: `medulla` is absent from product-features.txt but present-// in `[features] default`, so its nine controllers ARE dispatchable in an e2e-// build and are genuine obligations, not exclusions.+// `default` UNION the product set, not the product set alone. Default-on+// controllers remain dispatchable and require E2E coverage.const CORE_MANIFEST = path.join(ROOT, 'crates/openhuman-core/Cargo.toml');const PRODUCT_FEATURES_FILE = path.join(ROOT, 'scripts', 'ci', 'product-features.txt');diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex bed6a007b3..cbb72cf528 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -909,20 +909,6 @@"text": "if let Err(e) = with_origin(origin, apply_decision(run, &envelope)).await {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/platform/socket/medulla/mod.rs",- "line": 48,- "text": "use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/platform/socket/medulla/mod.rs",- "line": 249,- "text": "let turn = Box::pin(with_origin(origin, agent.run_single(&next_input)));",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/security/approval/gate_intercept.rs",diff --git a/scripts/ci/coverage-presence-allowlist.txt b/scripts/ci/coverage-presence-allowlist.txtindex 15f2162aef..acb3a8c584 100644--- a/scripts/ci/coverage-presence-allowlist.txt+++ b/scripts/ci/coverage-presence-allowlist.txt@@ -36,10 +36,3 @@ crates/openhuman-core/src/desktop/accessibility/helper/swift_focus.rscrates/openhuman-core/src/desktop/accessibility/helper/swift_paste.rscrates/openhuman-core/src/desktop/accessibility/helper/swift_ax_actions.rscrates/openhuman-core/src/desktop/accessibility/helper/swift_overlay.rs--# Medulla is deliberately not forwarded by the desktop product: it is a-# library/TUI-facing integration whose network client must not be compiled into-# the shipped Tauri app. `openhuman-embed` keeps the matching typed facade-# behind its `medulla` feature, so this Linux product-coverage lane cannot-# produce records for it.-crates/openhuman-embed/src/medulla.rsdiff --git a/scripts/generate-test-inventory.mjs b/scripts/generate-test-inventory.mjsindex 2b5c58c131..bf07323228 100644--- a/scripts/generate-test-inventory.mjs+++ b/scripts/generate-test-inventory.mjs@@ -85,9 +85,6 @@ const DOMAIN_ALLOWLIST = new Set(['mcp_audit','memory_diff','memory_goals',- // `medulla_local_e2e` covered the retired local namespace. The remaining- // cloud-backed Medulla controllers still need a dedicated RPC round-trip.- 'medulla','people','plan_review','provider_surfaces',diff --git a/scripts/i18n-find-english.ts b/scripts/i18n-find-english.tsindex 47fa84b8cf..2b099af563 100644--- a/scripts/i18n-find-english.ts+++ b/scripts/i18n-find-english.ts@@ -68,7 +68,6 @@ const INTENTIONAL_ENGLISH = new Set(["rewards.community.discordDetails", // "Discord" — brand/product name, same in every locale"rewards.community.rewardTokens", // "+{tokens} tokens" — "tokens" is the technical unit, kept in every locale (the recurring "/mo" variant IS translated)"nav.agentWorld",- "orchPage.medulla.title", // "Medulla" — brand/product name, same in every locale"memorySources.searchQueryPlaceholder","migration.vendor.hermes","namespaceOverview.entitiesShort",diff --git a/scripts/lib/feature-forwarding.mjs b/scripts/lib/feature-forwarding.mjsindex dc4e43f3d1..57fd1abecd 100644--- a/scripts/lib/feature-forwarding.mjs+++ b/scripts/lib/feature-forwarding.mjs@@ -50,7 +50,6 @@*/export const INTENTIONALLY_NOT_FORWARDED = {// 'some-gate': 'Reason it must not ship in the desktop build.',- medulla: 'Medulla orchestration-backend client; the desktop app is OpenHuman\'s own product and never dials a Medulla backend. Consumed by the Medulla TUI, which embeds this crate directly.',};/**diff --git a/tests/raw_coverage/medulla_session_e2e.rs b/tests/raw_coverage/medulla_session_e2e.rsdeleted file mode 100644index e7382402b1..0000000000--- a/tests/raw_coverage/medulla_session_e2e.rs+++ /dev/null@@ -1,1132 +0,0 @@-#![cfg(any())] // TODO(#6382): migrate this legacy TinyAgents fixture to the hosted public API.--//! JSON-RPC E2E coverage for the `openhuman.medulla_*` namespace — all nine-//! controllers, which had none.-//!-//! Run:-//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" medulla_session_e2e`-//!-//! ## What is being tested, and against what-//!-//! `openhuman::medulla` is OpenHuman acting as a **client** of the Medulla-//! orchestration backend — outbound HTTP to `/medulla/v1/*`, unwrapping a-//! `{success, data}` envelope (`client/mod.rs:118-159`). Do not confuse it with-//! `platform::socket::medulla`, which is the inbound worker side; they share a-//! product name and nothing else (`medulla/mod.rs:13-21`).-//!-//! Every case here runs against a loopback axum server speaking that envelope,-//! selected with `OPENHUMAN_MEDULLA_BASE_URL` — the documented override for-//! pointing a host at a different deployment (`resolve.rs:12-19`). Nothing-//! leaves the machine.-//!-//! ## Two preconditions, and both are worth asserting in their own right-//!-//! `resolve::client` needs a base URL **and** a session token, and reports the-//! two failures with distinct `data.kind` discriminators so a host can render-//! "sign in" separately from "misconfigured" (`ops.rs:189-201`). This suite-//! plants a session token through `AuthService` — the same store-//! `get_session_token` reads — and also covers the signed-out path, because a-//! signed-out host is the state most installs are in when they first touch this-//! surface.-//!-//! ## Feature note-//!-//! The `medulla` gate is default-ON but deliberately **not** forwarded to the-//! desktop shell (allow-listed in `INTENTIONALLY_NOT_FORWARDED` — the app never-//! dials a Medulla backend; the Medulla TUI embeds this crate instead). The-//! product feature string does not turn defaults off, so these controllers are-//! present in this binary.--use std::net::SocketAddr;-use std::path::Path;-use std::sync::{Arc, Mutex, OnceLock};-use std::time::Duration;--use axum::extract::{Path as AxumPath, Query, State};-use axum::http::header::AUTHORIZATION;-use axum::http::HeaderMap;-use axum::routing::{get, post};-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};-use openhuman_core::core::jsonrpc::build_core_http_router;--/// The bearer this suite *proposes*. It is only used if this suite happens to-/// be the first in the aggregated binary to initialise the token subsystem —-/// see `rpc_token()` below, which is what actually gets sent.-const PROPOSED_RPC_TOKEN: &str = "medulla-session-e2e-token";-/// The session token this suite plants and the fixture backend demands.-const SESSION_JWT: &str = "planted-medulla-session-jwt";--static AUTH_INIT: OnceLock<()> = OnceLock::new();--/// The crate-wide env lock, not a private one.-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())-}--// ── Env plumbing ────────────────────────────────────────────────────────────--struct EnvVarGuard {- key: &'static str,- old: Option<String>,-}--impl EnvVarGuard {- fn set_to_path(key: &'static str, path: &Path) -> Self {- let old = std::env::var(key).ok();- std::env::set_var(key, path.as_os_str());- Self { key, old }- }-- fn set(key: &'static str, value: &str) -> Self {- let old = std::env::var(key).ok();- std::env::set_var(key, value);- Self { key, old }- }-- fn unset(key: &'static str) -> Self {- let old = std::env::var(key).ok();- std::env::remove_var(key);- Self { key, old }- }-}--impl Drop for EnvVarGuard {- fn drop(&mut self) {- match &self.old {- Some(value) => std::env::set_var(self.key, value),- None => std::env::remove_var(self.key),- }- }-}--/// The bearer the running process will actually validate.-///-/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`-/// returns early once it is set. Every `tests/raw_coverage/` suite now shares-/// one process, so the FIRST suite to initialise pins the token for all of-/// them; a suite that sent its own hard-coded literal would get 401 whenever it-/// lost that race, in an order that depends on libtest scheduling and load.-///-/// So: propose a token, initialise, then ask what the process settled on and-/// send that. Correct whether this suite wins the race or loses it.-fn rpc_token() -> &'static str {- AUTH_INIT.get_or_init(|| {- if std::env::var(CORE_TOKEN_ENV_VAR)- .map(|v| v.trim().is_empty())- .unwrap_or(true)- {- std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);- }- let token_dir = std::env::temp_dir().join("openhuman-medulla-session-e2e-auth");- std::fs::create_dir_all(&token_dir).expect("token dir");- init_rpc_token(&token_dir).expect("init rpc auth token");- });- openhuman_core::core::auth::get_rpc_token()- .expect("the token subsystem is initialised by the line above")-}--// ── The fixture Medulla backend ─────────────────────────────────────────────--/// Records what the backend was asked, so the suite can assert the client sent-/// the right thing rather than only that it parsed the reply.-#[derive(Default)]-struct BackendState {- /// `(method, path, query)` for every request that arrived.- seen: Mutex<Vec<(String, String, String)>>,- /// Bodies of the message posts.- bodies: Mutex<Vec<Value>>,-}--impl BackendState {- fn record(&self, method: &str, path: &str, query: &str) {- self.seen.lock().unwrap_or_else(|p| p.into_inner()).push((- method.to_string(),- path.to_string(),- query.to_string(),- ));- }-- fn queries_for(&self, path: &str) -> Vec<String> {- self.seen- .lock()- .unwrap_or_else(|p| p.into_inner())- .iter()- .filter(|(_, p, _)| p == path)- .map(|(_, _, q)| q.clone())- .collect()- }-}--fn envelope(data: Value) -> Json<Value> {- Json(json!({ "success": true, "data": data }))-}--/// Reject anything not carrying the planted bearer token.-///-/// Every session method must attach it (`client/mod.rs:108-115`); a method that-/// forgot would sail past a fixture that did not check.-fn authed(headers: &HeaderMap) -> bool {- headers- .get(AUTHORIZATION)- .and_then(|v| v.to_str().ok())- .is_some_and(|v| v == format!("Bearer {SESSION_JWT}"))-}--async fn serve_fixture_backend() -> (- SocketAddr,- Arc<BackendState>,- tokio::task::JoinHandle<Result<(), std::io::Error>>,-) {- let state = Arc::new(BackendState::default());-- async fn list_sessions(- State(state): State<Arc<BackendState>>,- headers: HeaderMap,- ) -> Json<Value> {- state.record("GET", "/medulla/v1/sessions", "");- if !authed(&headers) {- return Json(- json!({ "success": false, "error": "unauthorized", "errorCode": "Unauthorized" }),- );- }- envelope(json!([- {- "sessionId": "sess-alpha",- "title": "Planted alpha",- "lastActiveAt": 1_700_000_000_000_i64,- "status": "active",- "lastSeq": 7- },- {- "sessionId": "sess-beta",- "title": null,- "status": "idle",- "lastSeq": 0- }- ]))- }-- async fn create_session(- State(state): State<Arc<BackendState>>,- headers: HeaderMap,- Json(body): Json<Value>,- ) -> Json<Value> {- state.record("POST", "/medulla/v1/sessions", "");- state- .bodies- .lock()- .unwrap_or_else(|p| p.into_inner())- .push(body.clone());- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- // Echo the title back through the id so the test can prove the body- // travelled rather than being dropped on the floor.- let suffix = body- .get("title")- .and_then(Value::as_str)- .unwrap_or("untitled");- envelope(json!({ "sessionId": format!("sess-new-{suffix}") }))- }-- async fn get_session(- State(state): State<Arc<BackendState>>,- AxumPath(id): AxumPath<String>,- headers: HeaderMap,- ) -> Json<Value> {- state.record("GET", "/medulla/v1/sessions/:id", &id);- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- if id == "sess-missing" {- // A backend refusal carrying its own vocabulary — `errorCode` is- // what the host branches on.- return Json(json!({- "success": false,- "error": "no such session",- "errorCode": "SessionNotFound"- }));- }- envelope(json!({- "sessionId": id,- "status": "active",- "lastCycleId": "cycle-9",- "lastSeq": 12,- "eventSeq": 30- }))- }-- async fn send_message(- State(state): State<Arc<BackendState>>,- AxumPath(_id): AxumPath<String>,- Query(query): Query<std::collections::HashMap<String, String>>,- headers: HeaderMap,- Json(body): Json<Value>,- ) -> Json<Value> {- let sync = query.get("sync").cloned().unwrap_or_default();- state.record("POST", "/medulla/v1/sessions/:id/messages", &sync);- state- .bodies- .lock()- .unwrap_or_else(|p| p.into_inner())- .push(body.clone());- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- // The two documented shapes: 202 async carries {cycleId, seq}; the- // sync form adds `reply`.- if sync == "1" {- envelope(json!({ "cycleId": "cycle-sync", "seq": 42, "reply": "PLANTED_SYNC_REPLY" }))- } else {- envelope(json!({ "cycleId": "cycle-async", "seq": 41 }))- }- }-- async fn list_messages(- State(state): State<Arc<BackendState>>,- AxumPath(id): AxumPath<String>,- Query(query): Query<std::collections::HashMap<String, String>>,- headers: HeaderMap,- ) -> Json<Value> {- let after = query.get("after").cloned().unwrap_or_default();- state.record("GET", "/medulla/v1/sessions/:id/messages", &after);- let _ = id;- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- // Honour the cursor, so "replays only what is new" is a property the- // test can actually observe rather than assume.- let all = vec![- json!({ "seq": 1, "role": "user", "body": "first", "ts": 1_700_000_000_000_i64, "cycleId": "cycle-1" }),- json!({ "seq": 2, "role": "assistant", "body": "second", "cycleId": "cycle-1" }),- json!({ "seq": 3, "role": "user", "body": "third" }),- ];- let cursor: i64 = after.parse().unwrap_or(0);- envelope(Value::Array(- all.into_iter()- .filter(|m| m["seq"].as_i64().unwrap_or(0) > cursor)- .collect(),- ))- }-- async fn list_events(- State(state): State<Arc<BackendState>>,- AxumPath(id): AxumPath<String>,- Query(query): Query<std::collections::HashMap<String, String>>,- headers: HeaderMap,- ) -> Json<Value> {- let after = query.get("after").cloned().unwrap_or_default();- state.record("GET", "/medulla/v1/sessions/:id/events", &after);- let _ = id;- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- // NOTE the shape. There are TWO `EventEnvelope` types in this domain and- // they are not the same on the wire:- //- // * `medulla::events::EventEnvelope` — `{seq, at, event: SessionEvent}`,- // the contract type, publicly re-exported by `medulla/mod.rs`.- // * `medulla::client::types::event::EventEnvelope` — `{seq?, at,- // sessionId, cycleId?, event: Value}`, the wire type.- //- // `ops::list_events` returns the **client** one, so `sessionId` is- // required and `event` stays raw JSON. Reading the domain's public- // re-export and assuming it describes the RPC response is the trap; it- // cost this suite one red run. See- // `~/tinyhuman/bugs/e2e-wave-medulla-two-eventenvelope-types.md`.- let all = vec![- json!({ "seq": 1, "at": 1_700_000_000_000_u64, "sessionId": "sess-alpha", "cycleId": "cycle-1",- "event": { "kind": "cycle_start", "cycleId": "cycle-1" } }),- json!({ "seq": 2, "at": 1_700_000_000_100_u64, "sessionId": "sess-alpha",- "event": { "kind": "assistant_delta", "delta": "hi" } }),- // A kind this build does not model: it must survive rather than- // dropping the row.- json!({ "seq": 3, "at": 1_700_000_000_200_u64, "sessionId": "sess-alpha",- "event": { "kind": "some_future_kind", "whatever": 1 } }),- ];- let cursor: i64 = after.parse().unwrap_or(0);- envelope(Value::Array(- all.into_iter()- .filter(|e| e["seq"].as_i64().unwrap_or(0) > cursor)- .collect(),- ))- }-- async fn abort(- State(state): State<Arc<BackendState>>,- AxumPath(id): AxumPath<String>,- headers: HeaderMap,- ) -> Json<Value> {- state.record("POST", "/medulla/v1/sessions/:id/abort", &id);- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- envelope(json!({ "sessionId": id, "aborted": true }))- }-- async fn roster(State(state): State<Arc<BackendState>>, headers: HeaderMap) -> Json<Value> {- state.record("GET", "/medulla/v1/roster", "");- if !authed(&headers) {- return Json(json!({ "success": false, "error": "unauthorized" }));- }- // Note the wrapper: `roster()` unwraps `{workers: [...]}` out of `data`.- // `selected` is the one non-defaulted bool on `RosterWorker`- // (`client/program/types.rs`) — every other optional field carries- // `#[serde(default)]`, so omitting it is the single way to make this- // decode fail. It did, on the first run of this suite.- envelope(json!({- "workers": [- {- "registryId": "worker-1",- "label": "Planted worker",- "description": "Does planted things.",- "availability": "idle",- "harness": "tinyagents",- "address": "127.0.0.1:0",- "selected": true- }- ]- }))- }-- let app = Router::new()- .route(- "/medulla/v1/sessions",- get(list_sessions).post(create_session),- )- .route("/medulla/v1/sessions/{id}", get(get_session))- .route(- "/medulla/v1/sessions/{id}/messages",- get(list_messages).post(send_message),- )- .route("/medulla/v1/sessions/{id}/events", get(list_events))- .route("/medulla/v1/sessions/{id}/abort", post(abort))- .route("/medulla/v1/roster", get(roster))- .with_state(Arc::clone(&state));-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind fixture backend");- let addr = listener.local_addr().expect("fixture backend addr");- let join = tokio::spawn(async move { axum::serve(listener, app).await });- (addr, state, join)-}--// ── Harness ─────────────────────────────────────────────────────────────────--const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"-default_model = "medulla-e2e-model"--[secrets]-encrypt = false--[local_ai]-enabled = false--[memory]-provider = "none"-embedding_provider = "none"-embedding_model = "none"-embedding_dimensions = 0--[memory_tree]-embedding_strict = false-"#;--struct Harness {- _tmp: TempDir,- _guards: Vec<EnvVarGuard>,- rpc_base: String,- join: tokio::task::JoinHandle<Result<(), std::io::Error>>,-}--/// `plant_session` decides whether `resolve::client` will find a token, which-/// is the difference between the configured and signed-out cases below.-async fn setup(extra: Vec<EnvVarGuard>, plant_session: bool) -> Harness {- crate::tinyhumans_boot::boot();- let _ = rpc_token();-- let tmp = tempdir().expect("tempdir");- let home = tmp.path();- let openhuman_home = home.join(".openhuman");- std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");- std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");- let _: openhuman_core::config::Config =- toml::from_str(MIN_CONFIG).expect("test config must match the config schema");-- let workspace = home.join("workspace");- std::fs::create_dir_all(&workspace).expect("create workspace");-- let mut guards = vec![- EnvVarGuard::set_to_path("HOME", home),- EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),- ];- guards.extend(extra);-- if plant_session {- // Write into the same profile store `get_session_token` reads- // (`session_support.rs:243-248` → `AuthService::get_profile`), so the- // token resolves through production's own path rather than a test seam.- use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,- };- let config = openhuman_core::config::Config::load_or_init()- .await- .expect("load config for session planting");- AuthService::from_config(&config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- SESSION_JWT,- std::collections::HashMap::new(),- true,- )- .expect("plant an app-session token");- }-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind rpc listener");- let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");- let router = build_core_http_router(false);- let join = tokio::spawn(async move { axum::serve(listener, router).await });-- Harness {- _tmp: tmp,- _guards: guards,- rpc_base: format!("http://{addr}"),- join,- }-}--async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(60))- .build()- .expect("build client");- let url = format!("{}/rpc", base.trim_end_matches('/'));- let response = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))- .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))- .send()- .await- .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));- assert!(- response.status().is_success(),- "HTTP {} for {method}",- response.status()- );- response- .json::<Value>()- .await- .unwrap_or_else(|err| panic!("json for {method}: {err}"))-}--fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {- if let Some(error) = value.get("error") {- panic!("{context}: unexpected JSON-RPC error: {error}");- }- value- .get("result")- .unwrap_or_else(|| panic!("{context}: missing result: {value}"))-}--fn err<'a>(value: &'a Value, context: &str) -> &'a Value {- value- .get("error")- .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))-}--/// The `data.kind` discriminator hosts branch on.-///-/// `medulla`'s ops encode a `StructuredRpcError` into the controller error-/// channel, and the transport decodes it at the boundary into the JSON-RPC-/// `error.data` — deliberately without branching on the method name-/// (`core/jsonrpc.rs:86-99`). Reading `data.kind` rather than matching the-/// message is the whole point of that machinery: the message is prose and may-/// be reworded, the discriminator is the contract.-fn error_kind(value: &Value, context: &str) -> String {- let error = err(value, context);- error- .get("data")- .and_then(|d| d.get("kind"))- .and_then(Value::as_str)- .map(str::to_string)- .unwrap_or_else(|| {- panic!("{context}: the error carries no structured `data.kind`: {error}")- })-}--// ── status ──────────────────────────────────────────────────────────────────--/// `medulla_status` is deliberately infallible — "not configured" is a state to-/// render, not an error to raise — and it must never leak the token.-#[tokio::test]-async fn medulla_status_reports_readiness_without_dialling_anything() {- let _lock = env_lock();- // Point at a port nothing is listening on: `status` must still answer,- // because it reports resolvability and makes no network call.- let harness = setup(- vec![EnvVarGuard::set(- "OPENHUMAN_MEDULLA_BASE_URL",- "http://127.0.0.1:9/",- )],- true,- )- .await;-- let status = rpc(- &harness.rpc_base,- 300,- "openhuman.medulla_status",- json!({}),- )- .await;- let status = ok(&status, "medulla_status configured");- assert_eq!(- status.get("configured").and_then(Value::as_bool),- Some(true),- "a base URL plus a planted session token is the configured state: {status}"- );- assert_eq!(- status.get("hasSessionToken").and_then(Value::as_bool),- Some(true),- "the planted token must be seen: {status}"- );- assert_eq!(- status.get("baseUrl").and_then(Value::as_str),- Some("http://127.0.0.1:9"),- "the resolved base URL is surfaced, with its trailing slash trimmed: {status}"- );- assert!(- status.get("reason").is_none_or(Value::is_null),- "a configured host must carry no reason discriminator: {status}"- );- assert!(- !status.to_string().contains(SESSION_JWT),- "the session token must NEVER be returned: {status}"- );-- harness.join.abort();-}--/// The signed-out host: `status` says so with a stable discriminator, and every-/// other method in the namespace refuses with the matching structured error.-///-/// This is the state a fresh install is in, and the `expected_user_state` flag-/// on these errors is what keeps them out of crash reporting — so it matters-/// that the discriminator is right and not merely that something failed.-#[tokio::test]-async fn medulla_signed_out_host_refuses_every_call_with_one_discriminator() {- let _lock = env_lock();- let (backend_addr, _state, backend_join) = serve_fixture_backend().await;- let harness = setup(- vec![EnvVarGuard::set(- "OPENHUMAN_MEDULLA_BASE_URL",- &format!("http://{backend_addr}"),- )],- // No session planted: signed out.- false,- )- .await;-- let status = rpc(- &harness.rpc_base,- 310,- "openhuman.medulla_status",- json!({}),- )- .await;- let status = ok(&status, "medulla_status signed out");- assert_eq!(- status.get("configured").and_then(Value::as_bool),- Some(false),- "a host with no session token is not configured: {status}"- );- assert_eq!(- status.get("hasSessionToken").and_then(Value::as_bool),- Some(false),- "and it must say the token specifically is what is missing: {status}"- );- assert_eq!(- status.get("reason").and_then(Value::as_str),- Some("MedullaNoSessionToken"),- "the reason must be the stable discriminator, not prose: {status}"- );- // The base URL still resolves — that is the point of reporting them- // separately, so a UI can say "sign in" rather than "misconfigured".- assert!(- status- .get("baseUrl")- .and_then(Value::as_str)- .is_some_and(|u| u.contains(&backend_addr.to_string())),- "a signed-out host still reports the base URL it would use: {status}"- );-- // Every network-backed method refuses identically.- for (id, method, params) in [- (311, "openhuman.medulla_list_sessions", json!({})),- (312, "openhuman.medulla_create_session", json!({})),- (- 313,- "openhuman.medulla_get_session",- json!({ "sessionId": "sess-alpha" }),- ),- (- 314,- "openhuman.medulla_send_message",- json!({ "sessionId": "sess-alpha", "body": "hi" }),- ),- (- 315,- "openhuman.medulla_abort",- json!({ "sessionId": "sess-alpha" }),- ),- (- 316,- "openhuman.medulla_list_messages",- json!({ "sessionId": "sess-alpha" }),- ),- (- 317,- "openhuman.medulla_list_events",- json!({ "sessionId": "sess-alpha" }),- ),- (318, "openhuman.medulla_roster", json!({})),- ] {- let refused = rpc(&harness.rpc_base, id, method, params).await;- assert_eq!(- error_kind(&refused, method),- "MedullaNoSessionToken",- "{method} must refuse a signed-out host with the same discriminator \- `status` reported: {refused}"- );- }-- backend_join.abort();- harness.join.abort();-}--// ── the session lifecycle ───────────────────────────────────────────────────--/// The full durable-session arc against the fixture backend:-/// create → list → get → send (async and sync) → abort.-#[tokio::test]-async fn medulla_session_lifecycle_round_trips_through_the_backend() {- let _lock = env_lock();- let (backend_addr, state, backend_join) = serve_fixture_backend().await;- let harness = setup(- vec![EnvVarGuard::set(- "OPENHUMAN_MEDULLA_BASE_URL",- &format!("http://{backend_addr}"),- )],- true,- )- .await;-- // ── create ──────────────────────────────────────────────────────────────- let created = rpc(- &harness.rpc_base,- 320,- "openhuman.medulla_create_session",- json!({ "title": "planted" }),- )- .await;- assert_eq!(- ok(&created, "medulla_create_session")- .get("sessionId")- .and_then(Value::as_str),- Some("sess-new-planted"),- "the title must reach the backend, not be dropped: {created}"- );-- // Omitting the title is legal — the backend names an untitled session- // itself rather than this host inventing one.- let untitled = rpc(- &harness.rpc_base,- 321,- "openhuman.medulla_create_session",- json!({}),- )- .await;- assert_eq!(- ok(&untitled, "medulla_create_session untitled")- .get("sessionId")- .and_then(Value::as_str),- Some("sess-new-untitled"),- "an absent title must send no title, not an empty one: {untitled}"- );-- // ── list ────────────────────────────────────────────────────────────────- let listed = rpc(- &harness.rpc_base,- 322,- "openhuman.medulla_list_sessions",- json!({}),- )- .await;- let listed = ok(&listed, "medulla_list_sessions");- let sessions = listed- .as_array()- .unwrap_or_else(|| panic!("list_sessions must return an array: {listed}"));- assert_eq!(sessions.len(), 2, "both fixture sessions: {listed}");- assert_eq!(- sessions[0].get("sessionId").and_then(Value::as_str),- Some("sess-alpha")- );- assert_eq!(- sessions[0].get("status").and_then(Value::as_str),- Some("active"),- "the wire status must round-trip through the modelled enum: {listed}"- );- assert_eq!(- sessions[0].get("lastSeq").and_then(Value::as_i64),- Some(7),- "the replay cursor must survive: {listed}"- );- // The second row omits `lastActiveAt` entirely; an absent optional must- // stay absent rather than becoming a fabricated zero.- assert!(- sessions[1].get("lastActiveAt").is_none_or(Value::is_null),- "an unreported lastActiveAt must not be invented: {listed}"- );-- // ── get ─────────────────────────────────────────────────────────────────- let detail = rpc(- &harness.rpc_base,- 323,- "openhuman.medulla_get_session",- json!({ "sessionId": "sess-alpha" }),- )- .await;- let detail = ok(&detail, "medulla_get_session");- assert_eq!(- detail.get("sessionId").and_then(Value::as_str),- Some("sess-alpha")- );- assert_eq!(- detail.get("lastCycleId").and_then(Value::as_str),- Some("cycle-9")- );- assert_eq!(detail.get("eventSeq").and_then(Value::as_i64), Some(30));-- // ── send, both modes ────────────────────────────────────────────────────- let async_send = rpc(- &harness.rpc_base,- 324,- "openhuman.medulla_send_message",- json!({ "sessionId": "sess-alpha", "body": "async turn" }),- )- .await;- let async_send = ok(&async_send, "medulla_send_message async");- assert_eq!(- async_send.get("cycleId").and_then(Value::as_str),- Some("cycle-async"),- "omitting `sync` must take the non-blocking path a UI wants: {async_send}"- );- assert!(- async_send.get("reply").is_none_or(Value::is_null),- "the async form carries no reply: {async_send}"- );-- let sync_send = rpc(- &harness.rpc_base,- 325,- "openhuman.medulla_send_message",- json!({ "sessionId": "sess-alpha", "body": "sync turn", "sync": true }),- )- .await;- let sync_send = ok(&sync_send, "medulla_send_message sync");- assert_eq!(- sync_send.get("cycleId").and_then(Value::as_str),- Some("cycle-sync")- );- assert_eq!(- sync_send.get("reply").and_then(Value::as_str),- Some("PLANTED_SYNC_REPLY"),- "the sync form must surface the backend's reply: {sync_send}"- );-- // The `sync` flag must reach the wire as the backend's `0`/`1`, not as a- // JSON boolean — that translation is the client's job.- let sync_flags = state.queries_for("/medulla/v1/sessions/:id/messages");- assert_eq!(- sync_flags,- vec!["0".to_string(), "1".to_string()],- "the two sends must have carried sync=0 then sync=1: {sync_flags:?}"- );- let bodies = state- .bodies- .lock()- .unwrap_or_else(|p| p.into_inner())- .clone();- assert!(- bodies- .iter()- .any(|b| b.get("body").and_then(Value::as_str) == Some("async turn")),- "the message body must reach the backend: {bodies:?}"- );-- // ── abort ───────────────────────────────────────────────────────────────- let aborted = rpc(- &harness.rpc_base,- 326,- "openhuman.medulla_abort",- json!({ "sessionId": "sess-alpha" }),- )- .await;- let aborted = ok(&aborted, "medulla_abort");- assert_eq!(- aborted.get("aborted").and_then(Value::as_bool),- Some(true),- "abort must report whether it actually aborted: {aborted}"- );- assert_eq!(- aborted.get("sessionId").and_then(Value::as_str),- Some("sess-alpha")- );-- // ── a backend refusal keeps the backend's own vocabulary ────────────────- let missing = rpc(- &harness.rpc_base,- 327,- "openhuman.medulla_get_session",- json!({ "sessionId": "sess-missing" }),- )- .await;- assert_eq!(- error_kind(&missing, "medulla_get_session missing"),- "SessionNotFound",- "the backend's `errorCode` must become `data.kind`, so a host branches \- on its vocabulary rather than on prose: {missing}"- );-- // ── params validation ───────────────────────────────────────────────────- let no_id = rpc(- &harness.rpc_base,- 328,- "openhuman.medulla_get_session",- json!({}),- )- .await;- assert!(- err(&no_id, "medulla_get_session no id")- .to_string()- .contains("sessionId"),- "an absent sessionId must be named: {no_id}"- );-- let no_body = rpc(- &harness.rpc_base,- 329,- "openhuman.medulla_send_message",- json!({ "sessionId": "sess-alpha" }),- )- .await;- assert!(- err(&no_body, "medulla_send_message no body")- .to_string()- .contains("body"),- "an absent message body must be named: {no_body}"- );-- backend_join.abort();- harness.join.abort();-}--// ── replay + roster ─────────────────────────────────────────────────────────--/// `medulla_list_messages` / `medulla_list_events` are cursors, not page-/// offsets: passing the last seq already seen must return only what is newer.-/// That property is what makes a reconnect cheap, and it is asserted here by-/// replaying the same session twice with different cursors.-#[tokio::test]-async fn medulla_replay_is_a_cursor_and_tolerates_unmodelled_event_kinds() {- let _lock = env_lock();- let (backend_addr, state, backend_join) = serve_fixture_backend().await;- let harness = setup(- vec![EnvVarGuard::set(- "OPENHUMAN_MEDULLA_BASE_URL",- &format!("http://{backend_addr}"),- )],- true,- )- .await;-- // No cursor: everything.- let all = rpc(- &harness.rpc_base,- 330,- "openhuman.medulla_list_messages",- json!({ "sessionId": "sess-alpha" }),- )- .await;- let all = ok(&all, "medulla_list_messages all");- let messages = all- .as_array()- .unwrap_or_else(|| panic!("list_messages must return an array: {all}"));- assert_eq!(messages.len(), 3, "the whole history: {all}");- assert_eq!(- messages[0].get("role").and_then(Value::as_str),- Some("user"),- "roles must round-trip lowercase through the modelled enum: {all}"- );- assert_eq!(- messages[1].get("role").and_then(Value::as_str),- Some("assistant")- );- assert_eq!(- messages[0].get("body").and_then(Value::as_str),- Some("first")- );-- // With a cursor: only what is newer. This is the assertion that separates- // a cursor from an offset — an offset of 2 would return one row, a cursor- // of 2 returns exactly the rows with seq > 2.- let tail = rpc(- &harness.rpc_base,- 331,- "openhuman.medulla_list_messages",- json!({ "sessionId": "sess-alpha", "after": 2 }),- )- .await;- let tail = ok(&tail, "medulla_list_messages after");- let tail_messages = tail.as_array().expect("array");- assert_eq!(tail_messages.len(), 1, "only seq 3 is newer than 2: {tail}");- assert_eq!(- tail_messages[0].get("seq").and_then(Value::as_i64),- Some(3),- "the cursor must be exclusive of its own value: {tail}"- );-- // The cursor must actually have travelled to the backend as `after=2` —- // filtering client-side would look identical from here.- let message_cursors = state.queries_for("/medulla/v1/sessions/:id/messages");- assert_eq!(- message_cursors,- vec![String::new(), "2".to_string()],- "an absent cursor must send no `after` param at all, and a present one \- must send its value: {message_cursors:?}"- );-- // Events: same cursor semantics, plus forward compatibility.- let events = rpc(- &harness.rpc_base,- 332,- "openhuman.medulla_list_events",- json!({ "sessionId": "sess-alpha" }),- )- .await;- let events = ok(&events, "medulla_list_events");- let envelopes = events- .as_array()- .unwrap_or_else(|| panic!("list_events must return an array: {events}"));- assert_eq!(- envelopes.len(),- 3,- "an unmodelled event kind must NOT be dropped — a newer backend would \- silently lose rows: {events}"- );- assert_eq!(envelopes[0].get("seq").and_then(Value::as_u64), Some(1));- assert_eq!(- envelopes[0].get("at").and_then(Value::as_u64),- Some(1_700_000_000_000),- "the wall-clock stamp must survive: {events}"- );- assert_eq!(- envelopes[0].get("sessionId").and_then(Value::as_str),- Some("sess-alpha"),- "the wire envelope's required sessionId must round-trip: {events}"- );- assert_eq!(- envelopes[0]- .get("event")- .and_then(|e| e.get("kind"))- .and_then(Value::as_str),- Some("cycle_start"),- "a modelled kind keeps its tag: {events}"- );- assert_eq!(- envelopes[1]- .get("event")- .and_then(|e| e.get("delta"))- .and_then(Value::as_str),- Some("hi"),- "a modelled kind keeps its payload: {events}"- );- // The unmodelled row survives, tagged with whatever the backend called it.- assert_eq!(- envelopes[2]- .get("event")- .and_then(|e| e.get("kind"))- .and_then(Value::as_str),- Some("some_future_kind"),- "an unknown kind must keep its own tag rather than being relabelled: {events}"- );-- let events_tail = rpc(- &harness.rpc_base,- 333,- "openhuman.medulla_list_events",- json!({ "sessionId": "sess-alpha", "after": 1 }),- )- .await;- assert_eq!(- ok(&events_tail, "medulla_list_events after")- .as_array()- .map(Vec::len),- Some(2),- "the events cursor must drop what has already been seen: {events_tail}"- );-- // ── roster ──────────────────────────────────────────────────────────────- // The backend wraps the list in `{workers: [...]}`; the controller unwraps- // it, so a caller gets the array and not the wrapper.- let roster = rpc(- &harness.rpc_base,- 334,- "openhuman.medulla_roster",- json!({}),- )- .await;- let roster = ok(&roster, "medulla_roster");- let workers = roster- .as_array()- .unwrap_or_else(|| panic!("roster must unwrap to a bare array, got: {roster}"));- assert_eq!(workers.len(), 1, "one planted worker: {roster}");- assert_eq!(- workers[0].get("registryId").and_then(Value::as_str),- Some("worker-1"),- "the worker's stable id must survive: {roster}"- );- assert_eq!(- workers[0].get("availability").and_then(Value::as_str),- Some("idle")- );- assert_eq!(- workers[0].get("harness").and_then(Value::as_str),- Some("tinyagents")- );- assert_eq!(- workers[0].get("selected").and_then(Value::as_bool),- Some(true),- "the roster's required `selected` flag must round-trip: {roster}"- );-- backend_join.abort();- harness.join.abort();-}