Skip to content

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

refactor: remove medulla integration

Steven Enamakel4ddf8e91d99e
diff --git a/Cargo.lock b/Cargo.lock
index c45cd84a5a..08370aa65d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -134,7 +134,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -145,7 +145,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -371,7 +371,7 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
- "sha1 0.10.7",
+ "sha1",
"sync_wrapper",
"tokio",
"tokio-tungstenite 0.29.0",
@@ -1683,7 +1683,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.2",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -1916,7 +1916,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -3677,7 +3677,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -4908,7 +4908,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -5395,7 +5395,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -5826,17 +5826,6 @@ dependencies = [
"digest 0.10.7",
]
-[[package]]
-name = "sha1"
-version = "0.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
-dependencies = [
- "cfg-if",
- "cpufeatures 0.3.1",
- "digest 0.11.3",
-]
-
[[package]]
name = "sha2"
version = "0.10.9"
@@ -5979,7 +5968,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -6231,10 +6220,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom 0.4.3",
+ "getrandom 0.3.4",
"once_cell",
"rustix",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -6247,7 +6236,7 @@ dependencies = [
"parking_lot",
"rustix",
"signal-hook",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -6549,7 +6538,7 @@ dependencies = [
"serde",
"serde-big-array",
"serde_json",
- "sha1 0.10.7",
+ "sha1",
"sha2 0.10.9",
"thiserror 2.0.20",
"tinychannels-bus",
@@ -6591,7 +6580,7 @@ dependencies = [
[[package]]
name = "tinyconnectors-bus"
-version = "0.10.0"
+version = "0.9.0"
dependencies = [
"serde",
"serde_json",
@@ -6607,7 +6596,7 @@ dependencies = [
[[package]]
name = "tinyflows"
-version = "0.8.3"
+version = "0.8.2"
dependencies = [
"async-trait",
"futures-timer",
@@ -6661,16 +6650,16 @@ dependencies = [
[[package]]
name = "tinyhosts"
-version = "0.1.7"
+version = "0.1.5"
dependencies = [
"async-trait",
- "base64 0.23.1",
+ "base64 0.22.1",
"hex",
"percent-encoding",
"reqwest",
"serde",
"serde_json",
- "sha1 0.11.0",
+ "sha1",
"thiserror 2.0.20",
]
@@ -7244,7 +7233,7 @@ dependencies = [
"httparse",
"log",
"rand 0.8.8",
- "sha1 0.10.7",
+ "sha1",
"thiserror 1.0.69",
"utf-8",
]
@@ -7264,7 +7253,7 @@ dependencies = [
"rand 0.9.5",
"rustls",
"rustls-pki-types",
- "sha1 0.10.7",
+ "sha1",
"thiserror 2.0.20",
]
@@ -7544,7 +7533,7 @@ dependencies = [
"serde",
"serde-big-array",
"serde_json",
- "sha1 0.10.7",
+ "sha1",
"sha2 0.10.9",
"thiserror 2.0.20",
"typed-builder",
@@ -7626,7 +7615,7 @@ dependencies = [
"prost",
"rand 0.10.2",
"serde",
- "sha1 0.10.7",
+ "sha1",
"sha2 0.10.9",
"subtle",
"thiserror 2.0.20",
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 9207cfed88..f1b99601b4 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -1012,7 +1012,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
@@ -1374,7 +1374,6 @@ crash-reporting = ["dep:sentry"]
# 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/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs
index 55620d5013..31dc1e4aea 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.rs
index 6b74283c74..1fc0062c4b 100644
--- a/crates/openhuman-core/src/config/schema/subconscious.rs
+++ b/crates/openhuman-core/src/config/schema/subconscious.rs
@@ -1,165 +1,26 @@
//! 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.
+//! The local tinyagents graph drives the heartbeat tick.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-/// Which engine runs the subconscious reflect/commit cognition.
+/// Which engine runs the subconscious cognition.
#[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.
#[default]
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.
+/// The subconscious config block.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct SubconsciousConfig {
- /// Which engine drives the subconscious tick. Default `local`.
+ /// Which engine drives the subconscious tick.
#[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.rs
deleted file mode 100644
index c72eb2338f..0000000000
--- a/crates/openhuman-core/src/config/schema/subconscious_tests.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-use super::*;
-
-#[test]
-fn default_engine_is_local() {
- assert_eq!(
- 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();
- 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)
- );
-}
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rs
index 72a296518e..5e41089273 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
@@ -146,7 +137,7 @@ pub enum DomainGroup {
impl DomainGroup {
/// Number of variants. Kept in sync by `domain_group_all_lists_every_variant`.
- pub const COUNT: usize = 21;
+ pub const COUNT: usize = 20;
/// Every variant, for exhaustive iteration in drift guards.
///
@@ -170,7 +161,6 @@ impl DomainGroup {
DomainGroup::Web3,
DomainGroup::Voice,
DomainGroup::Media,
- DomainGroup::Medulla,
DomainGroup::Inference,
DomainGroup::Integrations,
DomainGroup::Automation,
@@ -198,15 +188,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,
}
}
}
@@ -662,17 +651,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 resources
push(
&mut controllers,
@@ -1107,7 +1085,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.rs
index cbc8fdb4a5..36c5f3f92c 100644
--- a/crates/openhuman-core/src/core/all_tests.rs
+++ b/crates/openhuman-core/src/core/all_tests.rs
@@ -1214,36 +1214,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
@@ -1463,7 +1433,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,
@@ -1521,7 +1490,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/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rs
index ed14450f75..2049d5701e 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,
@@ -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,
diff --git a/crates/openhuman-core/src/core/runtime/builder_tests.rs b/crates/openhuman-core/src/core/runtime/builder_tests.rs
index 8af49c17b9..d66d28a714 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,7 +101,6 @@ 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.
assert!(DomainSet::embedded().allows(DomainGroup::Flows));
@@ -120,7 +115,7 @@ fn embedded_keeps_channels_on_for_web_chat() {
}
#[test]
-fn embedded_is_not_harness_plus_medulla() {
+fn embedded_is_not_harness() {
// 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.rs
index 082bbcdb62..da6a573270 100644
--- a/crates/openhuman-core/src/core/runtime/services.rs
+++ b/crates/openhuman-core/src/core/runtime/services.rs
@@ -529,10 +529,6 @@ pub fn spawn_socket_auto_connect(
// `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"
);
@@ -542,10 +538,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/medulla_bridge.rs b/crates/openhuman-core/src/flows/medulla_bridge.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
index ef0dd635ff..219d39fe77 100644
--- a/crates/openhuman-core/src/flows/mod.rs
+++ b/crates/openhuman-core/src/flows/mod.rs
@@ -37,7 +37,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.rs
index 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/lib.rs b/crates/openhuman-core/src/lib.rs
index e3b68683b8..10f80ed420 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -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.md
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/client/account.rs b/crates/openhuman-core/src/medulla/client/account.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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(&params);
- 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/mod.rs b/crates/openhuman-core/src/medulla/client/mod.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/types.rs b/crates/openhuman-core/src/medulla/client/program/types.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/sessions.rs b/crates/openhuman-core/src/medulla/client/sessions.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/tests/decode_tests.rs b/crates/openhuman-core/src/medulla/client/tests/decode_tests.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/mod.rs b/crates/openhuman-core/src/medulla/client/types/mod.rs
deleted file mode 100644
index 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/run.rs b/crates/openhuman-core/src/medulla/client/types/run.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/tests/mod.rs b/crates/openhuman-core/src/medulla/events/tests/mod.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/mod.rs b/crates/openhuman-core/src/medulla/mod.rs
deleted file mode 100644
index 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/ops.rs b/crates/openhuman-core/src/medulla/ops.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/event_handlers.rs b/crates/openhuman-core/src/platform/socket/event_handlers.rs
index 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.rs
index 479c22a90e..53b0dbbd6b 100644
--- a/crates/openhuman-core/src/platform/socket/manager.rs
+++ b/crates/openhuman-core/src/platform/socket/manager.rs
@@ -437,7 +437,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/medulla/README.md b/crates/openhuman-core/src/platform/socket/medulla/README.md
deleted file mode 100644
index 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.rs
deleted file mode 100644
index b56457057e..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, task-board 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.rs
deleted file mode 100644
index 6371340f66..0000000000
--- a/crates/openhuman-core/src/platform/socket/medulla/envelope_tests.rs
+++ /dev/null
@@ -1,144 +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,
- };
- 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.rs
deleted file mode 100644
index 09fc288c60..0000000000
--- a/crates/openhuman-core/src/platform/socket/medulla/mod.rs
+++ /dev/null
@@ -1,683 +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::Agent;
-
-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<Agent, 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 = Agent::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
-/// [`Agent::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::harness::turn_subagent_usage::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.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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/workflows.rs b/crates/openhuman-core/src/platform/socket/medulla/workflows.rs
deleted file mode 100644
index 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/mod.rs b/crates/openhuman-core/src/platform/socket/mod.rs
index 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.rs
index eb1aa890e7..d1bcd3f503 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())
}
@@ -25,7 +23,6 @@ pub async fn connect_static(
manager,
url,
token,
- super::medulla::workflows::clear_workflow_bridge,
)
.await
}
@@ -59,18 +56,15 @@ async fn connect_with_session_using(
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 +79,7 @@ pub async fn connect_with_session(manager: &SocketManager) -> Result<SocketState
let 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/ws_loop/dispatch.rs b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs
index 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 DISCONNECT
log::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.rs
index 4183675b44..cd1f5b5296 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/session_query.rs b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
index 9ce21b2aa7..3a3e95fbd5 100644
--- a/crates/openhuman-core/src/security/credentials/ops/session_query.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
@@ -41,7 +41,6 @@ pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Val
tracing::warn!(%error, "failed to disconnect backend socket on logout");
}
}
- crate::platform::socket::medulla::workflows::clear_workflow_bridge();
// Clear the active user marker so subsequent config loads fall back to the
// default (unauthenticated) openhuman directory.
diff --git a/crates/openhuman-core/src/tools/ops_tests.rs b/crates/openhuman-core/src/tools/ops_tests.rs
index 2a37c9da5c..b1dbba2665 100644
--- a/crates/openhuman-core/src/tools/ops_tests.rs
+++ b/crates/openhuman-core/src/tools/ops_tests.rs
@@ -381,7 +381,6 @@ const TOOL_LESS: &[crate::core::all::DomainGroup] = {
&[
G::Config,
G::Security,
- G::Medulla,
G::Modules,
G::Channels,
G::Hosted,
diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml
index c106cab8a0..5f6ac6466b 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/src/harness/mod.rs b/crates/openhuman-embed/src/harness/mod.rs
index 6ab0099479..02513db7d5 100644
--- a/crates/openhuman-embed/src/harness/mod.rs
+++ b/crates/openhuman-embed/src/harness/mod.rs
@@ -143,10 +143,6 @@ impl HarnessCore<'_> {
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.rs
index 3cd6b01210..9f5635372b 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -73,8 +73,6 @@ mod call;
mod config;
mod error;
mod harness;
-#[cfg(feature = "medulla")]
-mod medulla;
pub use agent::{absolute, Agent, Route, Turn, TurnOutcome, TurnRequest};
pub use auth::{Auth, AuthState, Session};
@@ -85,11 +83,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,
-};
use std::sync::Arc;
@@ -140,15 +133,6 @@ impl Core {
Agent(&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 a
diff --git a/crates/openhuman-embed/src/medulla.rs b/crates/openhuman-embed/src/medulla.rs
deleted file mode 100644
index 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.rs
deleted file mode 100644
index 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:?}"
- );
- }
-}