From 41691b7fe21da6608bb90023431f9cdf8fd9b7da Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:35:43 +0000 Subject: [PATCH 01/49] feat(workspace): add openhuman-process crate and reqwest dependency Register the new tinyhivemind-openhuman-process crate as a workspace member and add a default-features-off reqwest dependency for its loopback HTTP and SSE client, keeping TLS, HTTP/2 and proxy lookup out so a seat's token never reaches a proxy. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.toml | 10 ++- .../tinyhivemind-openhuman-process/Cargo.toml | 72 +++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 crates/tinyhivemind-openhuman-process/Cargo.toml diff --git a/Cargo.toml b/Cargo.toml index 7ff9ffcf..09dc8a8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" # package, each directory named for the package it holds. There is no root # package: the crate a host links is `crates/tinyhivemind-core`, the same as any # other member. Keeping the root virtual is what makes that uniform. -members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host"] +members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host", "crates/tinyhivemind-openhuman-process"] # `worktrees/` holds `git worktree` checkouts of this same repository; each # contains a full copy of this manifest. Keep them excluded from Cargo # workspace discovery. @@ -31,6 +31,14 @@ tinyhivemind-exec = { path = "crates/tinyhivemind-exec" } sha2 = "0.10" # Harness-neutral tool belt, policies, package plans and process supervision. tinyhivemind-host = { path = "crates/tinyhivemind-host" } +# The HTTP client process harness clients speak to a harness's loopback API +# with: JSON-RPC posts and a Server-Sent Events stream. Default features off, +# so no TLS stack, no HTTP/2 and no proxy lookup from the environment: every +# URL is `http://127.0.0.1`, and a proxy must never see a seat's token. It is +# already in this lockfile through the linked OpenHuman tree and `wiremock`, +# and it is `MIT OR Apache-2.0`. Its streaming `Response::chunk` is all SSE +# needs, so the `stream` feature is not taken either. +reqwest = { version = "0.12", default-features = false } # Durable cross-hive coordinator used at the harness boundary. tinyhivemind-hives = { path = "crates/tinyhivemind-hives" } # Concurrent owned runner futures in the coordinator, outside core. diff --git a/crates/tinyhivemind-openhuman-process/Cargo.toml b/crates/tinyhivemind-openhuman-process/Cargo.toml new file mode 100644 index 00000000..f2ac100d --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/Cargo.toml @@ -0,0 +1,72 @@ +[package] +name = "tinyhivemind-openhuman-process" +description = "Hive seats on OpenHuman as supervised `openhuman-core` child processes, through its JSON-RPC and event stream." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" +publish = false +# This crate names no OpenHuman type and links no harness (ADR 0035): it talks +# to a pinned `openhuman-core` binary over loopback HTTP. It is a crate of its +# own, not a module of `tinyhivemind-openhuman`, so that removing the linked +# adapter and `vendor/openhuman` deletes that crate without touching this one. +# `.github/scripts/assert-pure.sh` asserts that no harness enters its graph. + +[features] +# The host's conformance suite, and the scripted fake `openhuman-core` it runs +# against, which has to be a real process and so is a binary. +conformance = ["tinyhivemind-host/conformance", "dep:toml", "dep:rustix"] + +[[bin]] +name = "tinyhivemind-fake-openhuman" +path = "tests/fake/child.rs" +required-features = ["conformance"] +test = false +doc = false + +[[test]] +name = "conformance" +required-features = ["conformance"] + +[[test]] +name = "live" +required-features = ["conformance"] + +[dependencies] +# The harness port, seat runner, verification and process supervision. +tinyhivemind-host.workspace = true +# `AgentRunner`, `TurnRequest` and `TurnOutcome`. +tinyhivemind-hives.workspace = true +# The lowered seat and its provider, which decide what may be written. +tinyhivemind-lang.workspace = true +# Loopback JSON-RPC and the `/events` stream. +reqwest.workspace = true +# Request and event payloads, and the effective config. +serde_json.workspace = true +# Typed errors. +thiserror.workspace = true +# Deadlines, the seat's locks and the close signal of a running turn. +tokio = { workspace = true, features = ["time", "sync", "macros", "rt"] } +# The fake child reads the config the runner wrote, as `openhuman-core` does. +toml = { version = "0.8", optional = true } +# The fake child's grandchild leaves its session with `setsid`; the workspace +# forbids `unsafe`, so `std`'s `pre_exec` is out. Already in the lockfile. +rustix = { version = "1.1", default-features = false, features = ["std", "process"], optional = true } + +[dev-dependencies] +tinyhivemind-host = { workspace = true, features = ["conformance"] } +# Fallible tests over several error types. +anyhow.workspace = true +# Async tests, and the in-process fake's listener. +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "io-util", "time", "sync", "process"] } +# Seat and control directories. +tempfile.workspace = true +# The in-process fake reads the written config. +toml = "0.8" +# Killing a seat's child in the conformance suite. +rustix = { version = "1.1", default-features = false, features = ["std", "process"] } + +[lints] +workspace = true From d0bf86fe53c3f23c54bd66757c435fdcda4d4772 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:35:52 +0000 Subject: [PATCH 02/49] feat(host): add refused error variant for unsupported seats Add a Refused variant to the harness error enum so a seat that asks for something the harness cannot honour is reported without being started, with the client's own error preserved as the source for downcasting. The openhuman-process crate gains tokio's net and io-util features to support this. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-host/src/harness/error.rs | 4 ++++ crates/tinyhivemind-openhuman-process/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/tinyhivemind-host/src/harness/error.rs b/crates/tinyhivemind-host/src/harness/error.rs index 04531839..e4bb45cc 100644 --- a/crates/tinyhivemind-host/src/harness/error.rs +++ b/crates/tinyhivemind-host/src/harness/error.rs @@ -15,6 +15,10 @@ pub enum Error { /// The started instance is not what was asked for. #[error(transparent)] Mismatch(#[from] Mismatch), + /// The seat asks for something this harness cannot honour, so it is not + /// started. The client's own error says what, and may be downcast to it. + #[error("the seat cannot run on this harness: {0}")] + Refused(#[source] Box), /// The harness refused a call, broke its protocol or went away. #[error("harness failed: {0}")] Harness(String), diff --git a/crates/tinyhivemind-openhuman-process/Cargo.toml b/crates/tinyhivemind-openhuman-process/Cargo.toml index f2ac100d..04173e7e 100644 --- a/crates/tinyhivemind-openhuman-process/Cargo.toml +++ b/crates/tinyhivemind-openhuman-process/Cargo.toml @@ -48,7 +48,7 @@ serde_json.workspace = true # Typed errors. thiserror.workspace = true # Deadlines, the seat's locks and the close signal of a running turn. -tokio = { workspace = true, features = ["time", "sync", "macros", "rt"] } +tokio = { workspace = true, features = ["time", "sync", "macros", "rt", "net", "io-util"] } # The fake child reads the config the runner wrote, as `openhuman-core` does. toml = { version = "0.8", optional = true } # The fake child's grandchild leaves its session with `setsid`; the workspace From a791c234248544845a197695e5ca5d4325aea6fc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:36:01 +0000 Subject: [PATCH 03/49] test(host): cover refused seat preserving the client error Add a test asserting that a refused seat renders the client's own error message and keeps the original source available for downcasting, so the wrapping behaviour stays intact. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-host/src/harness/test/payloads.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/tinyhivemind-host/src/harness/test/payloads.rs b/crates/tinyhivemind-host/src/harness/test/payloads.rs index a4d0c02f..3ba19ed1 100644 --- a/crates/tinyhivemind-host/src/harness/test/payloads.rs +++ b/crates/tinyhivemind-host/src/harness/test/payloads.rs @@ -171,3 +171,17 @@ fn a_port_error_reaches_the_coordinator_as_its_own_message() { }; assert!(resume.to_string().contains("s1")); } + +#[test] +fn a_refused_seat_keeps_the_clients_own_error() { + let reason = std::io::Error::other("no provider"); + let error = Error::Refused(Box::new(reason)); + assert_eq!( + error.to_string(), + "the seat cannot run on this harness: no provider" + ); + let Error::Refused(source) = error else { + unreachable!("built as refused") + }; + assert!(source.downcast_ref::().is_some()); +} From 15d2492b8c827c723641644272c3d798a6f34155 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:36:26 +0000 Subject: [PATCH 04/49] feat(capability): add capability module for openhuman process Introduce a capability module that exposes the process crate's capabilities to the rest of the system. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/capability/mod.rs | 200 ++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/capability/mod.rs diff --git a/crates/tinyhivemind-openhuman-process/src/capability/mod.rs b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs new file mode 100644 index 00000000..0a4ab0c2 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs @@ -0,0 +1,200 @@ +//! What a lowered seat may ask of an OpenHuman process, and what it gets. +//! +//! [`check`] reads a [`LoweredSeat`] against the `openhuman` column of the +//! capability table in `docs/specs/harnesses.md` and returns the [`SeatModel`] +//! the generated config is written from, or the first [`Refusal`]. Everything +//! the spec marks "host side" (hive and executable tools, hooks, permission +//! layers other than `sandbox`, `autonomy`, `access`, package MCP servers) is +//! the MCP server's business and is not judged here. +use tinyhivemind_lang::{GroupMode, LoweredSeat, ProviderKind, Sandbox}; + +/// Model iterations after which the released binary ends a custom agent's +/// turn, reporting it as a normal end. +pub const ITERATION_CAP: usize = 8; + +/// The one provider route a seat runs on. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SeatModel { + /// The provider's id in the package, for messages. + pub provider: String, + /// The Chat Completions base URL, as declared. + pub endpoint: String, + /// The provider's model name. + pub model: String, + /// Most model iterations a turn may start, at most [`ITERATION_CAP`]. + pub iterations: usize, +} + +/// Why a seat cannot run on this harness. Each names the field. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum Refusal { + /// The seat resolves to no model at all. + #[error("the seat names no model")] + NoModel, + /// The model has no provider, so it would inherit one; a child process + /// has none and never falls back to its own. + #[error("model {model} names no provider, and a process harness has none to inherit")] + NoProvider { + /// The model's id. + model: String, + }, + /// The provider's kind is not one this harness has been shown to run. + #[error("provider {provider} is of kind {kind}, which this harness does not run")] + ProviderKind { + /// The provider's id. + provider: String, + /// Its kind, as a package names it. + kind: &'static str, + }, + /// An `openai` provider without an explicit endpoint. + #[error("provider {provider} has no endpoint")] + NoEndpoint { + /// The provider's id. + provider: String, + }, + /// A provider credential, which no conformance test has proven yet. + #[error("provider {provider} has a credential, which this harness does not take yet")] + Credential { + /// The provider's id. + provider: String, + }, + /// A model setting the generated config cannot carry. + #[error("model {model} sets {setting}, which this harness does not take")] + ModelSetting { + /// The model's id. + model: String, + /// `temperature` or `max_tokens`. + setting: &'static str, + }, + /// More iterations than the binary runs. + #[error("the seat asks for {asked} iterations, more than the {cap} this harness runs")] + Iterations { + /// What the seat asked for. + asked: usize, + /// [`ITERATION_CAP`]. + cap: usize, + }, + /// A spend limit, which nothing here can enforce. + #[error("the seat sets limits.budget_usd, which this harness cannot enforce")] + Budget, + /// A sandbox, which would not reach the executable tools the host serves. + #[error("permission set {permission} asks for a sandbox, which this harness cannot provide")] + Sandbox { + /// The permission set's id. + permission: String, + }, + /// Built-in tools, which start off for every process harness. + #[error("the seat turns on built-in tool group {group}")] + ToolGroup { + /// The group. + group: String, + }, + /// A field this harness does not take at all yet. + #[error("the seat sets {0}, which this harness does not take")] + Unsupported(&'static str), +} + +/// What `seat` runs on, if this harness can honour all of it. +/// +/// # Errors +/// The first [`Refusal`], provider rows first. +pub fn check(seat: &LoweredSeat) -> Result { + let integration = &seat.integration; + let lowered = integration.model.as_ref().ok_or(Refusal::NoModel)?; + let model = &lowered.model; + let provider = lowered.provider.as_ref().ok_or_else(|| Refusal::NoProvider { + model: model.id.clone(), + })?; + let kind = match provider.kind { + ProviderKind::Openai => None, + ProviderKind::Inherit => Some("inherit"), + ProviderKind::Openrouter => Some("openrouter"), + ProviderKind::Anthropic => Some("anthropic"), + }; + if let Some(kind) = kind { + return Err(Refusal::ProviderKind { + provider: provider.id.clone(), + kind, + }); + } + let endpoint = provider + .endpoint + .clone() + .filter(|endpoint| !endpoint.trim().is_empty()) + .ok_or_else(|| Refusal::NoEndpoint { + provider: provider.id.clone(), + })?; + if provider.credential.is_some() { + return Err(Refusal::Credential { + provider: provider.id.clone(), + }); + } + for (set, setting) in [ + (model.temperature.is_some(), "temperature"), + (model.max_tokens.is_some(), "max_tokens"), + ] { + if set { + return Err(Refusal::ModelSetting { + model: model.id.clone(), + setting, + }); + } + } + let iterations = integration.limits.iterations.unwrap_or(ITERATION_CAP); + if iterations > ITERATION_CAP { + return Err(Refusal::Iterations { + asked: iterations, + cap: ITERATION_CAP, + }); + } + if integration.limits.budget_usd.is_some() { + return Err(Refusal::Budget); + } + unsupported(seat)?; + Ok(SeatModel { + provider: provider.id.clone(), + endpoint, + model: model.name.clone(), + iterations, + }) +} + +/// Everything else the table rejects for this kind. +fn unsupported(seat: &LoweredSeat) -> Result<(), Refusal> { + let integration = &seat.integration; + if let Some(set) = integration + .permissions + .iter() + .find(|set| set.sandbox != Sandbox::None) + { + return Err(Refusal::Sandbox { + permission: set.id.clone(), + }); + } + if let Some((group, _)) = integration + .groups + .iter() + .find(|(_, mode)| **mode != GroupMode::Off) + { + return Err(Refusal::ToolGroup { + group: group.clone(), + }); + } + let fields = [ + (seat.memory.is_some(), "memory"), + (integration.agent_id.is_some(), "agent_id"), + (integration.definition_base.is_some(), "definition_base"), + (!integration.subagents.is_empty(), "subagents"), + (!integration.skills.is_empty(), "skills"), + (!integration.context.is_empty(), "context"), + (integration.bare_prompt, "bare_prompt"), + ]; + match fields.into_iter().find(|(set, _)| *set) { + Some((_, field)) => Err(Refusal::Unsupported(field)), + None => Ok(()), + } +} + +#[cfg(test)] +mod test; From 143eecc19109e6c15c0a2ea73ef7ccb1258b2c47 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:37:00 +0000 Subject: [PATCH 05/49] test(capability): add tests for capability handling Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/capability/test.rs | 228 ++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/capability/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/capability/test.rs b/crates/tinyhivemind-openhuman-process/src/capability/test.rs new file mode 100644 index 00000000..69bd4400 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/test.rs @@ -0,0 +1,228 @@ +//! The `openhuman` column of the capability table, row by row. +use super::{ITERATION_CAP, Refusal, SeatModel, check}; +use tinyhivemind_lang::{ + GroupMode, LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, PermissionSet, Provider, + ProviderKind, Sandbox, SecretRef, +}; + +/// A seat on `openai` at an explicit endpoint, with nothing else set. +pub(crate) fn seat() -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind: ProviderKind::Openai, + endpoint: Some("http://127.0.0.1:9/v1".into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: serde_json::Value::Null, + prompt: "You scout.".into(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +fn refused(change: impl FnOnce(&mut LoweredSeat)) -> Refusal { + let mut seat = seat(); + change(&mut seat); + match check(&seat) { + Err(refusal) => refusal, + Ok(model) => unreachable!("accepted {model:?}"), + } +} + +fn provider(seat: &mut LoweredSeat) -> &mut Provider { + let model = seat.integration.model.as_mut().map(|model| &mut model.provider); + let provider = model.and_then(Option::as_mut); + provider.unwrap_or_else(|| unreachable!("the seat has a provider")) +} + +fn model(seat: &mut LoweredSeat) -> &mut Model { + let model = seat.integration.model.as_mut().map(|model| &mut model.model); + model.unwrap_or_else(|| unreachable!("the seat has a model")) +} + +#[test] +fn openai_at_an_explicit_endpoint_without_a_credential_is_accepted() { + let accepted = check(&seat()); + let expected = SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: ITERATION_CAP, + }; + assert_eq!(accepted, Ok(expected)); +} + +#[test] +fn every_other_provider_row_is_rejected() { + assert_eq!( + refused(|seat| seat.integration.model = None), + Refusal::NoModel + ); + let inherits = refused(|seat| { + if let Some(model) = &mut seat.integration.model { + model.provider = None; + } + }); + assert_eq!( + inherits, + Refusal::NoProvider { + model: "fast".into() + } + ); + for (kind, name) in [ + (ProviderKind::Inherit, "inherit"), + (ProviderKind::Openrouter, "openrouter"), + (ProviderKind::Anthropic, "anthropic"), + ] { + let refusal = refused(|seat| provider(seat).kind = kind); + let expected = Refusal::ProviderKind { + provider: "local".into(), + kind: name, + }; + assert_eq!(refusal, expected); + } + for endpoint in [None, Some(" ".to_owned())] { + let refusal = refused(|seat| provider(seat).endpoint = endpoint); + let expected = Refusal::NoEndpoint { + provider: "local".into(), + }; + assert_eq!(refusal, expected); + } + let credential = refused(|seat| provider(seat).credential = Some(SecretRef::Env("K".into()))); + let expected = Refusal::Credential { + provider: "local".into(), + }; + assert_eq!(credential, expected); +} + +#[test] +fn model_settings_the_config_cannot_carry_are_rejected() { + let temperature = refused(|seat| model(seat).temperature = Some(0.2)); + assert!(matches!( + temperature, + Refusal::ModelSetting { + setting: "temperature", + .. + } + )); + let tokens = refused(|seat| model(seat).max_tokens = Some(10)); + assert!(matches!( + tokens, + Refusal::ModelSetting { + setting: "max_tokens", + .. + } + )); +} + +#[test] +fn more_iterations_than_the_cap_are_rejected_and_fewer_are_kept() { + let refusal = refused(|seat| seat.integration.limits.iterations = Some(9)); + assert_eq!(refusal, Refusal::Iterations { asked: 9, cap: 8 }); + let mut fewer = seat(); + fewer.integration.limits.iterations = Some(3); + assert_eq!(check(&fewer).map(|model| model.iterations), Ok(3)); + let budget = refused(|seat| seat.integration.limits.budget_usd = Some(1.0)); + assert_eq!(budget, Refusal::Budget); +} + +#[test] +fn a_sandbox_and_built_in_tools_are_rejected() { + for sandbox in [Sandbox::ReadOnly, Sandbox::Sandboxed] { + let refusal = refused(|seat| { + let set = PermissionSet { + id: "tight".into(), + sandbox, + ..PermissionSet::default() + }; + seat.integration.permissions.push(set); + }); + let expected = Refusal::Sandbox { + permission: "tight".into(), + }; + assert_eq!(refusal, expected); + } + let mut none = seat(); + none.integration.permissions.push(PermissionSet::default()); + none.integration.groups.insert("shell".into(), GroupMode::Off); + assert!(check(&none).is_ok()); + for mode in [GroupMode::Advertised, GroupMode::Withheld] { + let refusal = refused(|seat| { + seat.integration.groups.insert("shell".into(), mode); + }); + let expected = Refusal::ToolGroup { + group: "shell".into(), + }; + assert_eq!(refusal, expected); + } +} + +#[test] +fn fields_this_harness_does_not_take_are_named() { + let cases: [(&str, fn(&mut LoweredSeat)); 6] = [ + ("agent_id", |seat| { + seat.integration.agent_id = Some("a".into()); + }), + ("definition_base", |seat| { + seat.integration.definition_base = Some("b".into()); + }), + ("subagents", |seat| { + seat.integration.subagents.push("helper".into()); + }), + ("context", |seat| { + let document = ("notes.md".to_owned(), "text".to_owned()); + seat.integration.context.push(document); + }), + ("bare_prompt", |seat| seat.integration.bare_prompt = true), + ("skills", |seat| { + let skill = serde_json::json!({"id": "s", "path": "skills/s"}); + let skill = serde_json::from_value(skill).unwrap_or_else(|error| { + unreachable!("a skill of an id and a path: {error}") + }); + seat.integration.skills.push(skill); + }), + ]; + for (field, change) in cases { + assert_eq!(refused(change), Refusal::Unsupported(field), "{field}"); + } + let memory = serde_json::from_value(serde_json::json!({ + "agent_id": "scout", "namespace": "agent:scout", "kind": "agent", + "identity": {}, "root": "", "settings": {} + })); + if let Ok(memory) = memory { + assert_eq!( + refused(|seat| seat.memory = Some(memory)), + Refusal::Unsupported("memory") + ); + } +} + +#[test] +fn refusals_read_as_lowercase_sentences_naming_the_field() { + let refusal = Refusal::Iterations { asked: 9, cap: 8 }; + assert_eq!( + refusal.to_string(), + "the seat asks for 9 iterations, more than the 8 this harness runs" + ); + let unsupported = Refusal::Unsupported("memory").to_string(); + assert_eq!( + unsupported, + "the seat sets memory, which this harness does not take" + ); +} From e176ea10f0033250128f01bd6fd74e3f0fcbca92 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:37:33 +0000 Subject: [PATCH 06/49] feat(config): add openhuman process config module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/mod.rs | 206 ++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/config/mod.rs diff --git a/crates/tinyhivemind-openhuman-process/src/config/mod.rs b/crates/tinyhivemind-openhuman-process/src/config/mod.rs new file mode 100644 index 00000000..b36e9c3b --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/mod.rs @@ -0,0 +1,206 @@ +//! The `config.toml` a seat's instance runs with, and how its effective +//! config is compared with it. +//! +//! The config is built as one JSON tree from the experiment's +//! `docs/experiments/2026-11-25-process-harnesses/openhuman/config.toml.in`, +//! with the seat's provider, prompt and tools put in, and written as TOML. +//! The same tree is what [`Written::settings`] compares: every leaf that was +//! written, by its dotted path, plus the routes that must stay unset. The +//! binary silently falls back to its defaults on a config it cannot read, so +//! nothing else shows that it runs with this one. +//! +//! What is fixed, and why: +//! +//! - one cloud provider, `auth_style = "none"`, named by `primary_cloud` and by +//! every workload route, so the hosted provider is never consulted; +//! - one MCP server, the host's, with `expose = "direct"` and the seat's +//! bearer, so its tools are offered by name; +//! - one custom agent with an exact `tool_allowlist` and no denylist, because +//! `"*"` with a denylist let `mcp_call_tool` post as another seat; +//! - `auto_approve` exactly the hive tools, whose policy is the host's; +//! - memory, recall, conversation memory, search, hooks, suggestions and +//! token compression off. +//! +//! The top-level `embeddings_provider` is not written: 0.64.15 rewrites any +//! value to its hosted default on load, and nothing embeds with memory off. +mod toml; + +use crate::capability::SeatModel; +use serde_json::{Map, Value, json}; + +/// The custom agent every seat's instance runs as. +pub(crate) const AGENT_ID: &str = "thm_seat"; +/// The provider's id and slug in the generated config. +const PROVIDER: &str = "thm"; +/// Effective settings that must stay unset: any of them is another route. +const UNSET: [&str; 3] = ["api_key", "api_url", "inference_url"]; + +/// What a seat's config is made of. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Input<'a> { + /// The provider route. + pub(crate) model: &'a SeatModel, + /// The seat's id, which names its agent. + pub(crate) seat: &'a str, + /// The seat's system prompt. + pub(crate) prompt: &'a str, + /// The host's MCP server name. + pub(crate) server: &'a str, + /// Its URL. + pub(crate) url: &'a str, + /// The seat's bearer for it. + pub(crate) bearer: &'a str, + /// The model-visible names of the hive tools, which the allowlist and + /// `auto_approve` hold exactly. + pub(crate) tools: &'a [String], + /// How long the binary itself lets a turn run, in seconds. + pub(crate) turn_secs: u64, +} + +/// A config as written. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Written { + tree: Value, +} + +impl Written { + /// The config for `input`. + pub(crate) fn new(input: &Input<'_>) -> Self { + let model = input.model; + let route = format!("{PROVIDER}:{}", model.model); + let tree = json!({ + "schema_version": 13, + "chat_provider": route, + "reasoning_provider": route, + "agentic_provider": route, + "coding_provider": route, + "primary_cloud": PROVIDER, + "default_model": model.model, + "memory": { + "engine": "", + "embedding_provider": "none", + "recall": {"enabled": false}, + "conversations": {"enabled": false}, + }, + "search": {"enabled": false}, + "observability": {"analytics_enabled": false, "share_usage_data": false}, + "mcp_client": { + "enabled": true, + "servers": [{ + "name": input.server, + "endpoint": input.url, + "expose": "direct", + "enabled": true, + "auth": {"kind": "bearer_token", "token": input.bearer}, + }], + }, + "agent": { + "chat_agent_id": AGENT_ID, + "tool_dispatcher": "native", + "agent_timeout_secs": input.turn_secs, + }, + "autonomy": {"auto_approve": input.tools, "auto_approve_all": false}, + "tokenjuice": { + "router_enabled": false, + "ccr_enabled": false, + "repl_handle_enabled": false, + }, + "hooks": {"enabled": false}, + "web_chat": {"suggestions_enabled": false}, + "agent_registry": {"entries": [{ + "id": AGENT_ID, + "name": input.seat, + "description": "hive seat", + "source": "custom", + "enabled": true, + "system_prompt": input.prompt, + "tool_allowlist": input.tools, + }]}, + "cloud_providers": [{ + "id": PROVIDER, + "slug": PROVIDER, + "label": "tinyhivemind", + "endpoint": model.endpoint, + "auth_style": "none", + }], + }); + Self { tree } + } + + /// The file's text. + pub(crate) fn toml(&self) -> String { + toml::write(&self.tree) + } + + /// Every setting this config fixes, by dotted path, as written. + pub(crate) fn settings(&self) -> Vec<(String, Value)> { + let mut settings = Vec::new(); + leaves("", &self.tree, &mut settings); + settings.extend(UNSET.map(|name| (name.to_owned(), Value::Null))); + settings + } + + /// The same settings as `effective`, a `config_get` snapshot's `config`, + /// has them. A list of tables is cut down to the keys that were written + /// in each of its entries; an entry beyond them is kept whole, so that it + /// differs. + pub(crate) fn observe(&self, effective: &Value) -> Vec<(String, Value)> { + let settings = self.settings(); + let observed = settings.into_iter().map(|(path, written)| { + let found = lookup(effective, &path).cloned().unwrap_or(Value::Null); + let found = project(&written, found); + (path, found) + }); + observed.collect() + } +} + +/// Collect the leaves of `value` under `prefix`. A list is one leaf. +fn leaves(prefix: &str, value: &Value, into: &mut Vec<(String, Value)>) { + match value { + Value::Object(map) => { + for (key, value) in map { + let path = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + leaves(&path, value, into); + } + } + leaf => into.push((prefix.to_owned(), leaf.clone())), + } +} + +fn lookup<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(value, |value, key| value.get(key)) +} + +/// `found` cut down to the shape of `written`. +fn project(written: &Value, found: Value) -> Value { + match (written, found) { + (Value::Array(written), Value::Array(found)) => { + let entries = found.into_iter().enumerate().map(|(index, entry)| { + match written.get(index) { + Some(shape) => project(shape, entry), + None => entry, + } + }); + Value::Array(entries.collect()) + } + (Value::Object(written), Value::Object(mut found)) => { + let kept: Map = written + .iter() + .filter_map(|(key, shape)| { + let value = found.remove(key)?; + Some((key.clone(), project(shape, value))) + }) + .collect(); + Value::Object(kept) + } + (_, found) => found, + } +} + +#[cfg(test)] +mod test; From a7376668facb0d49867548a5e42935be42ba01a8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:37:45 +0000 Subject: [PATCH 07/49] feat(config): add toml config loader Introduce a TOML-based configuration loader for the openhuman process crate, parsing config files into the existing config structures. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/toml.rs | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/config/toml.rs diff --git a/crates/tinyhivemind-openhuman-process/src/config/toml.rs b/crates/tinyhivemind-openhuman-process/src/config/toml.rs new file mode 100644 index 00000000..3a00a895 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/toml.rs @@ -0,0 +1,71 @@ +//! JSON written as TOML, for the shapes a config has. +//! +//! Scalars and lists of scalars are `key = value` lines; tables are `[a.b]` +//! sections and lists of tables `[[a.b]]` sections, after the scalars of +//! their parent. A JSON string is a valid TOML basic string, since the escapes +//! `serde_json` writes (`\"`, `\\`, `\n`, `\uXXXX` and the like) are all TOML +//! escapes, so no value can break out of its line. Keys are the config's own +//! and are bare. `null` is left out, as TOML has none. +use serde_json::{Map, Value}; +use std::fmt::Write as _; + +/// `tree`, an object, as a TOML document. +pub(super) fn write(tree: &Value) -> String { + let mut out = String::new(); + if let Value::Object(map) = tree { + table(&mut out, "", map); + } + out +} + +fn is_table(value: &Value) -> bool { + value.is_object() +} + +fn is_table_list(value: &Value) -> bool { + matches!(value, Value::Array(items) if !items.is_empty() && items.iter().all(Value::is_object)) +} + +fn table(out: &mut String, path: &str, map: &Map) { + for (key, value) in map { + if !is_table(value) && !is_table_list(value) && !value.is_null() { + let _ = writeln!(out, "{key} = {}", inline(value)); + } + } + for (key, value) in map { + let path = if path.is_empty() { + key.clone() + } else { + format!("{path}.{key}") + }; + match value { + Value::Object(inner) => { + let _ = writeln!(out, "[{path}]"); + table(out, &path, inner); + } + Value::Array(items) if is_table_list(value) => { + for item in items.iter().filter_map(Value::as_object) { + let _ = writeln!(out, "[[{path}]]"); + table(out, &path, item); + } + } + _ => {} + } + } +} + +fn inline(value: &Value) -> String { + match value { + Value::Array(items) => { + let items: Vec = items.iter().map(inline).collect(); + format!("[{}]", items.join(", ")) + } + Value::Object(map) => { + let entries = map + .iter() + .map(|(key, value)| format!("{key} = {}", inline(value))); + format!("{{ {} }}", entries.collect::>().join(", ")) + } + scalar => scalar.to_string(), + } +} From 2c91a7114556047c908a9eea4a41408ac1a9ec56 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:38:10 +0000 Subject: [PATCH 08/49] feat(config): add tests for openhuman process config Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/test.rs | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/config/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/config/test.rs b/crates/tinyhivemind-openhuman-process/src/config/test.rs new file mode 100644 index 00000000..3def9c54 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/test.rs @@ -0,0 +1,183 @@ +//! The generated config: what it says, that it parses back, and how an +//! effective config is held against it. +use super::{AGENT_ID, Input, Written}; +use crate::capability::SeatModel; +use serde_json::{Value, json}; + +fn model() -> SeatModel { + SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: 8, + } +} + +fn written(prompt: &str, tools: &[String]) -> Written { + Written::new(&Input { + model: &model(), + seat: "scout", + prompt, + server: "hivemind", + url: "http://127.0.0.1:7/mcp", + bearer: "secret-bearer", + tools, + turn_secs: 600, + }) +} + +fn tools() -> Vec { + vec!["mcp_hivemind_post_1a2b3c".into(), "mcp_hivemind_ask_4d5e6f".into()] +} + +/// The file as `openhuman-core` reads it. +fn parsed(written: &Written) -> Value { + let text = written.toml(); + let table: ::toml::Table = text + .parse() + .unwrap_or_else(|error| unreachable!("the config does not parse: {error}\n{text}")); + serde_json::to_value(table).unwrap_or_else(|error| unreachable!("{error}")) +} + +#[test] +fn the_config_parses_back_to_what_was_built() { + let written = written("You scout.", &tools()); + assert_eq!(parsed(&written), written.tree); +} + +#[test] +fn the_allowlist_and_auto_approve_are_exactly_the_hive_tools() { + let config = parsed(&written("You scout.", &tools())); + let agent = &config["agent_registry"]["entries"][0]; + assert_eq!(agent["id"], AGENT_ID); + assert_eq!(agent["tool_allowlist"], json!(tools())); + assert!(agent.get("tool_denylist").is_none()); + assert_eq!(config["autonomy"]["auto_approve"], json!(tools())); + assert_eq!(config["autonomy"]["auto_approve_all"], false); + assert_eq!(config["agent"]["chat_agent_id"], AGENT_ID); + let text = written("You scout.", &tools()).toml(); + assert!(!text.contains("\"*\""), "{text}"); +} + +#[test] +fn the_provider_is_the_seats_alone_and_needs_no_key() { + let config = parsed(&written("You scout.", &tools())); + let providers = config["cloud_providers"].as_array().cloned(); + let providers = providers.unwrap_or_default(); + assert_eq!(providers.len(), 1); + assert_eq!(providers[0]["endpoint"], "http://127.0.0.1:9/v1"); + assert_eq!(providers[0]["auth_style"], "none"); + assert_eq!(config["primary_cloud"], providers[0]["id"]); + for route in [ + "chat_provider", + "reasoning_provider", + "agentic_provider", + "coding_provider", + ] { + assert_eq!(config[route], "thm:mock", "{route}"); + } +} + +#[test] +fn the_host_server_is_direct_with_the_seats_bearer() { + let config = parsed(&written("You scout.", &tools())); + let servers = &config["mcp_client"]["servers"]; + assert_eq!(servers.as_array().map(Vec::len), Some(1)); + assert_eq!(servers[0]["name"], "hivemind"); + assert_eq!(servers[0]["endpoint"], "http://127.0.0.1:7/mcp"); + assert_eq!(servers[0]["expose"], "direct"); + assert_eq!( + servers[0]["auth"], + json!({"kind": "bearer_token", "token": "secret-bearer"}) + ); +} + +#[test] +fn memory_search_hooks_suggestions_and_compression_are_off() { + let config = parsed(&written("You scout.", &tools())); + assert_eq!(config["memory"]["engine"], ""); + assert_eq!(config["memory"]["recall"]["enabled"], false); + assert_eq!(config["memory"]["conversations"]["enabled"], false); + assert_eq!(config["search"]["enabled"], false); + assert_eq!(config["hooks"]["enabled"], false); + assert_eq!(config["web_chat"]["suggestions_enabled"], false); + for flag in ["router_enabled", "ccr_enabled", "repl_handle_enabled"] { + assert_eq!(config["tokenjuice"][flag], false, "{flag}"); + } + assert_eq!(config["observability"]["analytics_enabled"], false); +} + +#[test] +fn a_prompt_cannot_break_out_of_its_string() { + let prompt = "line one\n[hooks]\nenabled = true\n\"\"\" ' \\ \u{1}"; + let config = parsed(&written(prompt, &tools())); + assert_eq!(config["agent_registry"]["entries"][0]["system_prompt"], prompt); + assert_eq!(config["hooks"], json!({"enabled": false})); +} + +#[test] +fn settings_name_every_leaf_written_and_the_routes_left_unset() { + let settings = written("You scout.", &tools()).settings(); + let names: Vec<&str> = settings.iter().map(|(name, _)| name.as_str()).collect(); + for name in [ + "primary_cloud", + "memory.recall.enabled", + "mcp_client.servers", + "agent_registry.entries", + "autonomy.auto_approve", + "api_key", + "inference_url", + ] { + assert!(names.contains(&name), "{name} in {names:?}"); + } + let unset = settings.iter().find(|(name, _)| name == "api_url"); + assert_eq!(unset.map(|(_, value)| value), Some(&Value::Null)); +} + +/// What `config_get` returns for the written file: the same, plus defaults. +fn effective(written: &Written) -> Value { + let mut config = written.tree.clone(); + config["agent"]["max_history_messages"] = json!(50); + config["mcp_client"]["servers"][0]["timeout_secs"] = json!(30); + config["mcp_client"]["servers"][0]["allowed_tools"] = json!([]); + config["embeddings_provider"] = json!("openhuman"); + for name in ["api_key", "api_url", "inference_url"] { + config[name] = Value::Null; + } + config +} + +#[test] +fn an_effective_config_with_defaults_added_is_the_one_written() { + let written = written("You scout.", &tools()); + let observed = written.observe(&effective(&written)); + assert_eq!(observed, written.settings()); +} + +#[test] +fn an_effective_config_that_differs_anywhere_written_is_another_one() { + let written = written("You scout.", &tools()); + let changes: [fn(&mut Value); 5] = [ + |config| config["hooks"]["enabled"] = json!(true), + |config| config["api_url"] = json!("https://hosted.example"), + |config| { + let extra = json!({"name": "other", "endpoint": "http://127.0.0.1:8/mcp"}); + if let Some(servers) = config["mcp_client"]["servers"].as_array_mut() { + servers.push(extra); + } + }, + |config| { + let tools = &mut config["agent_registry"]["entries"][0]["tool_allowlist"]; + if let Some(tools) = tools.as_array_mut() { + tools.push(json!("shell")); + } + }, + // What a config that did not parse falls back to. + |config| *config = json!({"schema_version": 13}), + ]; + for change in changes { + let mut config = effective(&written); + change(&mut config); + assert_ne!(written.observe(&config), written.settings(), "{config}"); + } +} From 5e9caec41d517fe78cc6543351bd51c6612df21b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:38:34 +0000 Subject: [PATCH 09/49] feat(openhuman-process): add crate for spawning and supervising OpenHuman child processes Introduce a new crate that launches the OpenHuman runtime as a child process and manages its lifecycle, including conformance and live tests against a fake child. The lockfile gains the crate's dependency set so the workspace builds it. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 17 +++++++++++++++++ .../tinyhivemind-openhuman-process/src/lib.rs | 3 +++ .../tests/conformance.rs | 1 + .../tests/fake/child.rs | 1 + .../tests/live.rs | 1 + 5 files changed, 23 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/lib.rs create mode 100644 crates/tinyhivemind-openhuman-process/tests/conformance.rs create mode 100644 crates/tinyhivemind-openhuman-process/tests/fake/child.rs create mode 100644 crates/tinyhivemind-openhuman-process/tests/live.rs diff --git a/Cargo.lock b/Cargo.lock index e5805aad..aa7b7dd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3622,6 +3622,23 @@ dependencies = [ "wiremock", ] +[[package]] +name = "tinyhivemind-openhuman-process" +version = "0.2.1" +dependencies = [ + "anyhow", + "reqwest", + "rustix 1.1.5", + "serde_json", + "tempfile", + "thiserror", + "tinyhivemind-hives", + "tinyhivemind-host", + "tinyhivemind-lang", + "tokio", + "toml 0.8.23", +] + [[package]] name = "tinyhivemind-tools" version = "0.2.1" diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs new file mode 100644 index 00000000..56667843 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -0,0 +1,3 @@ +//! Hive seats on OpenHuman, each a supervised `openhuman-core` process. +pub mod capability; +mod config; diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs new file mode 100644 index 00000000..4360cd35 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -0,0 +1 @@ +//! Placeholder until its slice. diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs new file mode 100644 index 00000000..f328e4d9 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs new file mode 100644 index 00000000..4360cd35 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -0,0 +1 @@ +//! Placeholder until its slice. From acd29a3c84980cdaf60e82a2c766254c7a1e089c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:38:56 +0000 Subject: [PATCH 10/49] test(capability): tighten fixtures for unsupported field checks The skill fixture now carries only an id, and the memory fixture is built with a full identity and settings and unwrapped instead of being silently skipped when parsing fails, so the unsupported-field assertions always run. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/capability/test.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/capability/test.rs b/crates/tinyhivemind-openhuman-process/src/capability/test.rs index 69bd4400..7bddde31 100644 --- a/crates/tinyhivemind-openhuman-process/src/capability/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/capability/test.rs @@ -191,7 +191,7 @@ fn fields_this_harness_does_not_take_are_named() { }), ("bare_prompt", |seat| seat.integration.bare_prompt = true), ("skills", |seat| { - let skill = serde_json::json!({"id": "s", "path": "skills/s"}); + let skill = serde_json::json!({"id": "s"}); let skill = serde_json::from_value(skill).unwrap_or_else(|error| { unreachable!("a skill of an id and a path: {error}") }); @@ -202,15 +202,15 @@ fn fields_this_harness_does_not_take_are_named() { assert_eq!(refused(change), Refusal::Unsupported(field), "{field}"); } let memory = serde_json::from_value(serde_json::json!({ - "agent_id": "scout", "namespace": "agent:scout", "kind": "agent", - "identity": {}, "root": "", "settings": {} - })); - if let Ok(memory) = memory { - assert_eq!( - refused(|seat| seat.memory = Some(memory)), - Refusal::Unsupported("memory") - ); - } + "agent_id": "scout", "namespace": "agent:scout", "kind": "agent", "root": "", + "identity": {"id": "m", "namespace": "agent:scout", "kind": "agent", "lifecycle": "run"}, + "settings": {"seat": "scout", "identity": "m", "budget_chars": 100} + })) + .unwrap_or_else(|error| unreachable!("a memory binding: {error}")); + assert_eq!( + refused(|seat| seat.memory = Some(memory)), + Refusal::Unsupported("memory") + ); } #[test] From 028c3c77ff8c8b34d25a9faee2e4ee32ffe7f1b9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:39:22 +0000 Subject: [PATCH 11/49] test(openhuman-process): add http test support helper Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/support/http.rs | 206 ++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/tests/support/http.rs diff --git a/crates/tinyhivemind-openhuman-process/tests/support/http.rs b/crates/tinyhivemind-openhuman-process/tests/support/http.rs new file mode 100644 index 00000000..8f85bc2f --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/http.rs @@ -0,0 +1,206 @@ +//! A small HTTP/1.1 server for the fakes: one request per connection, a JSON +//! answer or a close-delimited stream, and notice when the client hangs up. +//! +//! Hand-written over Tokio so that the fake child needs no web framework. It +//! reads a request line, headers and a `content-length` body; nothing else of +//! HTTP is needed by the clients it serves. +use serde_json::Value; +use std::future::Future; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::mpsc; + +/// Largest request the fakes read. +const LIMIT: usize = 4 * 1024 * 1024; + +/// One request. +#[derive(Clone, Debug, Default)] +pub(crate) struct Request { + pub(crate) method: String, + pub(crate) path: String, + pub(crate) query: String, + pub(crate) headers: Vec<(String, String)>, + pub(crate) body: Vec, +} + +impl Request { + /// The header `name`, case-insensitively. + pub(crate) fn header(&self, name: &str) -> Option<&str> { + let found = self.headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)); + found.map(|(_, value)| value.as_str()) + } + + /// The query parameter `name`, percent-decoded. + pub(crate) fn param(&self, name: &str) -> Option { + self.query.split('&').find_map(|pair| { + let (key, value) = pair.split_once('=')?; + (key == name).then(|| decode(value)) + }) + } + + /// The body as JSON, or null. + pub(crate) fn json(&self) -> Value { + serde_json::from_slice(&self.body).unwrap_or(Value::Null) + } +} + +fn decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + let hex = bytes.get(index + 1..index + 3).and_then(|hex| { + let hex = std::str::from_utf8(hex).ok()?; + u8::from_str_radix(hex, 16).ok() + }); + match (bytes[index], hex) { + (b'%', Some(byte)) => { + out.push(byte); + index += 3; + } + (b'+', _) => { + out.push(b' '); + index += 1; + } + (byte, _) => { + out.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// An answer. +#[derive(Debug)] +pub(crate) enum Reply { + /// A status and a JSON body. + Json(u16, Value), + /// `text/event-stream`, one chunk per message, until the sender is + /// dropped. Once the client hangs up the receiver is dropped, which the + /// sender sees as `closed()`. + Stream(mpsc::Receiver), +} + +/// Serve `handler` on `listener` until the task is dropped. +pub(crate) async fn serve(listener: TcpListener, handler: H) +where + H: Fn(Request) -> F + Send + Sync + 'static, + F: Future + Send + 'static, +{ + let handler = Arc::new(handler); + while let Ok((stream, _)) = listener.accept().await { + let handler = handler.clone(); + tokio::spawn(async move { + let _ = connection(stream, handler.as_ref()).await; + }); + } +} + +async fn connection(mut stream: TcpStream, handler: &H) -> std::io::Result<()> +where + H: Fn(Request) -> F, + F: Future, +{ + let Some(request) = read(&mut stream).await? else { + return Ok(()); + }; + match handler(request).await { + Reply::Json(status, body) => { + let body = body.to_string(); + let head = format!( + "HTTP/1.1 {status} {}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + reason(status), + body.len() + ); + stream.write_all(head.as_bytes()).await?; + stream.write_all(body.as_bytes()).await?; + stream.shutdown().await + } + Reply::Stream(mut chunks) => { + let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-cache\r\nconnection: close\r\n\r\n"; + stream.write_all(head.as_bytes()).await?; + stream.flush().await?; + let (mut reader, mut writer) = stream.into_split(); + let mut scratch = [0_u8; 256]; + loop { + tokio::select! { + chunk = chunks.recv() => match chunk { + Some(chunk) => { + writer.write_all(chunk.as_bytes()).await?; + writer.flush().await?; + } + None => return writer.shutdown().await, + }, + read = reader.read(&mut scratch) => { + if matches!(read, Ok(0) | Err(_)) { + // Hung up: dropping `chunks` tells the sender. + return Ok(()); + } + } + } + } + } + } +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 401 => "Unauthorized", + 404 => "Not Found", + _ => "Status", + } +} + +async fn read(stream: &mut TcpStream) -> std::io::Result> { + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 8192]; + let head_end = loop { + if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { + break end; + } + let read = stream.read(&mut chunk).await?; + if read == 0 || buffer.len() > LIMIT { + return Ok(None); + } + buffer.extend_from_slice(&chunk[..read]); + }; + let head = String::from_utf8_lossy(&buffer[..head_end]).into_owned(); + let mut lines = head.split("\r\n"); + let mut first = lines.next().unwrap_or_default().split(' '); + let method = first.next().unwrap_or_default().to_owned(); + let target = first.next().unwrap_or_default(); + let (path, query) = target.split_once('?').unwrap_or((target, "")); + let headers: Vec<(String, String)> = lines + .filter_map(|line| { + let (key, value) = line.split_once(':')?; + Some((key.trim().to_owned(), value.trim().to_owned())) + }) + .collect(); + let mut request = Request { + method, + path: path.to_owned(), + query: query.to_owned(), + headers, + body: buffer[head_end + 4..].to_vec(), + }; + let length: usize = request + .header("content-length") + .and_then(|length| length.parse().ok()) + .unwrap_or(0); + while request.body.len() < length.min(LIMIT) { + let read = stream.read(&mut chunk).await?; + if read == 0 { + return Ok(None); + } + request.body.extend_from_slice(&chunk[..read]); + } + Ok(Some(request)) +} + +/// One SSE message. +pub(crate) fn event(name: &str, data: &Value) -> String { + format!("event: {name}\ndata: {data}\n\n") +} From 4d19cf8f2d82912d09e1b2535c5998cb03b37151 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:40:44 +0000 Subject: [PATCH 12/49] feat(tests): add fake surface for openhuman process tests Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/fake/surface.rs | 458 ++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/tests/fake/surface.rs diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs new file mode 100644 index 00000000..383518a0 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -0,0 +1,458 @@ +//! A scripted fake of `openhuman-core run --headless-api`: the JSON-RPC, +//! `/health` and `/events` surface the runner uses, with the field names and +//! behaviour recorded from 0.64.15 in the harness spike. +//! +//! What it copies, because the runner must cope with it: +//! +//! - bad or unreadable TOML is not an error: the instance runs on defaults; +//! - MCP tools are listed only after a warm-up, by hashed names +//! `mcp___`; +//! - `channel_web_chat` rejects unknown params, answers with a `request_id`, +//! and may publish events before that answer arrives; +//! - events go to `/events` subscribers of the turn's `client_id`, and an +//! `approval_request` carries the approval's id as its `request_id`; +//! - a new message on a busy thread interrupts the turn on it; +//! - the custom agent ends after eight iterations as if it had finished. +//! +//! It is driven through files in a control directory shared with the test: +//! `steps/` (the scripted model, in name order), `calls.jsonl` (each model +//! call and its end), `served` (the tools the host's server serves), +//! `tools` (`extra` or `missing`), `misconfigured`, `version`, `warm` +//! (available-tools calls before MCP tools appear), and `methods.jsonl` and +//! `decisions.jsonl`, which it writes. +use super::http::{Reply, Request, event, serve}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::fs; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tokio::net::TcpListener; +use tokio::sync::{Notify, mpsc, oneshot}; + +/// The version the fake reports unless told otherwise. +pub(crate) const VERSION: &str = "0.64.15"; +/// The released binary's custom-agent iteration cap. +const CAP: u64 = 8; + +/// What the fake is started with. +#[derive(Clone, Debug)] +pub(crate) struct Setup { + /// The bearer every `/rpc` and `/events` request must carry. + pub(crate) token: String, + /// `OPENHUMAN_WORKSPACE`: holds `config.toml` and the transcripts. + pub(crate) workspace: PathBuf, + /// The control directory. + pub(crate) control: PathBuf, + /// The pid `/health` reports. + pub(crate) pid: u32, +} + +/// A running fake. +pub(crate) struct Fake { + /// Where it listens, on 127.0.0.1. + pub(crate) port: u16, + task: tokio::task::JoinHandle<()>, +} + +impl Fake { + /// Serve `setup` on a free port. + pub(crate) async fn start(setup: Setup) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + Ok(Self::on(listener, setup, port)) + } + + /// Serve `setup` on `listener`. + pub(crate) fn on(listener: TcpListener, setup: Setup, port: u16) -> Self { + let state = Arc::new(State::new(setup)); + let task = tokio::spawn(serve(listener, move |request| { + let state = state.clone(); + async move { state.handle(request).await } + })); + Self { port, task } + } +} + +impl Drop for Fake { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A turn running on a thread. +struct InFlight { + request_id: String, + cancel: Arc, +} + +struct State { + setup: Setup, + config: Value, + subscribers: Mutex)>>, + in_flight: Mutex>, + approvals: Mutex>>, + listed: AtomicUsize, + next: AtomicU64, +} + +impl State { + fn new(setup: Setup) -> Self { + let config = effective(&setup); + Self { + setup, + config, + subscribers: Mutex::default(), + in_flight: Mutex::default(), + approvals: Mutex::default(), + listed: AtomicUsize::new(0), + next: AtomicU64::new(0), + } + } + + fn control(&self, name: &str) -> PathBuf { + self.setup.control.join(name) + } + + fn read(&self, name: &str) -> Option { + fs::read_to_string(self.control(name)).ok() + } + + fn append(&self, name: &str, entry: &Value) { + let file = fs::File::options() + .create(true) + .append(true) + .open(self.control(name)); + if let Ok(mut file) = file { + let _ = writeln!(file, "{entry}"); + } + } + + async fn handle(self: Arc, request: Request) -> Reply { + if request.method == "GET" && request.path == "/health" { + let health = json!({"pid": self.setup.pid, "healthy": true, "components": {}}); + return Reply::Json(200, health); + } + let bearer = format!("Bearer {}", self.setup.token); + if request.header("authorization") != Some(bearer.as_str()) { + return Reply::Json(401, json!({"ok": false, "error": "unauthorized"})); + } + match (request.method.as_str(), request.path.as_str()) { + ("GET", "/events") => self.subscribe(&request), + ("POST", "/rpc") => { + let body = request.json(); + let id = body["id"].clone(); + let method = body["method"].as_str().unwrap_or_default().to_owned(); + self.append("methods.jsonl", &json!(method)); + let params = body["params"].clone(); + let answer = match self.clone().call(&method, ¶ms).await { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err(message) => json!({"jsonrpc": "2.0", "id": id, + "error": {"code": -32000, "message": message, "data": null}}), + }; + Reply::Json(200, answer) + } + _ => Reply::Json(404, json!({"ok": false, "error": "not_found"})), + } + } + + fn subscribe(&self, request: &Request) -> Reply { + let (sender, receiver) = mpsc::channel(1024); + let client = request.param("client_id").unwrap_or_default(); + lock(&self.subscribers).push((client, sender)); + Reply::Stream(receiver) + } + + /// Publish `name` to the subscribers of `client`. + fn publish(&self, client: &str, thread: &str, request_id: &str, name: &str, fields: Value) { + let mut data = json!({ + "event": name, "client_id": client, "thread_id": thread, "request_id": request_id, + }); + if let (Some(data), Value::Object(fields)) = (data.as_object_mut(), fields) { + data.extend(fields); + } + let frame = event(name, &data); + let mut subscribers = lock(&self.subscribers); + subscribers.retain(|(_, sender)| !sender.is_closed()); + for (_, sender) in subscribers.iter().filter(|(id, _)| id == client) { + let _ = sender.try_send(frame.clone()); + } + } + + async fn call(self: Arc, method: &str, params: &Value) -> Result { + let envelope = |result: Value| json!({"logs": ["fake"], "result": result}); + match method { + "core.version" => { + let version = self.read("version").unwrap_or_else(|| VERSION.into()); + Ok(json!({"version": version.trim()})) + } + "openhuman.config_get" => Ok(envelope(json!({ + "config": self.config, + "workspace_dir": self.setup.workspace.join("workspace"), + }))), + "openhuman.agent_registry_available_tools" => Ok(json!({"tools": self.tools()})), + "openhuman.threads_transcript_get" => { + let thread = params["thread_id"].as_str().unwrap_or_default(); + let exists = self.transcript(thread).exists(); + Ok(json!({"data": {"threadId": thread, "hasTranscript": exists}})) + } + "openhuman.channel_web_chat" => self.chat(params).map(envelope), + "openhuman.channel_web_cancel" => Ok(envelope(self.cancel(params))), + "openhuman.approval_decide" => { + let id = params["request_id"].as_str().unwrap_or_default(); + let decision = params["decision"].as_str().unwrap_or_default().to_owned(); + self.append("decisions.jsonl", &json!({"id": id, "decision": decision})); + let pending = lock(&self.approvals).remove(id); + let sender = pending.ok_or_else(|| format!("no pending approval {id}"))?; + let _ = sender.send(decision); + Ok(envelope(json!({"request_id": id}))) + } + other => Err(format!("unknown method: {other}")), + } + } + + fn tools(&self) -> Vec { + let builtin = ["shell", "mcp_call_tool", "juice_retrieve"]; + let mut tools: Vec = builtin.map(String::from).to_vec(); + let warm: usize = self.read("warm").and_then(|n| n.trim().parse().ok()).unwrap_or(2); + if self.listed.fetch_add(1, Ordering::Relaxed) >= warm { + let mut served: Vec = self + .read("served") + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default(); + if self.read("tools").as_deref() == Some("missing") { + served.pop(); + } + let servers = self.config["mcp_client"]["servers"].as_array().cloned(); + for server in servers.unwrap_or_default() { + let name = server["name"].as_str().unwrap_or_default(); + for tool in &served { + tools.push(hashed(name, tool)); + } + } + } + let tools = tools.into_iter().map(|name| json!({"name": name, "description": ""})); + tools.collect() + } + + fn transcript(&self, thread: &str) -> PathBuf { + let safe: String = thread + .chars() + .map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }) + .collect(); + self.setup.workspace.join("workspace/session_raw").join(format!("{safe}.jsonl")) + } + + fn chat(self: Arc, params: &Value) -> Result { + let known = ["client_id", "thread_id", "message", "model_override", "queue_mode"]; + for key in params.as_object().into_iter().flatten().map(|(key, _)| key) { + if !known.contains(&key.as_str()) { + return Err(format!("unknown param '{key}' for channel.web_chat")); + } + } + let agent = self.config["agent"]["chat_agent_id"].as_str().unwrap_or("orchestrator"); + let entries = self.config["agent_registry"]["entries"].as_array().cloned(); + if !entries.unwrap_or_default().iter().any(|entry| entry["id"] == agent) { + return Err(format!("chat_agent_id '{agent}' is not a runnable agent definition")); + } + let text = |key: &str| params[key].as_str().map(str::to_owned); + let (Some(client), Some(thread), Some(message)) = + (text("client_id"), text("thread_id"), text("message")) + else { + return Err("client_id, thread_id and message are required".into()); + }; + let number = self.next.fetch_add(1, Ordering::Relaxed); + let request_id = format!("req-{number}"); + let cancel = Arc::new(Notify::new()); + let flight = InFlight { + request_id: request_id.clone(), + cancel: cancel.clone(), + }; + if let Some(earlier) = lock(&self.in_flight).insert(thread.clone(), flight) { + // A second message interrupts the first, as `queue_mode` does by default. + earlier.cancel.notify_one(); + } + // The first event is out before the answer is. + let first = json!({"message": format!("Iteration 1/{CAP}"), "round": 1}); + self.publish(&client, &thread, &request_id, "iteration_start", first); + let ack = json!({"accepted": true, "client_id": client, "thread_id": thread, + "request_id": request_id}); + let ids = Ids { client, thread, request_id }; + tokio::spawn(async move { self.run(ids, message, cancel).await }); + Ok(ack) + } + + fn cancel(&self, params: &Value) -> Value { + let thread = params["thread_id"].as_str().unwrap_or_default(); + let scoped = params["request_id"].as_str(); + let mut in_flight = lock(&self.in_flight); + let target = in_flight + .get(thread) + .is_some_and(|flight| scoped.is_none_or(|id| id == flight.request_id)); + let cancelled = if target { in_flight.remove(thread) } else { None }; + let request_id = cancelled.as_ref().map(|flight| flight.request_id.clone()); + if let Some(flight) = cancelled { + flight.cancel.notify_one(); + } + json!({"cancelled": request_id.is_some(), "client_id": params["client_id"], + "thread_id": thread, "request_id": request_id, "subagents_cancelled": 0}) + } + + /// The next scripted step; null hangs. + fn step(&self) -> Value { + let mut steps: Vec = fs::read_dir(self.control("steps")) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .collect(); + steps.sort(); + for next in steps { + if let Ok(text) = fs::read_to_string(&next) + && fs::remove_file(&next).is_ok() + { + return serde_json::from_str(&text).unwrap_or(Value::Null); + } + } + Value::Null + } + + async fn run(self: Arc, ids: Ids, message: String, cancel: Arc) { + let step = self.step(); + let say = |name: &str, fields: Value| { + self.publish(&ids.client, &ids.thread, &ids.request_id, name, fields); + }; + if step["stray"].as_bool() == Some(true) { + let stray = json!({"full_response": "not yours", "request_id": "req-stray"}); + self.publish(&ids.client, &ids.thread, "req-stray", "chat_done", stray); + } + if let Some(tool) = step["approval"].as_str() { + let id = format!("approval-{}", self.next.fetch_add(1, Ordering::Relaxed)); + let (sender, decided) = oneshot::channel(); + lock(&self.approvals).insert(id.clone(), sender); + // Its `request_id` is the approval's, not the turn's. + let request = json!({"tool_name": tool, "args": {"command": ""}}); + self.publish(&ids.client, &ids.thread, &id, "approval_request", request); + let _ = decided.await; + } + let iterations = step["iterations"].as_u64().unwrap_or(1).min(CAP); + for round in 2..=iterations { + let text = format!("Iteration {round}/{CAP}"); + say("iteration_start", json!({"message": text, "round": round})); + } + if let Some(tool) = step["tool"].as_str() { + let call = json!({"tool_name": tool, "tool_call_id": "call_1", "args": {}}); + say("tool_call", call); + let result = json!({"tool_name": tool, "tool_call_id": "call_1", "success": false}); + say("tool_result", result); + } + let seen = self.remember(&ids.thread, "user", &message); + let call = self.open(seen); + if step.is_null() { + cancel.notified().await; + self.append("calls.jsonl", &json!({"call": call, "state": "aborted"})); + say("chat_error", json!({"message": "Cancelled", "error_type": "cancelled"})); + return; + } + self.append("calls.jsonl", &json!({"call": call, "state": "answered"})); + self.finish(&ids.thread, &ids.request_id); + if let Some(error) = step["error"].as_str() { + say("chat_error", json!({"message": error, "error_type": "inference"})); + return; + } + let reply = step["reply"].as_str().unwrap_or_default(); + self.remember(&ids.thread, "assistant", reply); + let tokens = step["tokens"].as_u64().unwrap_or(0); + let usage = json!({"input_tokens": tokens, "output_tokens": 2, + "cached_input_tokens": tokens / 10, "cost_usd": 0.0, "context_window": 0}); + say("text_delta", json!({"delta": reply, "delta_kind": "text", "round": 1})); + say("turn_cost", json!({"usage": usage, "round": 1})); + say("chat_done", json!({"full_response": reply, "usage": usage})); + } + + /// The turn on `thread` ended, unless a newer one replaced it. + fn finish(&self, thread: &str, request_id: &str) { + let mut in_flight = lock(&self.in_flight); + if in_flight.get(thread).is_some_and(|flight| flight.request_id == request_id) { + in_flight.remove(thread); + } + } + + /// Append to the thread's transcript; the user messages in it. + fn remember(&self, thread: &str, role: &str, text: &str) -> usize { + let path = self.transcript(thread); + if let Some(parent) = path.parent() { + let _ = fs::create_dir_all(parent); + } + let file = fs::File::options().create(true).append(true).open(&path); + if let Ok(mut file) = file { + let _ = writeln!(file, "{}", json!({"role": role, "text": text})); + } + let text = fs::read_to_string(&path).unwrap_or_default(); + text.lines().filter(|line| line.contains("\"user\"")).count() + } + + fn open(&self, seen: usize) -> u64 { + let log = self.read("calls.jsonl").unwrap_or_default(); + let count = log.lines().filter(|line| line.contains("\"open\"")).count(); + let call = u64::try_from(count).unwrap_or(u64::MAX); + let entry = json!({"call": call, "state": "open", "seen": seen, + "pid": std::process::id()}); + self.append("calls.jsonl", &entry); + call + } +} + +struct Ids { + client: String, + thread: String, + request_id: String, +} + +/// The model-visible name 0.64.15 gives a direct MCP tool. +pub(crate) fn hashed(server: &str, tool: &str) -> String { + let mut hash: u32 = 0x811c_9dc5; + for byte in format!("{server}/{tool}").bytes() { + hash = (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193); + } + format!("mcp_{server}_{tool}_{:06x}", hash & 0x00ff_ffff) +} + +/// The config the instance runs with: the file, unless it cannot be read, +/// with some of the defaults 0.64.15 adds. +fn effective(setup: &Setup) -> Value { + let control = &setup.control; + let written = fs::read_to_string(setup.workspace.join("config.toml")).ok(); + let parsed = written + .filter(|_| !control.join("misconfigured").exists()) + .and_then(|text| text.parse::().ok()) + .and_then(|table| serde_json::to_value(table).ok()); + let mut config = parsed.unwrap_or_else(|| json!({"schema_version": 13})); + config["embeddings_provider"] = json!("openhuman"); + if let Some(servers) = config["mcp_client"]["servers"].as_array_mut() { + for server in servers { + server["timeout_secs"] = json!(30); + } + } + if fs::read_to_string(control.join("tools")).as_deref() == Ok("extra") { + let entries = config["agent_registry"]["entries"].as_array_mut(); + for entry in entries.into_iter().flatten() { + if let Some(tools) = entry["tool_allowlist"].as_array_mut() { + tools.push(json!("shell")); + } + } + } + config +} + +/// A control directory for one fake, with its `steps/`. +pub(crate) fn control(root: &Path) -> std::io::Result { + let control = root.join("control"); + fs::create_dir_all(control.join("steps"))?; + Ok(control) +} From 1e9938d853714277edf1f8cb729320b16abd2c04 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:41:08 +0000 Subject: [PATCH 13/49] feat(fixture): add openhuman process fixture Introduce a fixture for the openhuman process crate so tests can exercise the process handling against a stable, reusable setup. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/fixture.rs | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/fixture.rs diff --git a/crates/tinyhivemind-openhuman-process/src/fixture.rs b/crates/tinyhivemind-openhuman-process/src/fixture.rs new file mode 100644 index 00000000..cd18834e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/fixture.rs @@ -0,0 +1,117 @@ +//! Unit-test fixture: the in-process fake surface, a seat config written for +//! it, and a client. +use crate::capability::SeatModel; +use crate::config::{Input, Written}; +use crate::fake::{Fake, Setup, control, hashed}; +use crate::rpc::Client; +use serde_json::{Value, json}; +use std::fs; +use std::path::PathBuf; + +pub(crate) const TOKEN: &str = "fake-core-token"; +pub(crate) const PID: u32 = 4242; +pub(crate) const SERVER: &str = "hivemind"; + +/// A fake instance with a written config. +pub(crate) struct Fixture { + pub(crate) root: tempfile::TempDir, + pub(crate) control: PathBuf, + pub(crate) written: Written, + pub(crate) client: Client, + pub(crate) fake: Fake, +} + +pub(crate) fn served() -> Vec { + vec!["hivemind_post".into(), "hivemind_ask".into()] +} + +pub(crate) fn hashed_tools() -> Vec { + served().iter().map(|tool| hashed(SERVER, tool)).collect() +} + +pub(crate) fn model() -> SeatModel { + SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: 8, + } +} + +impl Fixture { + /// A fake whose control directory already holds `files`. + pub(crate) async fn with(files: &[(&str, &str)]) -> Self { + let root = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let control = control(root.path()).unwrap_or_else(|error| unreachable!("{error}")); + let workspace = root.path().join("ws"); + let tools = hashed_tools(); + let model = model(); + let written = Written::new(&Input { + model: &model, + seat: "scout", + prompt: "You scout.", + server: SERVER, + url: "http://127.0.0.1:1/mcp", + bearer: "bearer", + tools: &tools, + turn_secs: 600, + }); + let wrote = fs::create_dir_all(&workspace) + .and_then(|()| fs::write(workspace.join("config.toml"), written.toml())) + .and_then(|()| fs::write(control.join("served"), json!(served()).to_string())); + for (name, text) in files { + let _ = fs::write(control.join(name), text); + } + assert!(wrote.is_ok(), "{wrote:?}"); + let setup = Setup { + token: TOKEN.into(), + workspace, + control: control.clone(), + pid: PID, + }; + let fake = Fake::start(setup).await; + let fake = fake.unwrap_or_else(|error| unreachable!("the fake starts: {error}")); + let client = Client::new(fake.port, TOKEN); + let client = client.unwrap_or_else(|error| unreachable!("a client: {error}")); + Self { + root, + control, + written, + client, + fake, + } + } + + pub(crate) async fn new() -> Self { + Self::with(&[]).await + } + + /// Have the model play `steps` from its next call on. + pub(crate) fn script(&self, steps: &[Value]) { + for (index, step) in steps.iter().enumerate() { + let path = self.control.join("steps").join(format!("{index:04}")); + let _ = fs::write(path, step.to_string()); + } + } + + /// Each line of a control file the fake writes. + pub(crate) fn log(&self, name: &str) -> Vec { + let text = fs::read_to_string(self.control.join(name)).unwrap_or_default(); + text.lines().filter_map(|line| serde_json::from_str(line).ok()).collect() + } + + /// The states of the model calls, in order. + pub(crate) fn calls(&self) -> Vec { + let mut states: Vec = Vec::new(); + for entry in self.log("calls.jsonl") { + let index = usize::try_from(entry["call"].as_u64().unwrap_or(0)).unwrap_or(0); + let state = entry["state"].as_str().unwrap_or_default().to_owned(); + if index < states.len() { + states[index] = state; + } else { + states.push(state); + } + } + states + } +} From f47d6fd31628acc0b125c7bbf688c4f982617e72 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:41:25 +0000 Subject: [PATCH 14/49] test(rpc): add tests for openhuman rpc process handling Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/rpc/test.rs | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/rpc/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs new file mode 100644 index 00000000..887dcca8 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -0,0 +1,104 @@ +//! The loopback client against the fake surface, and the SSE parser alone. +use super::sse::Parser; +use super::{Client, Error}; +use crate::fixture::{Fixture, PID}; +use serde_json::json; + +#[tokio::test] +async fn health_reports_the_process_that_answers() { + let fixture = Fixture::new().await; + let health = fixture.client.health().await; + assert_eq!(health.ok().map(|health| health["pid"].clone()), Some(json!(PID))); +} + +#[tokio::test] +async fn a_call_returns_its_result() { + let fixture = Fixture::new().await; + let version = fixture.client.call("core.version", json!({})).await; + assert_eq!(version.ok(), Some(json!({"version": "0.64.15"}))); +} + +#[tokio::test] +async fn a_wrong_token_is_refused_by_status() { + let fixture = Fixture::new().await; + let client = Client::new(fixture.fake.port, "wrong"); + let client = client.unwrap_or_else(|error| unreachable!("{error}")); + let refused = client.call("core.version", json!({})).await; + assert!( + matches!(refused, Err(Error::Status { status: 401, .. })), + "{refused:?}" + ); + let events = client.events("c").await.err(); + assert!(matches!(events, Some(Error::Status { status: 401, .. }))); +} + +#[tokio::test] +async fn an_rpc_error_carries_its_method_and_message() { + let fixture = Fixture::new().await; + let refused = fixture.client.call("openhuman.nope", json!({})).await; + let Err(Error::Rpc { method, message }) = refused else { + unreachable!("refused as an rpc error: {refused:?}") + }; + assert_eq!(method, "openhuman.nope"); + assert_eq!(message, "unknown method: openhuman.nope"); +} + +#[tokio::test] +async fn nobody_listening_is_a_transport_error() { + let port = { + let listener = std::net::TcpListener::bind("127.0.0.1:0"); + let listener = listener.unwrap_or_else(|error| unreachable!("{error}")); + listener.local_addr().map(|address| address.port()).unwrap_or(1) + }; + let client = Client::new(port, "t").unwrap_or_else(|error| unreachable!("{error}")); + let refused = client.health().await; + assert!(matches!(refused, Err(Error::Transport(_))), "{refused:?}"); +} + +#[tokio::test] +async fn events_are_those_of_the_subscribed_client_in_order() { + let fixture = Fixture::new().await; + fixture.script(&[json!({"reply": "hi", "tokens": 5})]); + let mut mine = fixture.client.events("mine").await.unwrap_or_else(|error| unreachable!("{error}")); + let params = json!({"client_id": "mine", "thread_id": "t", "message": "go"}); + let ack = fixture.client.call("openhuman.channel_web_chat", params).await; + assert_eq!(ack.ok().map(|ack| ack["result"]["accepted"].clone()), Some(json!(true))); + let mut names = Vec::new(); + while let Ok(Some(event)) = mine.next().await { + let name = event["event"].as_str().unwrap_or_default().to_owned(); + assert_eq!(event["client_id"], "mine"); + names.push(name.clone()); + if name == "chat_done" { + break; + } + } + assert_eq!(names, ["iteration_start", "text_delta", "turn_cost", "chat_done"]); +} + +#[tokio::test] +async fn a_stream_the_server_drops_ends() { + let fixture = Fixture::new().await; + let mut events = fixture.client.events("c").await.unwrap_or_else(|error| unreachable!("{error}")); + drop(fixture); + let ended = events.next().await; + assert!(matches!(ended, Ok(None) | Err(Error::Transport(_))), "{ended:?}"); +} + +#[test] +fn sse_frames_split_anywhere_are_put_back_together() { + let text = ": keep-alive\n\nevent: a\ndata: {\"n\":\n data: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; + for split in 0..text.len() { + let mut parser = Parser::default(); + let mut found = parser.push(&text.as_bytes()[..split]); + found.extend(parser.push(&text.as_bytes()[split..])); + let found: Vec<_> = found.into_iter().map(|frame| frame.map_err(|error| error.to_string())).collect(); + assert_eq!(found, [Ok(json!({"n": 1})), Ok(json!({"n": 2}))], "split at {split}"); + } +} + +#[test] +fn an_sse_frame_that_is_not_json_is_an_error() { + let mut parser = Parser::default(); + let found = parser.push(b"data: nope\n\n"); + assert!(matches!(found.as_slice(), [Err(Error::Decode(_))]), "{found:?}"); +} From c0cde4c147e9b16bb256d7fb5ff4ddb5d7d1e575 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:41:34 +0000 Subject: [PATCH 15/49] test(rpc): fix malformed sse fixture in split-frame test The test fixture had a stray leading space before the second data line, which made the sample payload invalid SSE. Removing it keeps the split-anywhere test exercising well-formed frames. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-openhuman-process/src/rpc/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs index 887dcca8..84376ffc 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -86,7 +86,7 @@ async fn a_stream_the_server_drops_ends() { #[test] fn sse_frames_split_anywhere_are_put_back_together() { - let text = ": keep-alive\n\nevent: a\ndata: {\"n\":\n data: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; + let text = ": keep-alive\n\nevent: a\ndata: {\"n\":\ndata: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; for split in 0..text.len() { let mut parser = Parser::default(); let mut found = parser.push(&text.as_bytes()[..split]); From 7a7a4f30eb038df1235d481dc174aa4d587ff0c3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:44:43 +0000 Subject: [PATCH 16/49] feat(openhuman-process): add rpc module and test fixtures Wire the new rpc module into the crate and expose the shared test support, fake surface, and fixture modules under cfg(test) so unit tests can reuse them. Also make the fake surface's tools check tolerant of read errors instead of comparing against a Result. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-openhuman-process/src/lib.rs | 10 + .../src/rpc/mod.rs | 161 +++++++++++++ .../src/rpc/sse.rs | 41 ++++ .../src/turn/test.rs | 223 ++++++++++++++++++ .../tests/fake/surface.rs | 2 +- 5 files changed, 436 insertions(+), 1 deletion(-) create mode 100644 crates/tinyhivemind-openhuman-process/src/rpc/mod.rs create mode 100644 crates/tinyhivemind-openhuman-process/src/rpc/sse.rs create mode 100644 crates/tinyhivemind-openhuman-process/src/turn/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs index 56667843..d0eb3c71 100644 --- a/crates/tinyhivemind-openhuman-process/src/lib.rs +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -1,3 +1,13 @@ //! Hive seats on OpenHuman, each a supervised `openhuman-core` process. pub mod capability; mod config; +mod rpc; + +#[cfg(test)] +#[path = "../tests/support/http.rs"] +mod http; +#[cfg(test)] +#[path = "../tests/fake/surface.rs"] +mod fake; +#[cfg(test)] +mod fixture; diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs new file mode 100644 index 00000000..eee6c822 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs @@ -0,0 +1,161 @@ +//! The instance's loopback API: JSON-RPC at `/rpc`, `/health`, and the +//! `/events` stream of one `client_id`. +//! +//! Every request carries the instance's core token as a bearer. The client +//! uses no proxy and no TLS: the URL is always `http://127.0.0.1:`. +//! Neither the token nor a request body is ever put in an error. +mod sse; + +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::time::Duration; + +/// How long one RPC may take. Turns are not RPCs: `channel_web_chat` +/// answers once the turn is accepted. +const CALL: Duration = Duration::from_secs(30); + +/// Result of an API call. +pub(crate) type Result = std::result::Result; + +/// API failures. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// Nothing answered, or the connection broke. + #[error("the instance could not be reached: {0}")] + Transport(String), + /// An answer other than 200. + #[error("{what} answered with status {status}")] + Status { + /// The endpoint. + what: &'static str, + /// Its status. + status: u16, + }, + /// A JSON-RPC error. + #[error("{method} failed: {message}")] + Rpc { + /// The method. + method: String, + /// The instance's message. + message: String, + }, + /// An answer that is not what the API says. + #[error("the instance answered with something unreadable: {0}")] + Decode(String), +} + +impl From for Error { + fn from(error: reqwest::Error) -> Self { + // Without the URL: it is loopback, and says nothing a reader needs. + Self::Transport(error.without_url().to_string()) + } +} + +/// A client of one instance. +#[derive(Clone, Debug)] +pub(crate) struct Client { + http: reqwest::Client, + base: String, + token: String, +} + +impl Client { + /// The instance at `127.0.0.1:port`, which takes `token`. + pub(crate) fn new(port: u16, token: &str) -> Result { + let http = reqwest::Client::builder().no_proxy().build()?; + Ok(Self { + http, + base: format!("http://127.0.0.1:{port}"), + token: token.to_owned(), + }) + } + + /// `GET /health`, which only a healthy instance answers with 200. + pub(crate) async fn health(&self) -> Result { + let url = format!("{}/health", self.base); + let response = self.http.get(url).timeout(CALL).send().await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { what: "/health", status }); + } + decode(&response.bytes().await?) + } + + /// Call `method` with `params`; its `result`. + pub(crate) async fn call(&self, method: &str, params: Value) -> Result { + let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}); + let response = self + .http + .post(format!("{}/rpc", self.base)) + .bearer_auth(&self.token) + .header("content-type", "application/json") + .body(body.to_string()) + .timeout(CALL) + .send() + .await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { what: "/rpc", status }); + } + let mut answer = decode(&response.bytes().await?)?; + if let Some(error) = answer.get("error").filter(|error| !error.is_null()) { + let message = error["message"].as_str().unwrap_or("no message"); + return Err(Error::Rpc { + method: method.to_owned(), + message: message.to_owned(), + }); + } + Ok(answer["result"].take()) + } + + /// Subscribe to the events of `client`. They are published to whoever + /// is subscribed when they happen, so this must come first. + pub(crate) async fn events(&self, client: &str) -> Result { + let response = self + .http + .get(format!("{}/events", self.base)) + .query(&[("client_id", client)]) + .bearer_auth(&self.token) + .send() + .await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { what: "/events", status }); + } + Ok(Events { + response, + parser: sse::Parser::default(), + ready: VecDeque::new(), + }) + } +} + +fn decode(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|error| Error::Decode(error.to_string())) +} + +/// One client's event stream. Dropping it closes the connection. +#[derive(Debug)] +pub(crate) struct Events { + response: reqwest::Response, + parser: sse::Parser, + ready: VecDeque>, +} + +impl Events { + /// The next event's payload, or `None` once the stream has ended. + pub(crate) async fn next(&mut self) -> Result> { + loop { + if let Some(ready) = self.ready.pop_front() { + return ready.map(Some); + } + match self.response.chunk().await? { + Some(chunk) => self.ready.extend(self.parser.push(&chunk)), + None => return Ok(None), + } + } + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs new file mode 100644 index 00000000..02ce17e8 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs @@ -0,0 +1,41 @@ +//! Server-Sent Events, as `/events` frames them: `event:` and `data:` lines, +//! a blank line ending each message, and `:` comments for keep-alive. +use super::Error; +use serde_json::Value; + +/// Bytes in, JSON payloads out, whatever the chunking. +#[derive(Debug, Default)] +pub(crate) struct Parser { + line: Vec, + data: Vec, +} + +impl Parser { + /// Feed `bytes`; the payloads of every message they complete. + pub(crate) fn push(&mut self, bytes: &[u8]) -> Vec> { + let mut frames = Vec::new(); + for &byte in bytes { + if byte != b'\n' { + self.line.push(byte); + continue; + } + let mut line = std::mem::take(&mut self.line); + if line.last() == Some(&b'\r') { + line.pop(); + } + if line.is_empty() { + if !self.data.is_empty() { + let data = std::mem::take(&mut self.data).join("\n"); + let parsed = serde_json::from_str(&data); + frames.push(parsed.map_err(|error| Error::Decode(error.to_string()))); + } + continue; + } + let line = String::from_utf8_lossy(&line); + if let Some(data) = line.strip_prefix("data:") { + self.data.push(data.strip_prefix(' ').unwrap_or(data).to_owned()); + } + } + frames + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/turn/test.rs b/crates/tinyhivemind-openhuman-process/src/turn/test.rs new file mode 100644 index 00000000..7239c8e5 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/test.rs @@ -0,0 +1,223 @@ +//! One turn over `channel_web_chat` and `/events`, against the fake surface. +use super::{Active, Ended, Turn, cancel, run}; +use crate::fixture::Fixture; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, PoisonError}; +use tinyhivemind_host::harness::{ + ApprovalFuture, Approver, DenyAll, Event, Observer, Progress, ToolApproval, ToolDecision, + TurnUsage, +}; +use tokio::sync::watch; + +#[derive(Default)] +struct Recorder(Mutex>); + +impl Observer for Recorder { + fn event(&self, _: &str, event: Event) { + self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event); + } +} + +impl Recorder { + fn progress(&self) -> Vec { + let events = self.0.lock().unwrap_or_else(PoisonError::into_inner); + let progress = events.iter().filter_map(|event| match event { + Event::Progress { progress, .. } => Some(progress.clone()), + _ => None, + }); + progress.collect() + } +} + +struct AllowAll; + +impl Approver for AllowAll { + fn decide(&self, _: ToolApproval) -> ApprovalFuture { + Box::pin(async { ToolDecision::Allow }) + } +} + +struct Harnessed { + fixture: Fixture, + events: Arc, + active: Arc>>, + closed: watch::Sender, +} + +impl Harnessed { + async fn new(steps: &[Value]) -> Self { + let fixture = Fixture::new().await; + fixture.script(steps); + Self { + fixture, + events: Arc::default(), + active: Arc::default(), + closed: watch::channel(false).0, + } + } + + fn turn<'a>(&'a self, approver: &'a dyn Approver, iterations: usize) -> Turn<'a> { + Turn { + client: &self.fixture.client, + seat: "scout", + thread: "thm-scout", + turn_id: "t1", + client_id: "thm-1".into(), + iterations, + observer: self.events.as_ref(), + approver, + closed: self.closed.subscribe(), + } + } + + async fn run(&self, iterations: usize) -> super::Result { + run(self.turn(&DenyAll, iterations), "go", &self.active).await + } +} + +#[tokio::test] +async fn a_turn_ends_with_its_reply_and_its_own_usage() { + let harnessed = Harnessed::new(&[json!({"reply": "done", "tokens": 40})]).await; + let ended = harnessed.run(8).await; + let usage = TurnUsage { + input_tokens: 40, + cached_input_tokens: 4, + output_tokens: 2, + reasoning_tokens: 0, + }; + let expected = Ended { + reply: Some("done".into()), + usage: Some(usage), + failure: None, + }; + assert_eq!(ended.ok(), Some(expected)); + // Published before `channel_web_chat` answered, and still seen. + let progress = harnessed.events.progress(); + assert_eq!(progress.first(), Some(&Progress::ModelCall { iteration: 1 })); + assert!(progress.contains(&Progress::Text { + delta: "done".into() + })); + assert!(harnessed.active.lock().ok().is_some_and(|active| active.is_none())); +} + +#[tokio::test] +async fn another_requests_events_are_not_this_turns() { + let step = json!({"reply": "mine", "tokens": 1, "stray": true}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await; + assert_eq!(ended.ok().and_then(|ended| ended.reply), Some("mine".into())); +} + +#[tokio::test] +async fn a_chat_error_fails_the_turn() { + let harnessed = Harnessed::new(&[json!({"error": "provider down"})]).await; + let ended = harnessed.run(8).await; + let failure = ended.ok().and_then(|ended| ended.failure); + assert!(failure.is_some_and(|failure| failure.contains("provider down"))); +} + +#[tokio::test] +async fn reaching_the_eight_iteration_cap_is_a_failed_turn_with_its_usage() { + let step = json!({"reply": "checkpoint", "tokens": 9, "iterations": 8}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await.ok(); + let failure = ended.as_ref().and_then(|ended| ended.failure.clone()); + assert!(failure.is_some_and(|failure| failure.contains("cap of 8"))); + let usage = ended.and_then(|ended| ended.usage); + assert_eq!(usage.map(|usage| usage.input_tokens), Some(9)); +} + +#[tokio::test] +async fn a_seat_limit_below_the_cap_fails_the_turn_past_it() { + let step = json!({"reply": "late", "tokens": 1, "iterations": 5}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(3).await.ok(); + let failure = ended.and_then(|ended| ended.failure); + assert!(failure.is_some_and(|failure| failure.contains("limit of 3"))); + let seven = Harnessed::new(&[json!({"reply": "ok", "iterations": 3})]).await; + let ended = seven.run(3).await.ok(); + assert_eq!(ended.and_then(|ended| ended.failure), None); +} + +#[tokio::test] +async fn a_harness_approval_is_decided_by_the_approver() { + let step = json!({"reply": "after", "approval": "shell"}); + let harnessed = Harnessed::new(&[step.clone()]).await; + assert!(harnessed.run(8).await.is_ok()); + let allowed = Harnessed::new(&[step]).await; + assert!(run(allowed.turn(&AllowAll, 8), "go", &allowed.active).await.is_ok()); + let decided = |harnessed: &Harnessed| { + let log = harnessed.fixture.log("decisions.jsonl"); + log.iter().map(|entry| entry["decision"].clone()).collect::>() + }; + assert_eq!(decided(&harnessed), [json!("deny")]); + assert_eq!(decided(&allowed), [json!("approve_once")]); +} + +#[tokio::test] +async fn a_tool_call_and_its_result_are_progress() { + let step = json!({"reply": "ok", "tool": "mcp_hivemind_hivemind_post_000001"}); + let harnessed = Harnessed::new(&[step]).await; + assert!(harnessed.run(8).await.is_ok()); + let progress = harnessed.events.progress(); + let call = Progress::ToolCall { + call_id: "call_1".into(), + tool: "mcp_hivemind_hivemind_post_000001".into(), + }; + let result = Progress::ToolResult { + call_id: "call_1".into(), + failed: true, + }; + assert!(progress.contains(&call) && progress.contains(&result), "{progress:?}"); +} + +#[tokio::test] +async fn a_cancelled_turn_is_shown_to_have_stopped() { + let harnessed = Arc::new(Harnessed::new(&[Value::Null]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { running.run(8).await.is_ok() }); + while harnessed.fixture.calls() != ["open"] { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + task.abort(); + let active = harnessed.active.lock().ok().and_then(|mut active| active.take()); + let active = active.unwrap_or_else(|| unreachable!("a dropped turn leaves itself")); + assert!(active.request_id.is_some()); + let cancelled = cancel(&harnessed.fixture.client, "thm-scout", &active).await; + assert!(cancelled.is_ok(), "{cancelled:?}"); + assert_eq!(harnessed.fixture.calls(), ["aborted"]); + // Nothing is running any more, so a second cancel returns at once. + let again = cancel(&harnessed.fixture.client, "thm-scout", &active).await; + assert!(again.is_ok()); +} + +#[tokio::test] +async fn a_closed_turn_ends_without_waiting_for_the_harness() { + let harnessed = Arc::new(Harnessed::new(&[Value::Null]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { running.run(8).await.err().map(|e| e.to_string()) }); + while harnessed.fixture.calls() != ["open"] { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + let _ = harnessed.closed.send(true); + let ended = task.await.ok().flatten(); + assert!(ended.is_some_and(|error| error.contains("closed"))); +} + +#[tokio::test] +async fn a_message_the_instance_does_not_accept_fails_and_agent_chat_is_never_used() { + let fixture = Fixture::with(&[]).await; + let harnessed = Harnessed { + fixture, + events: Arc::default(), + active: Arc::default(), + closed: watch::channel(false).0, + }; + let mut turn = harnessed.turn(&DenyAll, 8); + turn.thread = ""; + let ended = run(turn, "go", &harnessed.active).await; + assert!(ended.is_err()); + let methods = harnessed.fixture.log("methods.jsonl"); + assert!(!methods.contains(&json!("openhuman.inference_agent_chat"))); + assert!(methods.contains(&json!("openhuman.channel_web_chat"))); +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index 383518a0..5cd1bded 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -439,7 +439,7 @@ fn effective(setup: &Setup) -> Value { server["timeout_secs"] = json!(30); } } - if fs::read_to_string(control.join("tools")).as_deref() == Ok("extra") { + if fs::read_to_string(control.join("tools")).is_ok_and(|text| text == "extra") { let entries = config["agent_registry"]["entries"].as_array_mut(); for entry in entries.into_iter().flatten() { if let Some(tools) = entry["tool_allowlist"].as_array_mut() { From 6e7555e6598826035bc96e6134949c4ecf15e49e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:45:23 +0000 Subject: [PATCH 17/49] feat(turn): add turn module for openhuman process Introduce a turn module in the openhuman process crate to handle turn-level processing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/turn/mod.rs | 252 ++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/turn/mod.rs diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs new file mode 100644 index 00000000..1f591ad2 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -0,0 +1,252 @@ +//! One turn: `channel_web_chat` on the seat's thread, followed on `/events`. +//! +//! The order matters, and so does what is ignored: +//! +//! 1. Subscribe to `/events` for the turn's own `client_id` first, since +//! events go only to whoever is subscribed when they happen, and the +//! first ones can be out before `channel_web_chat` answers. +//! 2. Submit, and keep the `request_id` it returns in the seat's [`Active`], +//! which is what a cancellation names. The turn is never submitted again. +//! 3. Read events of that `request_id` only. `approval_request` is the +//! exception: its `request_id` is the approval's, and the seat's approver +//! decides it through `approval_decide`. +//! 4. `chat_done` ends the turn with its reply and usage, unless the turn +//! reached [`ITERATION_CAP`] `iteration_start` events, which the binary +//! reports as a normal end. `chat_error` and `chat_cancelled` fail it. +//! A seat limit below the cap fails the turn at the first iteration past +//! it, and the seat runner then cancels it. +//! +//! [`cancel`] is `channel_web_cancel` scoped to the request, then a wait for +//! that request's end on a fresh subscription. +use crate::capability::ITERATION_CAP; +use crate::rpc::{self, Client, Events}; +use serde_json::{Value, json}; +use std::sync::{Mutex, PoisonError}; +use tinyhivemind_host::harness::{ + Approver, Event, Observer, Progress, ToolApproval, ToolDecision, TurnUsage, +}; +use tokio::sync::watch; + +/// Result of a turn. +pub(crate) type Result = std::result::Result; + +/// Why a turn has no outcome. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// The API failed. + #[error(transparent)] + Api(#[from] rpc::Error), + /// `channel_web_chat` answered without accepting the message. + #[error("the instance did not accept the turn: {0}")] + NotAccepted(String), + /// The event stream ended before the turn did: the instance went away. + #[error("the event stream ended before the turn did")] + StreamEnded, + /// The seat is being stopped. + #[error("the turn was closed by a stop")] + Closed, +} + +/// The submitted turn of a seat, which a cancellation names. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct Active { + /// The turn's own `client_id`. + pub(crate) client_id: String, + /// What `channel_web_chat` returned, once it has. + pub(crate) request_id: Option, +} + +/// How a turn ended. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct Ended { + /// The model's reply. + pub(crate) reply: Option, + /// What the turn used, if it said. + pub(crate) usage: Option, + /// Why it failed, if it did. + pub(crate) failure: Option, +} + +/// What one turn runs with. +pub(crate) struct Turn<'a> { + pub(crate) client: &'a Client, + pub(crate) seat: &'a str, + pub(crate) thread: &'a str, + pub(crate) turn_id: &'a str, + pub(crate) client_id: String, + /// The seat's iteration limit, at most [`ITERATION_CAP`]. + pub(crate) iterations: usize, + pub(crate) observer: &'a dyn Observer, + pub(crate) approver: &'a dyn Approver, + /// Becomes true when the seat is stopped. + pub(crate) closed: watch::Receiver, +} + +fn set(active: &Mutex>, value: Option) { + *active.lock().unwrap_or_else(PoisonError::into_inner) = value; +} + +/// Run `turn` with `message`. `active` holds the submitted turn until it has +/// ended, so that a turn dropped meanwhile can be cancelled. +pub(crate) async fn run( + mut turn: Turn<'_>, + message: &str, + active: &Mutex>, +) -> Result { + let mut events = turn.client.events(&turn.client_id).await?; + let mut submitted = Active { + client_id: turn.client_id.clone(), + request_id: None, + }; + set(active, Some(submitted.clone())); + let params = json!({"client_id": turn.client_id, "thread_id": turn.thread, "message": message}); + let ack = turn.client.call("openhuman.channel_web_chat", params).await?; + let ack = &ack["result"]; + let request_id = ack["request_id"].as_str().filter(|_| ack["accepted"] == true); + let request_id = request_id.ok_or_else(|| Error::NotAccepted(ack.to_string()))?; + submitted.request_id = Some(request_id.to_owned()); + set(active, Some(submitted)); + let mut closed = turn.closed.clone(); + let ended = tokio::select! { + ended = follow(&turn, request_id, &mut events) => ended, + _ = closed.wait_for(|closed| *closed) => Err(Error::Closed), + }; + if ended.is_ok() { + set(active, None); + } + turn.closed = closed; + ended +} + +/// Read events until the request ends. +async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Result { + let mut iterations = 0_usize; + let progress = |progress| Event::Progress { + turn_id: turn.turn_id.to_owned(), + progress, + }; + while let Some(event) = events.next().await? { + let name = event["event"].as_str().unwrap_or_default(); + if name == "approval_request" { + approve(turn, &event).await?; + continue; + } + if event["request_id"] != request_id { + continue; + } + let text = |key: &str| event[key].as_str().unwrap_or_default().to_owned(); + match name { + "iteration_start" => { + iterations += 1; + let iteration = u32::try_from(iterations).unwrap_or(u32::MAX); + let step = progress(Progress::ModelCall { iteration }); + turn.observer.event(turn.seat, step); + if turn.iterations < ITERATION_CAP && iterations > turn.iterations { + let failure = format!( + "the turn started iteration {iterations}, past the seat's limit of {}", + turn.iterations + ); + return Ok(Ended { + failure: Some(failure), + ..Ended::default() + }); + } + } + "text_delta" if event["delta_kind"] == "text" => { + let delta = Progress::Text { delta: text("delta") }; + turn.observer.event(turn.seat, progress(delta)); + } + "tool_call" => { + let call = Progress::ToolCall { + call_id: text("tool_call_id"), + tool: text("tool_name"), + }; + turn.observer.event(turn.seat, progress(call)); + } + "tool_result" => { + let result = Progress::ToolResult { + call_id: text("tool_call_id"), + failed: event["success"] != true, + }; + turn.observer.event(turn.seat, progress(result)); + } + "chat_done" => { + let failure = (iterations >= ITERATION_CAP).then(|| { + format!( + "the turn reached the binary's cap of {ITERATION_CAP} iterations, which it reports as a normal end" + ) + }); + return Ok(Ended { + reply: event["full_response"].as_str().map(str::to_owned), + usage: usage(&event["usage"]), + failure, + }); + } + "chat_error" | "chat_cancelled" => { + let failure = format!("{name} ({}): {}", text("error_type"), text("message")); + return Ok(Ended { + failure: Some(failure), + ..Ended::default() + }); + } + _ => {} + } + } + Err(Error::StreamEnded) +} + +fn usage(usage: &Value) -> Option { + let count = |key: &str| usage[key].as_u64(); + Some(TurnUsage { + input_tokens: count("input_tokens")?, + cached_input_tokens: count("cached_input_tokens").unwrap_or(0), + output_tokens: count("output_tokens").unwrap_or(0), + reasoning_tokens: 0, + }) +} + +/// Ask the seat's approver, and tell the instance. +async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { + let id = event["request_id"].as_str().unwrap_or_default().to_owned(); + let request = ToolApproval { + seat: turn.seat.to_owned(), + turn_id: turn.turn_id.to_owned(), + call_id: id.clone(), + tool: event["tool_name"].as_str().unwrap_or_default().to_owned(), + arguments: event["args"].clone(), + }; + let decision = match turn.approver.decide(request).await { + ToolDecision::Allow => "approve_once", + ToolDecision::Deny { .. } => "deny", + }; + let params = json!({"request_id": id, "decision": decision}); + turn.client.call("openhuman.approval_decide", params).await?; + Ok(()) +} + +/// Cancel `active` on `thread`, returning once its request has ended. +pub(crate) async fn cancel(client: &Client, thread: &str, active: &Active) -> Result<()> { + let mut events = client.events(&active.client_id).await?; + let mut params = json!({"client_id": active.client_id, "thread_id": thread}); + if let Some(request_id) = &active.request_id { + params["request_id"] = json!(request_id); + } + let ack = client.call("openhuman.channel_web_cancel", params).await?; + let Some(cancelled) = ack["result"]["request_id"].as_str() else { + // Nothing was running, so no end follows. + return Ok(()); + }; + while let Some(event) = events.next().await? { + let ends = matches!( + event["event"].as_str(), + Some("chat_error" | "chat_cancelled" | "chat_done") + ); + if ends && event["request_id"] == cancelled { + return Ok(()); + } + } + Err(Error::StreamEnded) +} + +#[cfg(test)] +mod test; From 01f534e030ae53b0c57f7dd3a33d8eeeead3d81e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:45:39 +0000 Subject: [PATCH 18/49] fix(openhuman-process): keep the active turn when a failure is not terminal The follow loop now reports whether the instance's turn is over alongside the outcome, so a failure raised while the turn keeps running no longer clears the active turn. Empty strings in the fake surface are treated as absent, matching how the real binary omits optional fields. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-openhuman-process/src/lib.rs | 1 + .../src/turn/mod.rs | 31 ++++++++++++------- .../tests/fake/surface.rs | 2 +- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs index d0eb3c71..4bc9e115 100644 --- a/crates/tinyhivemind-openhuman-process/src/lib.rs +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -2,6 +2,7 @@ pub mod capability; mod config; mod rpc; +mod turn; #[cfg(test)] #[path = "../tests/support/http.rs"] diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs index 1f591ad2..39c530ce 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -111,15 +111,21 @@ pub(crate) async fn run( ended = follow(&turn, request_id, &mut events) => ended, _ = closed.wait_for(|closed| *closed) => Err(Error::Closed), }; - if ended.is_ok() { + turn.closed = closed; + let (ended, over) = ended?; + if over { set(active, None); } - turn.closed = closed; - ended + Ok(ended) } -/// Read events until the request ends. -async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Result { +/// Read events until the request ends, or fails while it runs on: whether +/// the instance's turn is over. +async fn follow( + turn: &Turn<'_>, + request_id: &str, + events: &mut Events, +) -> Result<(Ended, bool)> { let mut iterations = 0_usize; let progress = |progress| Event::Progress { turn_id: turn.turn_id.to_owned(), @@ -146,10 +152,11 @@ async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Resul "the turn started iteration {iterations}, past the seat's limit of {}", turn.iterations ); - return Ok(Ended { + let ended = Ended { failure: Some(failure), ..Ended::default() - }); + }; + return Ok((ended, false)); } } "text_delta" if event["delta_kind"] == "text" => { @@ -176,18 +183,20 @@ async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Resul "the turn reached the binary's cap of {ITERATION_CAP} iterations, which it reports as a normal end" ) }); - return Ok(Ended { + let ended = Ended { reply: event["full_response"].as_str().map(str::to_owned), usage: usage(&event["usage"]), failure, - }); + }; + return Ok((ended, true)); } "chat_error" | "chat_cancelled" => { let failure = format!("{name} ({}): {}", text("error_type"), text("message")); - return Ok(Ended { + let ended = Ended { failure: Some(failure), ..Ended::default() - }); + }; + return Ok((ended, true)); } _ => {} } diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index 5cd1bded..68b1543c 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -260,7 +260,7 @@ impl State { if !entries.unwrap_or_default().iter().any(|entry| entry["id"] == agent) { return Err(format!("chat_agent_id '{agent}' is not a runnable agent definition")); } - let text = |key: &str| params[key].as_str().map(str::to_owned); + let text = |key: &str| params[key].as_str().filter(|text| !text.is_empty()).map(str::to_owned); let (Some(client), Some(thread), Some(message)) = (text("client_id"), text("thread_id"), text("message")) else { From cb344c0f30726cc766eabd7d3f3aa3d2efb49adb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:46:05 +0000 Subject: [PATCH 19/49] test(instance): add coverage for process instance handling Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/instance/test.rs | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/instance/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs new file mode 100644 index 00000000..c97b2155 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -0,0 +1,94 @@ +//! Start-up verification and tool discovery, against the fake surface. +use super::verify::{discover, verify}; +use crate::error::Error; +use crate::fixture::{Fixture, PID, SERVER, hashed_tools, served}; +use std::collections::BTreeSet; +use std::time::Duration; +use tinyhivemind_host::harness::Mismatch; + +const WARM: Duration = Duration::from_secs(5); + +async fn verified(fixture: &Fixture, pid: u32) -> Result { + let tools = hashed_tools(); + verify(&fixture.client, pid, "0.64.15", &fixture.written, &tools, WARM).await +} + +#[tokio::test] +async fn the_instance_that_was_written_is_verified_after_its_warm_up() { + let fixture = Fixture::with(&[("warm", "3")]).await; + let started = verified(&fixture, PID).await; + let started = started.unwrap_or_else(|error| unreachable!("verified: {error}")); + assert_eq!(started.pid, PID); + assert_eq!(started.tools, hashed_tools().into_iter().collect::>()); + assert!(started.settings.contains("agent_registry.entries")); + assert!(started.settings.contains("api_url")); +} + +#[tokio::test] +async fn another_process_answering_is_refused() { + let fixture = Fixture::new().await; + let refused = verified(&fixture, PID + 1).await; + assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Pid { .. }))), "{refused:?}"); +} + +#[tokio::test] +async fn another_version_is_refused() { + let fixture = Fixture::with(&[("version", "0.64.14")]).await; + let refused = verified(&fixture, PID).await; + assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Version { .. }))), "{refused:?}"); +} + +#[tokio::test] +async fn a_config_that_fell_back_to_defaults_is_refused() { + let fixture = Fixture::with(&[("misconfigured", "")]).await; + let refused = verified(&fixture, PID).await; + assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Settings { .. }))), "{refused:?}"); +} + +#[tokio::test] +async fn a_tool_the_model_would_see_besides_the_hive_tools_is_refused() { + let fixture = Fixture::with(&[("tools", "extra")]).await; + let refused = verified(&fixture, PID).await; + assert!(matches!(refused, Err(Error::Mismatch(_))), "{refused:?}"); +} + +#[tokio::test] +async fn a_hive_tool_the_model_would_not_see_is_refused() { + let fixture = Fixture::with(&[("tools", "missing"), ("warm", "0")]).await; + let tools = hashed_tools(); + let refused = verify(&fixture.client, PID, "0.64.15", &fixture.written, &tools, Duration::ZERO).await; + let Err(Error::Mismatch(Mismatch::Tools { missing, unexpected })) = refused else { + unreachable!("refused for its tools: {refused:?}") + }; + assert_eq!(missing, [tools[1].clone()]); + assert!(unexpected.is_empty()); +} + +#[tokio::test] +async fn discovery_waits_out_the_warm_up_and_reads_the_hashed_names() { + let fixture = Fixture::with(&[("warm", "4")]).await; + let wanted: BTreeSet = served().into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + let mut expected = hashed_tools(); + expected.sort(); + assert_eq!(found.ok(), Some(expected)); +} + +#[tokio::test] +async fn a_tool_never_listed_fails_discovery_by_name() { + let fixture = Fixture::with(&[("tools", "missing")]).await; + let wanted: BTreeSet = served().into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, Duration::from_millis(300)).await; + let Err(Error::ToolsNotListed { missing, .. }) = found else { + unreachable!("not listed: {found:?}") + }; + assert_eq!(missing, ["hivemind_ask"]); +} + +#[tokio::test] +async fn a_tool_whose_name_another_tools_name_starts_with_is_told_apart() { + let fixture = Fixture::with(&[("served", r#"["post", "post_x"]"#), ("warm", "0")]).await; + let wanted: BTreeSet = ["post".to_owned()].into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + assert_eq!(found.ok(), Some(vec![crate::fake::hashed(SERVER, "post")])); +} From ab9e06b2bd722f34a11809a2e2e82795ec6b4b0b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:46:34 +0000 Subject: [PATCH 20/49] feat(openhuman-process): add error and instance modules Wire the new error and instance modules into the crate so the process supervision code can use them. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/error.rs | 62 ++++++++++ .../src/instance/mod.rs | 6 + .../src/instance/verify.rs | 115 ++++++++++++++++++ .../tinyhivemind-openhuman-process/src/lib.rs | 2 + 4 files changed, 185 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/error.rs create mode 100644 crates/tinyhivemind-openhuman-process/src/instance/mod.rs create mode 100644 crates/tinyhivemind-openhuman-process/src/instance/verify.rs diff --git a/crates/tinyhivemind-openhuman-process/src/error.rs b/crates/tinyhivemind-openhuman-process/src/error.rs new file mode 100644 index 00000000..80994c89 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error.rs @@ -0,0 +1,62 @@ +//! What can go wrong in this crate, and how the port sees it. +use crate::capability::Refusal; +use crate::{rpc, turn}; +use tinyhivemind_host::harness::{self, Mismatch}; +use tinyhivemind_host::process; + +/// Result of this crate's fallible steps. +pub(crate) type Result = std::result::Result; + +/// Failures before they reach the port. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// The seat asks for what this harness cannot do. + #[error(transparent)] + Refused(#[from] Refusal), + /// The instance's API failed. + #[error(transparent)] + Api(#[from] rpc::Error), + /// A turn failed to run. + #[error(transparent)] + Turn(#[from] turn::Error), + /// The process could not be supervised. + #[error(transparent)] + Process(#[from] process::Error), + /// The instance is not the one asked for. + #[error(transparent)] + Mismatch(#[from] Mismatch), + /// The instance never listed some of the host's tools. + #[error("the instance did not list {missing:?} of server {server}")] + ToolsNotListed { + /// The server. + server: String, + /// Its tools, by the names it serves them under. + missing: Vec, + }, + /// A file of the instance could not be written or read. + #[error("{what}: {source}")] + Io { + /// What it was. + what: &'static str, + /// The failure. + source: std::io::Error, + }, +} + +impl Error { + /// An I/O failure at `what`. + pub(crate) fn io(what: &'static str) -> impl FnOnce(std::io::Error) -> Self { + move |source| Self::Io { what, source } + } +} + +impl From for harness::Error { + fn from(error: Error) -> Self { + match error { + Error::Refused(refusal) => Self::Refused(Box::new(refusal)), + Error::Process(error) => Self::Process(error), + Error::Mismatch(mismatch) => Self::Mismatch(mismatch), + other => Self::Harness(other.to_string()), + } + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs new file mode 100644 index 00000000..62a8c23a --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -0,0 +1,6 @@ +//! Starting one instance: its directories, environment and config, tool +//! discovery, and the verification it must pass. +mod verify; + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs new file mode 100644 index 00000000..acbfb527 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -0,0 +1,115 @@ +//! Whether a started instance is the one that was asked for, and the names +//! its model sees the hive tools under. +use crate::config::{AGENT_ID, Written}; +use crate::error::{Error, Result}; +use crate::rpc::Client; +use serde_json::{Value, json}; +use std::collections::BTreeSet; +use std::time::Duration; +use tinyhivemind_host::harness::{Expected, Observed, Started}; +use tokio::time::Instant; + +/// How often a warming instance is asked again. +const POLL: Duration = Duration::from_millis(100); + +/// Every tool name the instance offers. +async fn available(client: &Client) -> Result> { + let listed = client.call("openhuman.agent_registry_available_tools", json!({})).await?; + let tools = listed["tools"].as_array().cloned().unwrap_or_default(); + let names = tools.iter().filter_map(|tool| tool["name"].as_str().map(str::to_owned)); + Ok(names.collect()) +} + +/// The name `tool` of `server` has among `names`: `mcp___` and +/// a hex hash, which no other tool's name also matches. +fn name_of<'a>(names: &'a [String], server: &str, tool: &str) -> Option<&'a String> { + let prefix = format!("mcp_{server}_{tool}_"); + let mut found = names.iter().filter(|name| { + name.strip_prefix(&prefix) + .is_some_and(|hash| !hash.is_empty() && hash.bytes().all(|b| b.is_ascii_hexdigit())) + }); + let first = found.next(); + first.filter(|_| found.next().is_none()) +} + +/// The model-visible names of `tools`, served by `server`, once the instance +/// has connected to it, within `warm_up`. +/// +/// # Errors +/// [`Error::ToolsNotListed`] for tools still unnamed when `warm_up` is over. +pub(crate) async fn discover( + client: &Client, + server: &str, + tools: &BTreeSet, + warm_up: Duration, +) -> Result> { + let deadline = Instant::now() + warm_up; + loop { + let names = available(client).await?; + let found: Vec<_> = tools.iter().map(|tool| name_of(&names, server, tool)).collect(); + if found.iter().all(Option::is_some) { + let mut found: Vec = found.into_iter().flatten().cloned().collect(); + found.sort(); + return Ok(found); + } + if Instant::now() >= deadline { + let missing = tools.iter().zip(&found).filter(|(_, name)| name.is_none()); + return Err(Error::ToolsNotListed { + server: server.to_owned(), + missing: missing.map(|(tool, _)| tool.clone()).collect(), + }); + } + tokio::time::sleep(POLL).await; + } +} + +/// The tools the model sees: the agent's effective allowlist, of those the +/// instance has. +fn visible(config: &Value, available: &[String]) -> Vec { + let entries = config["agent_registry"]["entries"].as_array().cloned(); + let agent = entries.unwrap_or_default().into_iter().find(|entry| entry["id"] == AGENT_ID); + let allowed = agent.map(|agent| agent["tool_allowlist"].clone()).unwrap_or(Value::Null); + let allowed = allowed.as_array().cloned().unwrap_or_default(); + let names = allowed.iter().filter_map(Value::as_str); + names.filter(|name| available.iter().any(|tool| tool == name)).map(str::to_owned).collect() +} + +/// Hold the instance at `client` against the child `pid`, the pinned +/// `version`, the `written` config and exactly `tools`, waiting up to +/// `warm_up` for its MCP tools to be listed. +/// +/// # Errors +/// [`Error::Mismatch`] for any difference, or the API's own failure. +pub(crate) async fn verify( + client: &Client, + pid: u32, + version: &str, + written: &Written, + tools: &[String], + warm_up: Duration, +) -> Result { + let health = client.health().await?; + let answering = health["pid"].as_u64().and_then(|pid| u32::try_from(pid).ok()); + let running = client.call("core.version", json!({})).await?; + let running = running["version"].as_str().unwrap_or_default().to_owned(); + let snapshot = client.call("openhuman.config_get", json!({})).await?; + let config = &snapshot["result"]["config"]; + let deadline = Instant::now() + warm_up; + let seen = loop { + let seen = visible(config, &available(client).await?); + let all = tools.iter().all(|tool| seen.contains(tool)); + if all || Instant::now() >= deadline { + break seen; + } + tokio::time::sleep(POLL).await; + }; + let mut expected = Expected::new(pid, version).tools(tools.iter().cloned()); + for (name, value) in written.settings() { + expected = expected.setting(name, value); + } + let mut observed = Observed::new(answering.unwrap_or_default(), running).tools(seen); + for (name, value) in written.observe(config) { + observed = observed.setting(name, value); + } + Ok(expected.verify(&observed)?) +} diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs index 4bc9e115..80dcc57d 100644 --- a/crates/tinyhivemind-openhuman-process/src/lib.rs +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -1,6 +1,8 @@ //! Hive seats on OpenHuman, each a supervised `openhuman-core` process. pub mod capability; mod config; +mod error; +mod instance; mod rpc; mod turn; From a2f603aca38bb97da5a77cdd641c91360122f481 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:47:04 +0000 Subject: [PATCH 21/49] test(fake): clear subscribers when the fake surface is dropped The fake now keeps a handle to its shared state so that dropping it clears the subscriber registry, matching a process that has gone away where nothing answers and every stream ends. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-openhuman-process/tests/fake/surface.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index 68b1543c..1cd05f52 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -54,6 +54,7 @@ pub(crate) struct Fake { /// Where it listens, on 127.0.0.1. pub(crate) port: u16, task: tokio::task::JoinHandle<()>, + state: Arc, } impl Fake { @@ -67,17 +68,20 @@ impl Fake { /// Serve `setup` on `listener`. pub(crate) fn on(listener: TcpListener, setup: Setup, port: u16) -> Self { let state = Arc::new(State::new(setup)); + let serving = state.clone(); let task = tokio::spawn(serve(listener, move |request| { - let state = state.clone(); + let state = serving.clone(); async move { state.handle(request).await } })); - Self { port, task } + Self { port, task, state } } } impl Drop for Fake { + /// Like a process that is gone: nothing answers and every stream ends. fn drop(&mut self) { self.task.abort(); + lock(&self.state.subscribers).clear(); } } From 86e4b27ebcb97ce64ae9c198c0dc450b6b3164e0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:47:41 +0000 Subject: [PATCH 22/49] refactor(turn): carry the thread on the active turn The active turn now records its own thread, so cancel no longer takes the thread as a separate argument and reads it from the turn instead. This keeps the cancellation parameters together with the turn they describe. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-openhuman-process/src/turn/mod.rs | 9 ++++++--- crates/tinyhivemind-openhuman-process/src/turn/test.rs | 4 ++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs index 39c530ce..a4d63230 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -50,6 +50,8 @@ pub(crate) enum Error { /// The submitted turn of a seat, which a cancellation names. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct Active { + /// The seat's thread. + pub(crate) thread: String, /// The turn's own `client_id`. pub(crate) client_id: String, /// What `channel_web_chat` returned, once it has. @@ -95,6 +97,7 @@ pub(crate) async fn run( ) -> Result { let mut events = turn.client.events(&turn.client_id).await?; let mut submitted = Active { + thread: turn.thread.to_owned(), client_id: turn.client_id.clone(), request_id: None, }; @@ -233,10 +236,10 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { Ok(()) } -/// Cancel `active` on `thread`, returning once its request has ended. -pub(crate) async fn cancel(client: &Client, thread: &str, active: &Active) -> Result<()> { +/// Cancel `active`, returning once its request has ended. +pub(crate) async fn cancel(client: &Client, active: &Active) -> Result<()> { let mut events = client.events(&active.client_id).await?; - let mut params = json!({"client_id": active.client_id, "thread_id": thread}); + let mut params = json!({"client_id": active.client_id, "thread_id": active.thread}); if let Some(request_id) = &active.request_id { params["request_id"] = json!(request_id); } diff --git a/crates/tinyhivemind-openhuman-process/src/turn/test.rs b/crates/tinyhivemind-openhuman-process/src/turn/test.rs index 7239c8e5..2a03d7b9 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/test.rs @@ -183,11 +183,11 @@ async fn a_cancelled_turn_is_shown_to_have_stopped() { let active = harnessed.active.lock().ok().and_then(|mut active| active.take()); let active = active.unwrap_or_else(|| unreachable!("a dropped turn leaves itself")); assert!(active.request_id.is_some()); - let cancelled = cancel(&harnessed.fixture.client, "thm-scout", &active).await; + let cancelled = cancel(&harnessed.fixture.client, &active).await; assert!(cancelled.is_ok(), "{cancelled:?}"); assert_eq!(harnessed.fixture.calls(), ["aborted"]); // Nothing is running any more, so a second cancel returns at once. - let again = cancel(&harnessed.fixture.client, "thm-scout", &active).await; + let again = cancel(&harnessed.fixture.client, &active).await; assert!(again.is_ok()); } From 05a84581207c725c600fb1eed0f14e19918f6972 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:48:12 +0000 Subject: [PATCH 23/49] feat(instance): start and verify an openhuman instance Add the instance module that lays out the state directories, writes the config and keyring key, builds the child environment, and runs the two-start discovery and verification flow so each instance gets an exact MCP tool allowlist before it is used. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/instance/mod.rs | 231 ++++++++++++++++++ 1 file changed, 231 insertions(+) diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs index 62a8c23a..a3ae86b4 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -1,6 +1,237 @@ //! Starting one instance: its directories, environment and config, tool //! discovery, and the verification it must pass. +//! +//! An instance lives in the seat's directory, made private by +//! [`InstanceDir`]. Its state directory holds: +//! +//! | Path | For | +//! | --- | --- | +//! | `ws/` | `OPENHUMAN_WORKSPACE`: `config.toml`, sessions, the keyring | +//! | `home/` | `HOME` | +//! | `action/` | `OPENHUMAN_ACTION_DIR`, and the working directory | +//! | `keyring.key` | the keyring's random master key, mode 0600, kept across starts | +//! +//! A start is two starts. The model-visible name of an MCP tool carries a +//! hash that only the instance knows, so the first start runs with an +//! allowlist that matches nothing, waits out the MCP warm-up and reads the +//! names from `agent_registry_available_tools`; then it is stopped, the exact +//! allowlist is written, and the second start is verified. The core token is +//! new for every start; the port is a free one, and an instance that moved +//! to another fails the pid check. `OPENHUMAN_SANDBOX` is never set. mod verify; +pub(crate) use verify::{discover, verify}; + +use crate::capability::SeatModel; +use crate::config::{Input, Written}; +use crate::error::{Error, Result}; +use crate::harness::{Options, Program}; +use crate::rpc::Client; +use std::fs; +use std::io::{Read as _, Write as _}; +use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tinyhivemind_host::harness::{SeatPlan, Started, ToolEndpoint}; +use tinyhivemind_host::process::{Instance, InstanceDir, Launch}; + +/// The allowlist of the discovery start, which no tool is called. +const NOTHING: &str = "thm_no_tool"; +/// The least a turn may run inside the binary, which has its own deadline. +const TURN_FLOOR: u64 = 600; + +/// A started, verified instance. +#[derive(Debug)] +pub(crate) struct Live { + pub(crate) instance: Instance, + pub(crate) client: Client, + pub(crate) started: Started, +} + +/// The directories of one instance's state. +#[derive(Clone, Debug)] +pub(crate) struct Layout { + state: PathBuf, +} + +impl Layout { + pub(crate) fn new(state: &Path) -> Self { + Self { + state: state.to_path_buf(), + } + } + pub(crate) fn workspace(&self) -> PathBuf { + self.state.join("ws") + } + fn home(&self) -> PathBuf { + self.state.join("home") + } + fn action(&self) -> PathBuf { + self.state.join("action") + } + fn create(&self) -> Result<()> { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true).mode(0o700); + for dir in [self.workspace(), self.home(), self.action()] { + builder.create(dir).map_err(Error::io("the instance directories"))?; + } + Ok(()) + } + + /// The keyring's master key, made on first use. + fn master_key(&self) -> Result { + let path = self.state.join("keyring.key"); + if let Ok(key) = fs::read_to_string(&path) { + return Ok(key); + } + let key = random()?; + let mut file = fs::File::options() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .map_err(Error::io("the keyring key"))?; + file.write_all(key.as_bytes()).map_err(Error::io("the keyring key"))?; + Ok(key) + } + + fn write_config(&self, written: &Written) -> Result<()> { + let path = self.workspace().join("config.toml"); + let mut file = fs::File::options() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(path) + .map_err(Error::io("the config"))?; + file.write_all(written.toml().as_bytes()).map_err(Error::io("the config")) + } +} + +/// 256 random bits, as hex. +fn random() -> Result { + let mut bytes = [0_u8; 32]; + let mut source = fs::File::open("/dev/urandom").map_err(Error::io("/dev/urandom"))?; + source.read_exact(&mut bytes).map_err(Error::io("/dev/urandom"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +/// The child's whole environment, besides what the supervisor adds. +pub(crate) fn environment(layout: &Layout, token: &str, key: &str) -> Vec<(&'static str, String)> { + let path = |path: PathBuf| path.to_string_lossy().into_owned(); + vec![ + ("PATH", "/usr/bin:/bin".into()), + ("HOME", path(layout.home())), + ("LANG", "C.UTF-8".into()), + ("OPENHUMAN_WORKSPACE", path(layout.workspace())), + ("OPENHUMAN_ACTION_DIR", path(layout.action())), + ("OPENHUMAN_TOOL_DISPATCHER", "native".into()), + ("OPENHUMAN_COMPOSIO_MODE", "disabled".into()), + // The binary asks for a backend key; this one opens nothing. + ("OPENHUMAN_BACKEND_API_KEY", "dummy".into()), + ("OPENHUMAN_KEYRING_BACKEND", "encrypted_file".into()), + ("OPENHUMAN_KEYRING_MASTER_KEY", key.into()), + ("OPENHUMAN_CORE_TOKEN", token.into()), + ("RUST_LOG", "warn".into()), + ] +} + +/// A port nobody is listening on now. +fn free_port() -> Result { + let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(Error::io("a free port"))?; + let address = listener.local_addr().map_err(Error::io("a free port"))?; + Ok(address.port()) +} + +/// How long the binary itself lets a turn run: past the seat's own limit, +/// which the seat runner enforces. +fn turn_secs(limit: Option) -> u64 { + let limit = limit.map_or(0, |limit| limit.as_secs().saturating_add(60)); + limit.max(TURN_FLOOR) +} + +/// Starts a seat's instances. +pub(crate) struct Launcher<'a> { + pub(crate) program: &'a Program, + pub(crate) options: &'a Options, + pub(crate) plan: &'a SeatPlan, + pub(crate) tools: &'a ToolEndpoint, + pub(crate) model: &'a SeatModel, +} + +impl Launcher<'_> { + /// Start, discover, restart and verify; or leave nothing running. + pub(crate) async fn launch(&self) -> Result { + let dir = InstanceDir::create(&self.plan.directory)?; + let layout = Layout::new(dir.state()); + layout.create()?; + let key = layout.master_key()?; + let (probe, written) = self.start(&dir, &layout, &key, &[NOTHING.to_owned()]).await?; + drop(written); + let server = &self.tools.server; + let names = discover(&probe.1, server, &self.tools.tools, self.options.warm_up).await; + probe.0.stop(async {}, self.options.stop).await?; + let names = names?; + let ((instance, client), written) = self.start(&dir, &layout, &key, &names).await?; + let version = &self.program.version; + let pid = instance.pid(); + let warm_up = self.options.warm_up; + match verify(&client, pid, version, &written, &names, warm_up).await { + Ok(started) => Ok(Live { + instance, + client, + started, + }), + Err(error) => { + instance.stop(async {}, self.options.stop).await?; + Err(error) + } + } + } + + /// One healthy instance with `tools` allowed. + async fn start( + &self, + dir: &InstanceDir, + layout: &Layout, + key: &str, + tools: &[String], + ) -> Result<((Instance, Client), Written)> { + let written = Written::new(&Input { + model: self.model, + seat: &self.plan.seat.id, + prompt: &self.plan.seat.prompt, + server: &self.tools.server, + url: &self.tools.url, + bearer: self.tools.bearer(), + tools, + turn_secs: turn_secs(self.plan.turn_timeout()), + }); + layout.write_config(&written)?; + let token = random()?; + let port = free_port()?; + let mut launch = Launch::new(&self.program.path, dir.clone()) + .args(["run", "--headless-api", "--host", "127.0.0.1", "--port"]) + .arg(port.to_string()) + .current_dir(layout.action()); + for (name, value) in environment(layout, &token, key) { + launch = launch.env(name, value); + } + let instance = Instance::start(launch).await?; + let client = Client::new(port, &token)?; + let probe = async { + while client.health().await.is_err() { + tokio::time::sleep(Duration::from_millis(50)).await; + } + Ok::<(), String>(()) + }; + if let Err(error) = instance.ready(probe, self.options.ready).await { + instance.stop(async {}, self.options.stop).await?; + return Err(error.into()); + } + Ok(((instance, client), written)) + } +} + #[cfg(test)] mod test; From 382155e194a2c97bbd71a730c132586fe43887b4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:48:25 +0000 Subject: [PATCH 24/49] refactor(instance): simplify launch argument construction and probe handling Reworked the launcher to build the child process arguments in a loop and to destructure the probe result directly, which keeps the start-up path easier to follow without changing behaviour. Added tests pinning the exact environment recipe and the turn timeout floor so regressions in the sandbox configuration are caught. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/instance/mod.rs | 17 +++++---- .../src/instance/test.rs | 37 +++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs index a3ae86b4..4ccf7090 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -166,11 +166,11 @@ impl Launcher<'_> { let layout = Layout::new(dir.state()); layout.create()?; let key = layout.master_key()?; - let (probe, written) = self.start(&dir, &layout, &key, &[NOTHING.to_owned()]).await?; - drop(written); + let nothing = [NOTHING.to_owned()]; + let ((probe, client), _) = self.start(&dir, &layout, &key, ¬hing).await?; let server = &self.tools.server; - let names = discover(&probe.1, server, &self.tools.tools, self.options.warm_up).await; - probe.0.stop(async {}, self.options.stop).await?; + let names = discover(&client, server, &self.tools.tools, self.options.warm_up).await; + probe.stop(async {}, self.options.stop).await?; let names = names?; let ((instance, client), written) = self.start(&dir, &layout, &key, &names).await?; let version = &self.program.version; @@ -210,10 +210,11 @@ impl Launcher<'_> { layout.write_config(&written)?; let token = random()?; let port = free_port()?; - let mut launch = Launch::new(&self.program.path, dir.clone()) - .args(["run", "--headless-api", "--host", "127.0.0.1", "--port"]) - .arg(port.to_string()) - .current_dir(layout.action()); + let mut launch = Launch::new(&self.program.path, dir.clone()).current_dir(layout.action()); + for argument in ["run", "--headless-api", "--host", "127.0.0.1", "--port"] { + launch = launch.arg(argument); + } + launch = launch.arg(port.to_string()); for (name, value) in environment(layout, &token, key) { launch = launch.env(name, value); } diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index c97b2155..072653d7 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -1,4 +1,5 @@ //! Start-up verification and tool discovery, against the fake surface. +use super::{Layout, environment, turn_secs}; use super::verify::{discover, verify}; use crate::error::Error; use crate::fixture::{Fixture, PID, SERVER, hashed_tools, served}; @@ -92,3 +93,39 @@ async fn a_tool_whose_name_another_tools_name_starts_with_is_told_apart() { let found = discover(&fixture.client, SERVER, &wanted, WARM).await; assert_eq!(found.ok(), Some(vec![crate::fake::hashed(SERVER, "post")])); } + +#[test] +fn the_environment_is_exactly_the_recipe_and_never_turns_the_sandbox_off() { + let layout = Layout::new(std::path::Path::new("/seat/state")); + let environment = environment(&layout, "token", "key"); + let names: Vec<&str> = environment.iter().map(|(name, _)| *name).collect(); + assert_eq!( + names, + [ + "PATH", + "HOME", + "LANG", + "OPENHUMAN_WORKSPACE", + "OPENHUMAN_ACTION_DIR", + "OPENHUMAN_TOOL_DISPATCHER", + "OPENHUMAN_COMPOSIO_MODE", + "OPENHUMAN_BACKEND_API_KEY", + "OPENHUMAN_KEYRING_BACKEND", + "OPENHUMAN_KEYRING_MASTER_KEY", + "OPENHUMAN_CORE_TOKEN", + "RUST_LOG", + ] + ); + let value = |name: &str| environment.iter().find(|(key, _)| *key == name).map(|(_, value)| value.as_str()); + assert_eq!(value("OPENHUMAN_WORKSPACE"), Some("/seat/state/ws")); + assert_eq!(value("OPENHUMAN_KEYRING_BACKEND"), Some("encrypted_file")); + assert_eq!(value("OPENHUMAN_BACKEND_API_KEY"), Some("dummy")); + assert!(value("OPENHUMAN_SANDBOX").is_none()); +} + +#[test] +fn the_binary_lets_a_turn_run_past_the_seats_own_limit() { + assert_eq!(turn_secs(None), 600); + assert_eq!(turn_secs(Some(Duration::from_secs(5))), 600); + assert_eq!(turn_secs(Some(Duration::from_secs(3600))), 3660); +} From 534298bbad30e3a95a3bed971ce81df29213163c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:48:44 +0000 Subject: [PATCH 25/49] feat(harness): add harness module for openhuman process Introduce a harness module to the openhuman process crate, providing the scaffolding needed to drive and manage the process. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/harness/mod.rs | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/harness/mod.rs diff --git a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs new file mode 100644 index 00000000..3f53c7f3 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs @@ -0,0 +1,134 @@ +//! [`OpenHumanHarness`]: the `openhuman` kind of the host's harness port. +//! +//! Each seat is one instance of the pinned binary, started by +//! [`crate::instance`] and run by a seat runner held to the port's rules by +//! [`SeatRunner`]. See the crate documentation for what a seat may ask for. +mod seat; + +use crate::capability; +use seat::{Runner, Seat}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use tinyhivemind_hives::AgentRunner; +use tinyhivemind_host::harness::{ + Error, Harness, HarnessKind, SeatPlan, SeatRunner, StartFuture, StopFuture, ToolEndpoint, +}; +use tinyhivemind_host::process::StopPolicy; + +/// The pinned `openhuman-core` binary. The library never downloads it: +/// `.github/scripts/fetch-harness.sh` fetches and checks the one in +/// `harnesses.lock`, and the host passes its path. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Program { + /// The binary, an absolute path. + pub path: PathBuf, + /// The version it must report, as `harnesses.lock` records it. + pub version: String, +} + +impl Program { + /// The binary at `path`, which must report `version`. + #[must_use] + pub fn new(path: impl Into, version: impl Into) -> Self { + Self { + path: path.into(), + version: version.into(), + } + } +} + +/// How long the steps of starting and stopping an instance may take. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Options { + /// From spawn to a healthy `/health`. + pub ready: Duration, + /// For the instance to list the host's tools, which it does only once + /// it has connected to the MCP server. + pub warm_up: Duration, + /// Each step of a stop. + pub stop: StopPolicy, +} + +impl Default for Options { + /// 30 s to be healthy, 20 s to warm up, and the supervisor's own stop. + fn default() -> Self { + Self { + ready: Duration::from_secs(30), + warm_up: Duration::from_secs(20), + stop: StopPolicy::default(), + } + } +} + +/// Runs seats on OpenHuman, one supervised `openhuman-core` per seat. +/// +/// Its futures must be driven within a Tokio runtime with time and I/O +/// enabled. +#[derive(Debug)] +pub struct OpenHumanHarness { + program: Program, + options: Options, + seats: Arc>>>, +} + +impl OpenHumanHarness { + /// Seats on `program`, with the default [`Options`]. + #[must_use] + pub fn new(program: Program) -> Self { + Self { + program, + options: Options::default(), + seats: Arc::default(), + } + } + + /// The same, with `options`. + #[must_use] + pub fn with_options(mut self, options: Options) -> Self { + self.options = options; + self + } +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +impl Harness for OpenHumanHarness { + fn kind(&self) -> HarnessKind { + HarnessKind::OpenHuman + } + + /// Refuses, with [`Error::Refused`] holding a [`capability::Refusal`], a + /// seat this harness cannot honour, before anything is started. + fn start(&self, plan: SeatPlan, tools: ToolEndpoint) -> StartFuture { + let program = self.program.clone(); + let options = self.options; + let seats = self.seats.clone(); + Box::pin(async move { + let model = capability::check(&plan.seat).map_err(|refusal| Error::Refused(Box::new(refusal)))?; + let id = plan.seat.id.clone(); + if lock(&seats).contains_key(&id) { + return Err(Error::Harness(format!("seat {id} is already running"))); + } + let timeout = plan.turn_timeout(); + let seat = Arc::new(Seat::new(program, options, plan, tools, model)); + seat.start().await?; + lock(&seats).insert(id, seat.clone()); + let runner = SeatRunner::new(Arc::new(Runner(seat))).with_timeout(timeout); + Ok(Arc::new(runner) as Arc) + }) + } + + fn stop(&self, seat_id: &str) -> StopFuture { + let seat = lock(&self.seats).remove(seat_id); + Box::pin(async move { + match seat { + Some(seat) => Ok(seat.stop().await?), + None => Ok(()), + } + }) + } +} From f7ca461c51b01ec01daf121d4ae87b4236a19eb5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:49:00 +0000 Subject: [PATCH 26/49] feat(harness): add seat module for openhuman process Introduce a seat abstraction in the harness so openhuman processes can be assigned and tracked per seat. This lays the groundwork for managing process placement within the harness. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/harness/seat.rs | 190 ++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/src/harness/seat.rs diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs new file mode 100644 index 00000000..ff79d7ce --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -0,0 +1,190 @@ +//! One seat: its instance, its thread, and the turn it may be running. +use super::{Options, Program}; +use crate::capability::SeatModel; +use crate::error::{Error, Result}; +use crate::instance::{Launcher, Live}; +use crate::turn::{self, Active, Turn}; +use serde_json::json; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use tinyhivemind_hives::{AgentRunner, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest}; +use tinyhivemind_host::harness::{self, CancelFuture, CancellableRunner, Event, SeatPlan, ToolEndpoint}; +use tokio::sync::{Mutex as AsyncMutex, watch}; + +/// A seat and its instance, if one is running. +#[derive(Debug)] +pub(super) struct Seat { + program: Program, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + model: SeatModel, + live: AsyncMutex>>, + active: Mutex>, + closed: watch::Sender, + turns: AtomicU64, +} + +fn take(active: &Mutex>) -> Option { + active.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +fn clear(active: &Mutex>) { + *active.lock().unwrap_or_else(PoisonError::into_inner) = None; +} + +impl Seat { + pub(super) fn new( + program: Program, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + model: SeatModel, + ) -> Self { + Self { + program, + options, + plan, + tools, + model, + live: AsyncMutex::new(None), + active: Mutex::new(None), + closed: watch::channel(false).0, + turns: AtomicU64::new(0), + } + } + + /// The thread a seat's first turn starts, and keeps for its life. + fn thread(&self) -> String { + format!("thm-{}", self.plan.seat.id) + } + + /// Start an instance if none is running, reporting it. + pub(super) async fn start(&self) -> Result> { + let mut live = self.live.lock().await; + if let Some(running) = live.as_ref().filter(|live| live.instance.exit().is_none()) { + return Ok(running.clone()); + } + if let Some(dead) = live.take() { + dead.instance.stop(async {}, self.options.stop).await?; + } + let launcher = Launcher { + program: &self.program, + options: &self.options, + plan: &self.plan, + tools: &self.tools, + model: &self.model, + }; + let started = Arc::new(launcher.launch().await?); + let event = Event::Started(started.started.clone()); + self.plan.observer.event(&self.plan.seat.id, event); + *live = Some(started.clone()); + Ok(started) + } + + async fn run(&self, request: TurnRequest) -> Result { + if *self.closed.borrow() { + return Err(turn::Error::Closed.into()); + } + let live = self.start().await?; + let thread = request.session_id.clone().unwrap_or_else(|| self.thread()); + if let Some(session) = &request.session_id { + let found = live + .client + .call("openhuman.threads_transcript_get", json!({"thread_id": session})) + .await?; + if found["data"]["hasTranscript"] != true { + return Err(Error::Resume(session.clone())); + } + } + let message = tinyhivemind_host::turn::render(&request) + .map_err(|error| Error::Render(error.to_string()))?; + let number = self.turns.fetch_add(1, Ordering::Relaxed); + let turn = Turn { + client: &live.client, + seat: &self.plan.seat.id, + thread: &thread, + turn_id: &request.turn_id, + client_id: format!("thm-turn-{number}"), + iterations: self.model.iterations, + observer: self.plan.observer.as_ref(), + approver: self.plan.approver.as_ref(), + closed: self.closed.subscribe(), + }; + let ended = turn::run(turn, &message, &self.active).await?; + if let Some(usage) = ended.usage { + let event = Event::Usage { + turn_id: request.turn_id.clone(), + usage, + }; + self.plan.observer.event(&self.plan.seat.id, event); + } + let disposition = ended + .failure + .map_or(TurnDisposition::Completed, TurnDisposition::Failed); + Ok(TurnOutcome { + session_id: thread, + reply: ended.reply, + disposition, + }) + } + + /// Cancel the submitted turn and show it stopped, or kill the instance. + async fn cancel(&self) -> Result<()> { + let Some(active) = take(&self.active) else { + return Ok(()); + }; + let mut live = self.live.lock().await; + let Some(running) = live.clone() else { + // Stopped since, so the turn is over. + clear(&self.active); + return Ok(()); + }; + let alive = running.instance.exit().is_none(); + if alive && turn::cancel(&running.client, &active).await.is_ok() { + clear(&self.active); + return Ok(()); + } + // Dead, or it could not show the turn stopped: then nothing of it may + // run on. + running.instance.stop(async {}, self.options.stop).await?; + *live = None; + clear(&self.active); + Ok(()) + } + + /// Cancel, close the turn's events, then stop the instance and prove it. + pub(super) async fn stop(&self) -> Result<()> { + self.closed.send_replace(true); + let Some(live) = self.live.lock().await.take() else { + return Ok(()); + }; + let active = take(&self.active); + let cancel = async { + if let Some(active) = &active { + // Best effort: the stop that follows ends the turn anyway. + let _ = turn::cancel(&live.client, active).await; + } + }; + live.instance.stop(cancel, self.options.stop).await?; + clear(&self.active); + Ok(()) + } +} + +/// The seat as the seat runner sees it. +pub(super) struct Runner(pub(super) Arc); + +impl AgentRunner for Runner { + fn run(&self, request: TurnRequest) -> TurnFuture { + let seat = self.0.clone(); + Box::pin(async move { Ok(seat.run(request).await.map_err(harness::Error::from)?) }) + } +} + +impl CancellableRunner for Runner { + fn cancel(&self, _: &str) -> CancelFuture { + let seat = self.0.clone(); + Box::pin(async move { Ok(seat.cancel().await?) }) + } +} From 969d5a34371ee2042361b22840d975c45aea546c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:49:46 +0000 Subject: [PATCH 27/49] feat(openhuman): add resume and render errors and document the harness Adds Resume and Render error variants so a missing thread and an unrenderable turn surface as distinct failures, and expands the crate docs to describe how a seat is started, verified, and driven. Also renames the seat's active-turn helper to current and marks the fixture root as intentionally held. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/error.rs | 10 +++ .../src/fixture.rs | 4 +- .../src/harness/seat.rs | 6 +- .../tinyhivemind-openhuman-process/src/lib.rs | 44 ++++++++++ .../tests/fake/child.rs | 84 ++++++++++++++++++- 5 files changed, 142 insertions(+), 6 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/error.rs b/crates/tinyhivemind-openhuman-process/src/error.rs index 80994c89..c22d148f 100644 --- a/crates/tinyhivemind-openhuman-process/src/error.rs +++ b/crates/tinyhivemind-openhuman-process/src/error.rs @@ -33,6 +33,12 @@ pub(crate) enum Error { /// Its tools, by the names it serves them under. missing: Vec, }, + /// The seat's session is gone from the instance; no new one is started. + #[error("the instance has no thread {0}")] + Resume(String), + /// The turn's request could not be rendered as its message. + #[error("the turn could not be rendered: {0}")] + Render(String), /// A file of the instance could not be written or read. #[error("{what}: {source}")] Io { @@ -56,6 +62,10 @@ impl From for harness::Error { Error::Refused(refusal) => Self::Refused(Box::new(refusal)), Error::Process(error) => Self::Process(error), Error::Mismatch(mismatch) => Self::Mismatch(mismatch), + Error::Resume(session_id) => Self::Resume { + reason: format!("the instance has no thread {session_id}"), + session_id, + }, other => Self::Harness(other.to_string()), } } diff --git a/crates/tinyhivemind-openhuman-process/src/fixture.rs b/crates/tinyhivemind-openhuman-process/src/fixture.rs index cd18834e..7d2ff2fa 100644 --- a/crates/tinyhivemind-openhuman-process/src/fixture.rs +++ b/crates/tinyhivemind-openhuman-process/src/fixture.rs @@ -14,7 +14,7 @@ pub(crate) const SERVER: &str = "hivemind"; /// A fake instance with a written config. pub(crate) struct Fixture { - pub(crate) root: tempfile::TempDir, + pub(crate) _root: tempfile::TempDir, pub(crate) control: PathBuf, pub(crate) written: Written, pub(crate) client: Client, @@ -74,7 +74,7 @@ impl Fixture { let client = Client::new(fake.port, TOKEN); let client = client.unwrap_or_else(|error| unreachable!("a client: {error}")); Self { - root, + _root: root, control, written, client, diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs index ff79d7ce..05953b14 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -25,7 +25,7 @@ pub(super) struct Seat { turns: AtomicU64, } -fn take(active: &Mutex>) -> Option { +fn current(active: &Mutex>) -> Option { active.lock().unwrap_or_else(PoisonError::into_inner).clone() } @@ -131,7 +131,7 @@ impl Seat { /// Cancel the submitted turn and show it stopped, or kill the instance. async fn cancel(&self) -> Result<()> { - let Some(active) = take(&self.active) else { + let Some(active) = current(&self.active) else { return Ok(()); }; let mut live = self.live.lock().await; @@ -159,7 +159,7 @@ impl Seat { let Some(live) = self.live.lock().await.take() else { return Ok(()); }; - let active = take(&self.active); + let active = current(&self.active); let cancel = async { if let Some(active) = &active { // Best effort: the stop that follows ends the turn anyway. diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs index 80dcc57d..feba8f53 100644 --- a/crates/tinyhivemind-openhuman-process/src/lib.rs +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -1,11 +1,55 @@ //! Hive seats on OpenHuman, each a supervised `openhuman-core` process. +//! +//! [`OpenHumanHarness`] implements the host's +//! [`Harness`](tinyhivemind_host::harness::Harness) port for the `openhuman` +//! kind. Each seat gets one `openhuman-core run --headless-api` in its own +//! private directory, with a generated `config.toml`, and is driven over its +//! loopback JSON-RPC and `/events` stream: a turn is `channel_web_chat` on +//! the seat's one thread, followed by its events until `chat_done` or +//! `chat_error`, and cancelled with `channel_web_cancel`. +//! +//! Before a seat starts, [`capability::check`] holds it to the `openhuman` +//! column of the capability table in `docs/specs/harnesses.md`: only an +//! `openai` provider with an explicit endpoint and no credential, no more +//! than [`capability::ITERATION_CAP`] iterations, no sandbox, no built-in +//! tools. A start is verified: the process answering is the child, its +//! version is the pin, its effective config is the one written, and its +//! model sees exactly the host's tools. +//! +//! ```no_run +//! use std::sync::Arc; +//! use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +//! use tinyhivemind_openhuman_process::{OpenHumanHarness, Program}; +//! +//! # async fn start(seat: tinyhivemind_lang::LoweredSeat) -> Result<(), Box> { +//! let harness = OpenHumanHarness::new(Program::new("/opt/oh/openhuman-core", "0.64.15")); +//! let tools = ToolEndpoint::new( +//! "hivemind", +//! "http://127.0.0.1:7000/mcp", +//! "seat-bearer", +//! ["hivemind_post".to_owned()], +//! ); +//! let runner = harness.start(SeatPlan::new(seat, "/var/lib/hive/scout"), tools).await?; +//! // Register `runner` with the coordinator; stop the seat with: +//! harness.stop("scout").await?; +//! # drop(runner); Ok(()) } +//! ``` +//! +//! What this crate does not hold: it names no OpenHuman type and links no +//! harness, so it outlives the linked adapter; it serves no tools (the host's +//! MCP server does, and judges their policy); and it never downloads a +//! binary: `.github/scripts/fetch-harness.sh` fetches the one pinned in +//! `harnesses.lock`, and the host passes its path. pub mod capability; mod config; mod error; +mod harness; mod instance; mod rpc; mod turn; +pub use harness::{OpenHumanHarness, Options, Program}; + #[cfg(test)] #[path = "../tests/support/http.rs"] mod http; diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs index f328e4d9..6038b726 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs @@ -1 +1,83 @@ -fn main() {} +//! The scripted fake `openhuman-core`: `run --headless-api --host 127.0.0.1 +//! --port ` serves the fake surface from `surface.rs` on that port, with +//! the token and workspace from the environment the runner gives the real +//! one. `CONTROL` names the control directory; a test's wrapper script sets +//! it. Asked through `/escape`, it leaves a grandchild in a session +//! of its own, which reports its pid to `/escapee`. +#[path = "../support/http.rs"] +mod http; +#[path = "surface.rs"] +mod surface; + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::Duration; + +fn main() -> ExitCode { + let arguments: Vec = std::env::args().skip(1).collect(); + if let [mode, report] = arguments.as_slice() + && mode == "escapee" + { + return escapee(Path::new(report)); + } + // The real binary is never run with its sandbox off, so neither is this. + if std::env::var_os("OPENHUMAN_SANDBOX").is_some() { + return ExitCode::from(3); + } + let port = arguments + .windows(2) + .find(|pair| pair[0] == "--port") + .and_then(|pair| pair[1].parse::().ok()); + let variable = |name: &str| std::env::var_os(name).map(PathBuf::from); + let (Some(port), Some(workspace), Some(control), Ok(token)) = ( + port, + variable("OPENHUMAN_WORKSPACE"), + variable("CONTROL"), + std::env::var("OPENHUMAN_CORE_TOKEN"), + ) else { + return ExitCode::from(2); + }; + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build(); + let Ok(runtime) = runtime else { + return ExitCode::FAILURE; + }; + runtime.block_on(async move { + let Ok(listener) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await else { + return ExitCode::FAILURE; + }; + let setup = surface::Setup { + token, + workspace, + control: control.clone(), + pid: std::process::id(), + }; + let _fake = surface::Fake::on(listener, setup, port); + loop { + let request = control.join("escape"); + if std::fs::remove_file(&request).is_ok() + && let Ok(program) = std::env::current_exe() + { + let _ = std::process::Command::new(program) + .arg("escapee") + .arg(control.join("escapee")) + .spawn(); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) +} + +/// Leave the process group, report, and stay two minutes at most. +fn escapee(report: &Path) -> ExitCode { + if rustix::process::setsid().is_err() { + return ExitCode::FAILURE; + } + let partial = report.with_extension("partial"); + let written = std::fs::write(&partial, std::process::id().to_string()) + .and_then(|()| std::fs::rename(&partial, report)); + if written.is_err() { + return ExitCode::FAILURE; + } + std::thread::sleep(Duration::from_secs(120)); + ExitCode::SUCCESS +} From 870a0731cbaac28142dde8b6c381e93a7e9812e4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:51:04 +0000 Subject: [PATCH 28/49] test(openhuman-process): add conformance suite over a fake core child The conformance placeholder is replaced by a suite that runs every host case against a fake openhuman-core child, so supervision is exercised for real, plus checks that seat refusals happen before anything starts and that start and stop are idempotent. The fake child's shared surface module is marked dead-code-allowed for the binary, and the live test file keeps its placeholder note. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/conformance.rs | 83 +++++- .../tests/fake/child.rs | 2 + .../tests/fake/subject.rs | 249 ++++++++++++++++++ .../tests/live.rs | 2 +- .../tests/live/model.rs | 123 +++++++++ 5 files changed, 457 insertions(+), 2 deletions(-) create mode 100644 crates/tinyhivemind-openhuman-process/tests/fake/subject.rs create mode 100644 crates/tinyhivemind-openhuman-process/tests/live/model.rs diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index 4360cd35..cc854d68 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -1 +1,82 @@ -//! Placeholder until its slice. +//! The host's conformance suite over this runner and a fake `openhuman-core` +//! child, so that supervision is real; and the seat refusals through the +//! port. Linux only, as the suite escapes a process group on purpose. +#![cfg(target_os = "linux")] + +#[path = "fake/subject.rs"] +mod subject; + +use anyhow::Result; +use subject::FakeSubject; +use tinyhivemind_host::harness::conformance::{Case, Subject as _}; +use tinyhivemind_host::harness::{Error, HarnessKind, SeatPlan}; +use tinyhivemind_openhuman_process::capability::Refusal; + +/// One test per case, and a check that no case is left out. +macro_rules! passes { + ($($name:ident => $case:ident),* $(,)?) => { + $( + #[tokio::test(flavor = "multi_thread")] + async fn $name() -> Result<()> { + Case::$case.run(&FakeSubject::new()?).await?; + Ok(()) + } + )* + #[test] + fn every_case_is_run() { + assert_eq!(Case::ALL, [$(Case::$case),*]); + } + }; +} + +passes! { + a_second_turn_continues_the_session => SecondTurnContinues, + a_session_is_resumed_after_a_restart => ResumesAfterRestart, + a_resume_failure_is_an_error => ResumeFailureIsAnError, + a_timeout_stops_the_turn => TimeoutStopsTheTurn, + a_dropped_run_stops_the_turn => DropStopsTheTurn, + a_kill_neither_replays_nor_loses_the_seat => KillNeitherReplaysNorLosesTheSeat, + one_turn_runs_at_a_time => OneTurnAtATime, + no_turn_runs_twice => NoTurnTwice, + usage_is_per_turn => UsageIsPerTurn, + the_tool_list_is_exact => ToolListIsExact, + the_config_is_the_one_written => ConfigIsTheOneWritten, + nothing_is_left_after_stop => NothingLeftAfterStop, +} + +#[tokio::test] +async fn the_harness_is_the_openhuman_kind() -> Result<()> { + let subject = FakeSubject::new()?; + assert_eq!(subject.harness().kind(), HarnessKind::OpenHuman); + Ok(()) +} + +#[tokio::test] +async fn a_seat_it_cannot_honour_is_refused_before_anything_starts() -> Result<()> { + let subject = FakeSubject::new()?; + let mut seat = subject::seat("http://127.0.0.1:9/v1"); + seat.integration.limits.iterations = Some(20); + let plan = SeatPlan::new(seat, subject.root_path().join("instance")); + let refused = subject.harness().start(plan, subject.endpoint()).await; + let Err(Error::Refused(refusal)) = refused else { + anyhow::bail!("not refused: {:?}", refused.err()); + }; + let refusal = refusal.downcast_ref::(); + assert_eq!(refusal, Some(&Refusal::Iterations { asked: 20, cap: 8 })); + assert!(subject.processes().is_empty()); + Ok(()) +} + +#[tokio::test] +async fn a_running_seat_is_not_started_twice_and_a_stopped_one_is_already_stopped() -> Result<()> { + let subject = FakeSubject::new()?; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + let again = harness.start(subject.seat(), subject.endpoint()).await; + assert!(matches!(again, Err(Error::Harness(reason)) if reason.contains("already running"))); + harness.stop("scout").await?; + harness.stop("scout").await?; + assert!(subject.processes().is_empty()); + drop(runner); + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs index 6038b726..9b1df9c7 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs @@ -6,6 +6,8 @@ //! of its own, which reports its pid to `/escapee`. #[path = "../support/http.rs"] mod http; +// The in-process unit tests use the parts of the fake this binary does not. +#[allow(dead_code, reason = "shared with the in-process tests")] #[path = "surface.rs"] mod surface; diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs new file mode 100644 index 00000000..f13180a3 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -0,0 +1,249 @@ +//! The fake `openhuman-core` as a subject of the host's conformance suite. +//! +//! The runner launches a wrapper script that sets `CONTROL` and execs the +//! fake child, so the runner itself is exactly the one a host uses. +use rustix::process::{Pid, Signal, kill_process}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::fmt::Debug; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; +use tinyhivemind_host::harness::conformance::{ + CallState, EscapeFuture, ModelCall, ModelStep, Subject, ToolFault, +}; +use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +use tinyhivemind_host::process::StopPolicy; +use tinyhivemind_lang::{ + LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, ProviderKind, +}; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; + +/// The result of something the test itself does, which has to work. +pub(crate) fn done(result: &Result) { + assert!(result.is_ok(), "{result:?}"); +} + +/// A seat on an `openai` endpoint at `endpoint`. +pub(crate) fn seat(endpoint: &str) -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind: ProviderKind::Openai, + endpoint: Some(endpoint.into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: Value::Null, + prompt: "You scout.".into(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +/// Whatever runs in `instance`. +pub(crate) fn processes_in(instance: &Path) -> Vec { + fs::read_dir("/proc") + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| entry.file_name().to_str()?.parse().ok()) + .filter(|pid: &u32| { + fs::read_link(format!("/proc/{pid}/cwd")).is_ok_and(|cwd| cwd.starts_with(instance)) + }) + .collect() +} + +/// Kill what a faulty run left behind. +pub(crate) fn kill_all(pids: Vec) { + for pid in pids { + if let Some(pid) = Pid::from_raw(pid.cast_signed()) { + let _ = kill_process(pid, Signal::KILL); + } + } +} + +/// Fresh durable state and the scripted fake. +pub(crate) struct FakeSubject { + root: tempfile::TempDir, + steps: AtomicUsize, +} + +pub(crate) const TOOLS: [&str; 2] = ["hivemind_post", "hivemind_ask"]; + +impl FakeSubject { + pub(crate) fn new() -> std::io::Result { + let root = tempfile::tempdir()?; + let control = root.path().join("control"); + fs::create_dir_all(control.join("steps"))?; + fs::write(control.join("served"), json!(TOOLS).to_string())?; + let program = env!("CARGO_BIN_EXE_tinyhivemind-fake-openhuman"); + let wrapper = root.path().join("openhuman-core"); + let script = format!( + "#!/bin/sh\nCONTROL='{}' exec '{program}' \"$@\"\n", + control.display() + ); + fs::write(&wrapper, script)?; + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755))?; + Ok(Self { + root, + steps: AtomicUsize::new(0), + }) + } + + pub(crate) fn control(&self) -> PathBuf { + self.root.path().join("control") + } + + pub(crate) fn root_path(&self) -> &Path { + self.root.path() + } + + fn instance(&self) -> PathBuf { + self.root.path().join("instance") + } + + fn entries(&self) -> Vec { + fs::read_to_string(self.control().join("calls.jsonl")) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } + + pub(crate) fn options() -> Options { + Options { + ready: Duration::from_secs(20), + warm_up: Duration::from_secs(3), + stop: StopPolicy { + cancel: Duration::from_secs(2), + terminate: Duration::from_secs(2), + kill: Duration::from_secs(10), + }, + } + } +} + +impl Subject for FakeSubject { + fn harness(&self) -> Arc { + let program = Program::new(self.root.path().join("openhuman-core"), "0.64.15"); + Arc::new(OpenHumanHarness::new(program).with_options(Self::options())) + } + + fn seat(&self) -> SeatPlan { + SeatPlan::new(seat("http://127.0.0.1:9/v1"), self.instance()) + } + + fn endpoint(&self) -> ToolEndpoint { + let tools = TOOLS.map(String::from); + ToolEndpoint::new("hivemind", "http://127.0.0.1:1/mcp", "seat-bearer", tools) + } + + fn script(&self, steps: &[ModelStep]) { + let directory = self.control().join("steps"); + for old in fs::read_dir(&directory).into_iter().flatten().flatten() { + let _ = fs::remove_file(old.path()); + } + for step in steps { + let number = self.steps.fetch_add(1, Ordering::Relaxed); + let step = match step { + ModelStep::Reply { text, usage } => { + json!({"reply": text, "tokens": usage.input_tokens}) + } + ModelStep::Hang => Value::Null, + }; + let path = directory.join(format!("{number:06}")); + done(&fs::write(path, step.to_string())); + } + } + + fn model_calls(&self) -> Vec { + let mut calls = BTreeMap::new(); + for entry in self.entries() { + let state = match entry["state"].as_str() { + Some("answered") => CallState::Answered, + Some("aborted") => CallState::Aborted, + // A model call ends with the process that makes it. + _ if !Path::new(&format!("/proc/{}/cwd", entry["pid"])).exists() => { + CallState::Aborted + } + _ => CallState::Open, + }; + let seen = entry["seen"].as_u64().unwrap_or_default(); + let call = calls.entry(entry["call"].as_u64()).or_insert(ModelCall { + seen: usize::try_from(seen).unwrap_or(usize::MAX), + state, + }); + call.state = state; + } + calls.into_values().collect() + } + + fn lose_sessions(&self) { + let transcripts = self.instance().join("state/ws/workspace/session_raw"); + done(&fs::remove_dir_all(transcripts)); + } + + fn offer(&self, fault: ToolFault) { + let text = match fault { + ToolFault::None => "", + ToolFault::Extra => "extra", + ToolFault::Missing => "missing", + }; + done(&fs::write(self.control().join("tools"), text)); + } + + fn misconfigure(&self) { + done(&fs::write(self.control().join("misconfigured"), "")); + } + + fn escapee(&self) -> EscapeFuture { + let control = self.control(); + Box::pin(async move { + let report = control.join("escapee"); + let _ = fs::remove_file(&report); + done(&fs::write(control.join("escape"), "")); + loop { + if let Ok(pid) = fs::read_to_string(&report) { + return pid.parse().ok(); + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + } + + fn processes(&self) -> Vec { + processes_in(&self.instance()) + } + + fn turn_limit(&self) -> Duration { + Duration::from_secs(5) + } + + fn patience(&self) -> Duration { + Duration::from_secs(60) + } +} + +impl Drop for FakeSubject { + fn drop(&mut self) { + kill_all(self.processes()); + } +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs index 4360cd35..5da52741 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -1 +1 @@ -//! Placeholder until its slice. +//! Live tests, written in slice 6. diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs new file mode 100644 index 00000000..0646698f --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -0,0 +1,123 @@ +//! A scripted Chat Completions model on loopback, played by the host's +//! conformance steps: each request takes the next step, and a hanging one +//! notices when the caller hangs up. +#[path = "../support/http.rs"] +mod http; + +use http::{Reply, Request, serve}; +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tinyhivemind_host::harness::conformance::{CallState, ModelCall, ModelStep}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[derive(Default)] +struct State { + steps: Mutex>, + calls: Mutex>, +} + +/// The model, serving until dropped. +pub(crate) struct ScriptedModel { + pub(crate) port: u16, + state: Arc, + task: tokio::task::JoinHandle<()>, +} + +impl ScriptedModel { + pub(crate) async fn start() -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let state = Arc::new(State::default()); + let serving = state.clone(); + let task = tokio::spawn(serve(listener, move |request| { + let state = serving.clone(); + async move { answer(&state, &request) } + })); + Ok(Self { port, state, task }) + } + + pub(crate) fn script(&self, steps: &[ModelStep]) { + *lock(&self.state.steps) = steps.iter().cloned().collect(); + } + + pub(crate) fn calls(&self) -> Vec { + lock(&self.state.calls).clone() + } +} + +impl Drop for ScriptedModel { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn answer(state: &Arc, request: &Request) -> Reply { + if request.method == "GET" && request.path.ends_with("/models") { + return Reply::Json(200, json!({"object": "list", "data": [{"id": "mock", "object": "model"}]})); + } + if !request.path.ends_with("/chat/completions") { + return Reply::Json(404, json!({})); + } + let body = request.json(); + let messages = body["messages"].as_array().cloned().unwrap_or_default(); + let seen = messages.iter().filter(|message| message["role"] == "user").count(); + let index = { + let mut calls = lock(&state.calls); + calls.push(ModelCall { seen, state: CallState::Open }); + calls.len() - 1 + }; + let step = lock(&state.steps).pop_front().unwrap_or(ModelStep::Hang); + let (sender, receiver) = mpsc::channel(16); + let state = state.clone(); + let stream = body["stream"] == true; + match step { + ModelStep::Hang => { + tokio::spawn(async move { + sender.closed().await; + lock(&state.calls)[index].state = CallState::Aborted; + }); + Reply::Stream(receiver) + } + ModelStep::Reply { text, usage } => { + lock(&state.calls)[index].state = CallState::Answered; + let usage = json!({"prompt_tokens": usage.input_tokens, "completion_tokens": 1, + "total_tokens": usage.input_tokens + 1}); + let base = json!({"id": "c", "created": 1, "model": "mock"}); + if !stream { + let mut reply = base; + reply["object"] = json!("chat.completion"); + reply["choices"] = json!([{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": text}}]); + reply["usage"] = usage; + return Reply::Json(200, reply); + } + let chunk = |choices: Value, usage: Option| { + let mut chunk = base.clone(); + chunk["object"] = json!("chat.completion.chunk"); + chunk["choices"] = choices; + if let Some(usage) = usage { + chunk["usage"] = usage; + } + format!("data: {chunk}\n\n") + }; + let frames = [ + chunk(json!([{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]), None), + chunk(json!([{"index": 0, "delta": {}, "finish_reason": "stop"}]), None), + chunk(json!([]), Some(usage)), + "data: [DONE]\n\n".to_owned(), + ]; + tokio::spawn(async move { + for frame in frames { + let _ = sender.send(frame).await; + } + }); + Reply::Stream(receiver) + } + } +} From 39492b7a8f8be3f29c4f167d6a7f2cb5a554d44e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:51:32 +0000 Subject: [PATCH 29/49] test(live): allow dead code in shared http test helper The shared http module is now also used by the fake surface, so the dead_code lint is silenced to keep the live model tests compiling without warnings. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/live/model.rs | 1 + .../tests/live/subject.rs | 201 ++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/tests/live/subject.rs diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs index 0646698f..d73602c5 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/model.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -1,6 +1,7 @@ //! A scripted Chat Completions model on loopback, played by the host's //! conformance steps: each request takes the next step, and a hanging one //! notices when the caller hangs up. +#[allow(dead_code, reason = "shared with the fake surface")] #[path = "../support/http.rs"] mod http; diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs new file mode 100644 index 00000000..681e3463 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -0,0 +1,201 @@ +//! The pinned `openhuman-core` as a subject of the conformance suite: the +//! scripted model in `model.rs`, and the spike fixture's MCP stub, run by +//! Node, for the host's tools. +use super::model::ScriptedModel; +use super::subject_support::{kill_all, processes_in, seat}; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::Duration; +use tinyhivemind_host::harness::conformance::{EscapeFuture, ModelCall, ModelStep, Subject, ToolFault}; +use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +use tinyhivemind_host::process::StopPolicy; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; +use tokio::io::{AsyncBufReadExt as _, BufReader}; +use tokio::process::{Child, Command}; + +/// The pinned version, as `harnesses.lock` records it. +pub(crate) const PINNED: &str = "0.64.15"; + +/// What a live test needs, or why it cannot run here. +pub(crate) fn requirements() -> Result<(PathBuf, PathBuf), String> { + let binary = std::env::var_os("THM_OPENHUMAN_CORE") + .map(PathBuf::from) + .ok_or("THM_OPENHUMAN_CORE is not set to the pinned openhuman-core")?; + let node = std::env::var_os("THM_NODE").map(PathBuf::from).or_else(|| { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path).map(|dir| dir.join("node")).find(|node| node.is_file()) + }); + let node = node.ok_or("node is neither THM_NODE nor on PATH, and the fixture needs it")?; + Ok((binary, node)) +} + +/// The spike's fixture: a model that ignores its key and an MCP stub that +/// maps `seat-a-token` to seat `a`. +pub(crate) struct Fixture { + pub(crate) port: u16, + pub(crate) log: PathBuf, + _child: Child, +} + +impl Fixture { + pub(crate) async fn start(node: &Path, dir: &Path) -> std::io::Result { + let port = std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let script = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/experiments/2026-11-25-process-harnesses/fixture/server.mjs"); + let log = dir.join("fixture.jsonl"); + let mut child = Command::new(node) + .arg(script) + .arg(port.to_string()) + .arg(&log) + .stdout(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn()?; + let stdout = child.stdout.take().ok_or(std::io::ErrorKind::BrokenPipe)?; + let mut lines = BufReader::new(stdout).lines(); + while let Some(line) = lines.next_line().await? { + if line.trim() == "ready" { + return Ok(Self { port, log, _child: child }); + } + } + Err(std::io::ErrorKind::UnexpectedEof.into()) + } + + pub(crate) fn entries(&self) -> Vec { + fs::read_to_string(&self.log) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } +} + +/// Generous: the real binary takes up to a second to start. +pub(crate) fn options() -> Options { + Options { + ready: Duration::from_secs(30), + warm_up: Duration::from_secs(20), + stop: StopPolicy::default(), + } +} + +pub(crate) struct LiveSubject { + root: tempfile::TempDir, + model: ScriptedModel, + fixture: Fixture, + fault: AtomicU8, +} + +impl LiveSubject { + pub(crate) async fn new() -> anyhow::Result> { + let (binary, node) = match requirements() { + Ok(found) => found, + Err(reason) => { + eprintln!("skipped: {reason}"); + return Ok(None); + } + }; + let root = tempfile::tempdir()?; + let fixture = Fixture::start(&node, root.path()).await?; + // Corrupts the written config on request, so that the binary falls + // back to its defaults as it does on bad TOML. + let script = format!( + "#!/bin/sh\n[ -e '{}/misconfigured' ] && printf '\\n[[[\\n' >> \"$OPENHUMAN_WORKSPACE/config.toml\"\nexec '{}' \"$@\"\n", + root.path().display(), + binary.display() + ); + let wrapper = root.path().join("openhuman-core"); + fs::write(&wrapper, script)?; + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755))?; + Ok(Some(Self { + model: ScriptedModel::start().await?, + root, + fixture, + fault: AtomicU8::new(0), + })) + } + + fn instance(&self) -> PathBuf { + self.root.path().join("instance") + } +} + +impl Subject for LiveSubject { + fn harness(&self) -> Arc { + let program = Program::new(self.root.path().join("openhuman-core"), PINNED); + Arc::new(OpenHumanHarness::new(program).with_options(options())) + } + + fn seat(&self) -> SeatPlan { + let endpoint = format!("http://127.0.0.1:{}/v1", self.model.port); + SeatPlan::new(seat(&endpoint), self.instance()) + } + + fn endpoint(&self) -> ToolEndpoint { + let mut tools = vec!["hivemind_post".to_owned()]; + if self.fault.load(Ordering::Relaxed) == 2 { + // The stub serves no such tool, so the instance never lists it. + tools.push("hivemind_absent".to_owned()); + } + let url = format!("http://127.0.0.1:{}/mcp", self.fixture.port); + ToolEndpoint::new("hivea", url, "seat-a-token", tools) + } + + fn script(&self, steps: &[ModelStep]) { + self.model.script(steps); + } + + fn model_calls(&self) -> Vec { + self.model.calls() + } + + fn lose_sessions(&self) { + let workspace = self.instance().join("state/ws/workspace"); + for store in ["session_raw", "sessions", "session_db", "memory/conversations"] { + let _ = fs::remove_dir_all(workspace.join(store)); + } + } + + /// The binary shows its model only what the exact allowlist names, so an + /// extra tool can only come from another config: that is what `Extra` + /// writes. `Missing` names a tool the stub does not serve. + fn offer(&self, fault: ToolFault) { + let (code, misconfigured) = match fault { + ToolFault::None => (0, false), + ToolFault::Extra => (1, true), + ToolFault::Missing => (2, false), + }; + self.fault.store(code, Ordering::Relaxed); + let marker = self.root.path().join("misconfigured"); + let _ = if misconfigured { fs::write(marker, "") } else { fs::remove_file(marker) }; + } + + fn misconfigure(&self) { + let _ = fs::write(self.root.path().join("misconfigured"), ""); + } + + /// Built-in tools are off, so nothing can make this instance spawn. + fn escapee(&self) -> EscapeFuture { + Box::pin(async { None }) + } + + fn processes(&self) -> Vec { + processes_in(&self.instance()) + } + + fn turn_limit(&self) -> Duration { + Duration::from_secs(20) + } + + fn patience(&self) -> Duration { + Duration::from_secs(90) + } +} + +impl Drop for LiveSubject { + fn drop(&mut self) { + kill_all(self.processes()); + } +} From 4b7eb00fe92088a8d127a77875477a4c22c411e8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:51:46 +0000 Subject: [PATCH 30/49] test: share seat and process helpers across conformance suites Move the seat builder and process helpers out of the fake subject into a shared support module so both the fake and live suites can use them. The live subject now imports the scripted model and seat helpers through crate paths instead of its own module tree. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/conformance.rs | 4 +- .../tests/fake/subject.rs | 64 +---------------- .../tests/live/subject.rs | 4 +- .../tests/support/seat.rs | 69 +++++++++++++++++++ 4 files changed, 75 insertions(+), 66 deletions(-) create mode 100644 crates/tinyhivemind-openhuman-process/tests/support/seat.rs diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index cc854d68..dbac896b 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -3,6 +3,8 @@ //! port. Linux only, as the suite escapes a process group on purpose. #![cfg(target_os = "linux")] +#[path = "support/seat.rs"] +mod seat_support; #[path = "fake/subject.rs"] mod subject; @@ -54,7 +56,7 @@ async fn the_harness_is_the_openhuman_kind() -> Result<()> { #[tokio::test] async fn a_seat_it_cannot_honour_is_refused_before_anything_starts() -> Result<()> { let subject = FakeSubject::new()?; - let mut seat = subject::seat("http://127.0.0.1:9/v1"); + let mut seat = seat_support::seat("http://127.0.0.1:9/v1"); seat.integration.limits.iterations = Some(20); let plan = SeatPlan::new(seat, subject.root_path().join("instance")); let refused = subject.harness().start(plan, subject.endpoint()).await; diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs index f13180a3..8fa7fc40 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -2,10 +2,9 @@ //! //! The runner launches a wrapper script that sets `CONTROL` and execs the //! fake child, so the runner itself is exactly the one a host uses. -use rustix::process::{Pid, Signal, kill_process}; +use crate::seat_support::{done, kill_all, processes_in, seat}; use serde_json::{Value, json}; use std::collections::BTreeMap; -use std::fmt::Debug; use std::fs; use std::os::unix::fs::PermissionsExt as _; use std::path::{Path, PathBuf}; @@ -17,69 +16,8 @@ use tinyhivemind_host::harness::conformance::{ }; use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; use tinyhivemind_host::process::StopPolicy; -use tinyhivemind_lang::{ - LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, ProviderKind, -}; use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; -/// The result of something the test itself does, which has to work. -pub(crate) fn done(result: &Result) { - assert!(result.is_ok(), "{result:?}"); -} - -/// A seat on an `openai` endpoint at `endpoint`. -pub(crate) fn seat(endpoint: &str) -> LoweredSeat { - let provider = Provider { - id: "local".into(), - kind: ProviderKind::Openai, - endpoint: Some(endpoint.into()), - credential: None, - }; - let model = Model { - id: "fast".into(), - provider: Some("local".into()), - name: "mock".into(), - ..Model::default() - }; - LoweredSeat { - id: "scout".into(), - label: "Scout".into(), - template: "seat".into(), - config: Value::Null, - prompt: "You scout.".into(), - memory: None, - integration: LoweredSeatIntegration { - model: Some(LoweredModel { - model, - provider: Some(provider), - }), - ..LoweredSeatIntegration::default() - }, - } -} - -/// Whatever runs in `instance`. -pub(crate) fn processes_in(instance: &Path) -> Vec { - fs::read_dir("/proc") - .into_iter() - .flatten() - .flatten() - .filter_map(|entry| entry.file_name().to_str()?.parse().ok()) - .filter(|pid: &u32| { - fs::read_link(format!("/proc/{pid}/cwd")).is_ok_and(|cwd| cwd.starts_with(instance)) - }) - .collect() -} - -/// Kill what a faulty run left behind. -pub(crate) fn kill_all(pids: Vec) { - for pid in pids { - if let Some(pid) = Pid::from_raw(pid.cast_signed()) { - let _ = kill_process(pid, Signal::KILL); - } - } -} - /// Fresh durable state and the scripted fake. pub(crate) struct FakeSubject { root: tempfile::TempDir, diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs index 681e3463..4f6e112d 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -1,8 +1,8 @@ //! The pinned `openhuman-core` as a subject of the conformance suite: the //! scripted model in `model.rs`, and the spike fixture's MCP stub, run by //! Node, for the host's tools. -use super::model::ScriptedModel; -use super::subject_support::{kill_all, processes_in, seat}; +use crate::model::ScriptedModel; +use crate::seat_support::{kill_all, processes_in, seat}; use std::fs; use std::os::unix::fs::PermissionsExt as _; use std::path::{Path, PathBuf}; diff --git a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs new file mode 100644 index 00000000..8e29aed9 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs @@ -0,0 +1,69 @@ +//! What both conformance subjects share: the seat, and the processes of an +//! instance directory. +use rustix::process::{Pid, Signal, kill_process}; +use serde_json::Value; +use std::fmt::Debug; +use std::fs; +use std::path::Path; +use tinyhivemind_lang::{ + LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, ProviderKind, +}; + +/// The result of something the test itself does, which has to work. +pub(crate) fn done(result: &Result) { + assert!(result.is_ok(), "{result:?}"); +} + +/// A seat on an `openai` endpoint at `endpoint`. +pub(crate) fn seat(endpoint: &str) -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind: ProviderKind::Openai, + endpoint: Some(endpoint.into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: Value::Null, + prompt: "You scout.".into(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +/// Whatever runs in `instance`. +pub(crate) fn processes_in(instance: &Path) -> Vec { + fs::read_dir("/proc") + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| entry.file_name().to_str()?.parse().ok()) + .filter(|pid: &u32| { + fs::read_link(format!("/proc/{pid}/cwd")).is_ok_and(|cwd| cwd.starts_with(instance)) + }) + .collect() +} + +/// Kill what a faulty run left behind. +pub(crate) fn kill_all(pids: Vec) { + for pid in pids { + if let Some(pid) = Pid::from_raw(pid.cast_signed()) { + let _ = kill_process(pid, Signal::KILL); + } + } +} + From 1bec2b99ae2dfc8e66169f3d53850ee1cec9c4e3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:53:27 +0000 Subject: [PATCH 31/49] test(live): run the conformance cases against the pinned core Adds a live test runner that drives every conformance case through the real openhuman-core binary and Node fixture, gated on THM_OPENHUMAN_CORE and THM_NODE so the suite skips with a reason when either is absent. Also adds a spike gate test that repeats the original spike's checks through the runner, and fixes the subject helper's expectations to match. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/live.rs | 162 +++++++++++++++++- .../tests/live/subject.rs | 4 +- 2 files changed, 163 insertions(+), 3 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs index 5da52741..9cd5982f 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -1 +1,161 @@ -//! Live tests, written in slice 6. +//! `live_*`: this runner on the pinned `openhuman-core`. +//! +//! Opt in with `THM_OPENHUMAN_CORE=`, fetched and +//! checked by `.github/scripts/fetch-harness.sh`; Node runs the spike +//! fixture, from `THM_NODE` or `PATH`. Without either, each test says why on +//! stderr and passes. The conformance cases run with the scripted model in +//! `live/model.rs` and the fixture's MCP stub; the gate repeats the spike's +//! checks with the fixture as model too. +#![cfg(target_os = "linux")] + +#[path = "live/model.rs"] +mod model; +#[path = "support/seat.rs"] +mod seat_support; +#[path = "live/subject.rs"] +mod subject; + +use anyhow::{Context as _, Result}; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use subject::{Fixture, LiveSubject, PINNED, options, requirements}; +use tinyhivemind_hives::{Destination, Message, TurnDisposition, TurnRequest}; +use tinyhivemind_host::harness::conformance::Case; +use tinyhivemind_host::harness::{Event, Harness as _, Observer, SeatPlan, ToolEndpoint}; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Program}; + +macro_rules! live { + ($($name:ident => $case:ident),* $(,)?) => { + $( + #[tokio::test(flavor = "multi_thread")] + async fn $name() -> Result<()> { + if let Some(subject) = LiveSubject::new().await? { + Case::$case.run(&subject).await?; + } + Ok(()) + } + )* + #[test] + fn every_case_is_run_live() { + assert_eq!(Case::ALL, [$(Case::$case),*]); + } + }; +} + +live! { + live_a_second_turn_continues_the_session => SecondTurnContinues, + live_a_session_is_resumed_after_a_restart => ResumesAfterRestart, + live_a_resume_failure_is_an_error => ResumeFailureIsAnError, + live_a_timeout_stops_the_turn => TimeoutStopsTheTurn, + live_a_dropped_run_stops_the_turn => DropStopsTheTurn, + live_a_kill_neither_replays_nor_loses_the_seat => KillNeitherReplaysNorLosesTheSeat, + live_one_turn_runs_at_a_time => OneTurnAtATime, + live_no_turn_runs_twice => NoTurnTwice, + live_usage_is_per_turn => UsageIsPerTurn, + live_the_tool_list_is_exact => ToolListIsExact, + live_the_config_is_the_one_written => ConfigIsTheOneWritten, + live_nothing_is_left_after_stop => NothingLeftAfterStop, +} + +#[derive(Default)] +struct Recorder(Mutex>); + +impl Observer for Recorder { + fn event(&self, _: &str, event: Event) { + self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event); + } +} + +fn request(turn: &str, body: &str, session: Option<&str>) -> TurnRequest { + TurnRequest { + turn_id: turn.into(), + scheduled_job_id: None, + teammates: Vec::new(), + agent_id: "scout".into(), + session_id: session.map(Into::into), + messages: vec![Message { + scheduled_job_id: None, + message_id: format!("message-{turn}"), + sequence: 1, + sender: tinyhivemind_hives::HOST_ID.into(), + destination: Destination::Agent("scout".into()), + body: body.into(), + thread: None, + episode_id: None, + only_for: Vec::new(), + }], + memberships: Vec::new(), + episode: None, + resumption: None, + } +} + +/// The spike's gate through this runner: the hive tool is called as the +/// right seat, the model is offered that tool alone, usage is the turn's, +/// a dropped turn closes its model call, and nothing is left after stop. +#[tokio::test(flavor = "multi_thread")] +async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { + let (binary, node) = match requirements() { + Ok(found) => found, + Err(reason) => { + eprintln!("skipped: {reason}"); + return Ok(()); + } + }; + let root = tempfile::tempdir()?; + let fixture = Fixture::start(&node, root.path()).await?; + let harness = OpenHumanHarness::new(Program::new(binary, PINNED)).with_options(options()); + let endpoint = format!("http://127.0.0.1:{}/v1", fixture.port); + let events = Arc::new(Recorder::default()); + let mut plan = SeatPlan::new(seat_support::seat(&endpoint), root.path().join("instance")); + plan.observer = events.clone(); + let url = format!("http://127.0.0.1:{}/mcp", fixture.port); + let tools = ToolEndpoint::new("hivea", url, "seat-a-token", ["hivemind_post".to_owned()]); + let runner = harness.start(plan, tools).await?; + + let since = fixture.entries().len(); + let outcome = runner.run(request("t1", "CALLTOOL please", None)).await?; + assert_eq!(outcome.disposition, TurnDisposition::Completed); + assert_eq!(outcome.reply.as_deref(), Some("MOCK_REPLY turns=1")); + let entries: Vec = fixture.entries().split_off(since); + let calls: Vec<&Value> = entries.iter().filter(|entry| entry["rpc"] == "tools/call").collect(); + assert_eq!(calls.len(), 1, "{entries:?}"); + assert_eq!(calls[0]["seat"], "a"); + let models: Vec<&Value> = entries.iter().filter(|entry| entry["kind"] == "model").collect(); + let started = events.0.lock().unwrap_or_else(PoisonError::into_inner).iter().find_map(|event| match event { + Event::Started(started) => Some(started.clone()), + _ => None, + }); + let started = started.context("no started event")?; + assert_eq!(started.version, PINNED); + let offered: Vec = started.tools.iter().map(|tool| json!(tool)).collect(); + assert_eq!(offered.len(), 1); + for model in &models { + assert_eq!(model["tools"], json!(offered), "the model saw other tools"); + } + let usage = events.0.lock().unwrap_or_else(PoisonError::into_inner).iter().find_map(|event| match event { + Event::Usage { turn_id, usage } if turn_id == "t1" => Some(*usage), + _ => None, + }); + assert_eq!(usage.map(|usage| usage.input_tokens), Some(200)); + + let session = outcome.session_id; + let slow = tokio::spawn(runner.run(request("t2", "SLOW please", Some(&session)))); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + while !fixture.entries().iter().any(|entry| entry["key"] == "SLOW") { + anyhow::ensure!(tokio::time::Instant::now() < deadline, "the slow turn never reached the model"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + slow.abort(); + while !fixture.entries().iter().any(|entry| entry["kind"] == "model-disconnect") { + anyhow::ensure!(tokio::time::Instant::now() < deadline, "the dropped turn kept its model call open"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let again = runner.run(request("t3", "PLAIN again", Some(&session))).await?; + assert_eq!(again.reply.as_deref(), Some("MOCK_REPLY turns=3")); + + harness.stop("scout").await?; + assert!(seat_support::processes_in(&root.path().join("instance")).is_empty()); + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs index 4f6e112d..4bcedc4a 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -2,7 +2,7 @@ //! scripted model in `model.rs`, and the spike fixture's MCP stub, run by //! Node, for the host's tools. use crate::model::ScriptedModel; -use crate::seat_support::{kill_all, processes_in, seat}; +use crate::seat_support::{done, kill_all, processes_in, seat}; use std::fs; use std::os::unix::fs::PermissionsExt as _; use std::path::{Path, PathBuf}; @@ -173,7 +173,7 @@ impl Subject for LiveSubject { } fn misconfigure(&self) { - let _ = fs::write(self.root.path().join("misconfigured"), ""); + done(&fs::write(self.root.path().join("misconfigured"), "")); } /// Built-in tools are off, so nothing can make this instance spawn. From fadd2384f379c778992c2b034c64e573b874c119 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:57:03 +0000 Subject: [PATCH 32/49] fix(openhuman-process): disable tool-output compaction in the written config The written config now sets context.compaction_enabled to false, because 0.64.15 otherwise adds juice_retrieve to every allowlist. Verification accounts for that recovery tool when compaction is on, and tests cover both the config and the visible-tool behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/mod.rs | 4 +++- .../src/fixture.rs | 15 +++++++++++++++ .../src/instance/test.rs | 17 +++++++++++++++++ .../src/instance/verify.rs | 16 +++++++++++++--- .../tests/fake/surface.rs | 6 +++++- .../tests/live.rs | 5 ++++- 6 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/config/mod.rs b/crates/tinyhivemind-openhuman-process/src/config/mod.rs index b36e9c3b..aa4648ab 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/mod.rs @@ -19,7 +19,8 @@ //! `"*"` with a denylist let `mcp_call_tool` post as another seat; //! - `auto_approve` exactly the hive tools, whose policy is the host's; //! - memory, recall, conversation memory, search, hooks, suggestions and -//! token compression off. +//! token compression off, and tool-output compaction too: while it is on, +//! 0.64.15 adds `juice_retrieve` to every allowlist. //! //! The top-level `embeddings_provider` is not written: 0.64.15 rewrites any //! value to its hosted default on load, and nothing embeds with memory off. @@ -105,6 +106,7 @@ impl Written { "ccr_enabled": false, "repl_handle_enabled": false, }, + "context": {"compaction_enabled": false}, "hooks": {"enabled": false}, "web_chat": {"suggestions_enabled": false}, "agent_registry": {"entries": [{ diff --git a/crates/tinyhivemind-openhuman-process/src/fixture.rs b/crates/tinyhivemind-openhuman-process/src/fixture.rs index 7d2ff2fa..c20add33 100644 --- a/crates/tinyhivemind-openhuman-process/src/fixture.rs +++ b/crates/tinyhivemind-openhuman-process/src/fixture.rs @@ -82,6 +82,21 @@ impl Fixture { } } + /// The config every fixture writes, without a fake. + pub(crate) fn written_for_test() -> Written { + let tools = hashed_tools(); + Written::new(&Input { + model: &model(), + seat: "scout", + prompt: "You scout.", + server: SERVER, + url: "http://127.0.0.1:1/mcp", + bearer: "bearer", + tools: &tools, + turn_secs: 600, + }) + } + pub(crate) async fn new() -> Self { Self::with(&[]).await } diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index 072653d7..5def44bb 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -129,3 +129,20 @@ fn the_binary_lets_a_turn_run_past_the_seats_own_limit() { assert_eq!(turn_secs(Some(Duration::from_secs(5))), 600); assert_eq!(turn_secs(Some(Duration::from_secs(3600))), 3660); } + +#[test] +fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { + let available = ["juice_retrieve".to_owned(), "mcp_s_post_1".to_owned()]; + let agent = serde_json::json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); + let on = serde_json::json!({"agent_registry": {"entries": [agent.clone()]}}); + assert_eq!(super::verify::visible(&on, &available), ["mcp_s_post_1", "juice_retrieve"]); + let off = serde_json::json!({"agent_registry": {"entries": [agent]}, "context": {"compaction_enabled": false}}); + assert_eq!(super::verify::visible(&off, &available), ["mcp_s_post_1"]); +} + +#[test] +fn the_written_config_turns_compaction_off() { + let settings = Fixture::written_for_test().settings(); + let compaction = settings.iter().find(|(name, _)| name == "context.compaction_enabled"); + assert_eq!(compaction.map(|(_, value)| value.clone()), Some(serde_json::json!(false))); +} diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs index acbfb527..1db729fc 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -63,15 +63,25 @@ pub(crate) async fn discover( } } +/// The tool 0.64.15 adds to any allowlist while tool-output compaction is +/// on, so that the model can recover a compacted result. +const RECOVERY: &str = "juice_retrieve"; + /// The tools the model sees: the agent's effective allowlist, of those the -/// instance has. -fn visible(config: &Value, available: &[String]) -> Vec { +/// instance has, and the recovery tool unless compaction is off, which the +/// binary defaults it to. +pub(super) fn visible(config: &Value, available: &[String]) -> Vec { let entries = config["agent_registry"]["entries"].as_array().cloned(); let agent = entries.unwrap_or_default().into_iter().find(|entry| entry["id"] == AGENT_ID); let allowed = agent.map(|agent| agent["tool_allowlist"].clone()).unwrap_or(Value::Null); let allowed = allowed.as_array().cloned().unwrap_or_default(); let names = allowed.iter().filter_map(Value::as_str); - names.filter(|name| available.iter().any(|tool| tool == name)).map(str::to_owned).collect() + let mut seen: Vec = + names.filter(|name| available.iter().any(|tool| tool == name)).map(str::to_owned).collect(); + if config["context"]["compaction_enabled"] != false { + seen.push(RECOVERY.to_owned()); + } + seen } /// Hold the instance at `client` against the child `pid`, the pinned diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index 1cd05f52..c5a122f2 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -12,7 +12,8 @@ //! - events go to `/events` subscribers of the turn's `client_id`, and an //! `approval_request` carries the approval's id as its `request_id`; //! - a new message on a busy thread interrupts the turn on it; -//! - the custom agent ends after eight iterations as if it had finished. +//! - the custom agent ends after eight iterations as if it had finished; +//! - compaction is on unless the config turns it off. //! //! It is driven through files in a control directory shared with the test: //! `steps/` (the scripted model, in name order), `calls.jsonl` (each model @@ -438,6 +439,9 @@ fn effective(setup: &Setup) -> Value { .and_then(|table| serde_json::to_value(table).ok()); let mut config = parsed.unwrap_or_else(|| json!({"schema_version": 13})); config["embeddings_provider"] = json!("openhuman"); + if config["context"]["compaction_enabled"].is_null() { + config["context"]["compaction_enabled"] = json!(true); + } if let Some(servers) = config["mcp_client"]["servers"].as_array_mut() { for server in servers { server["timeout_secs"] = json!(30); diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs index 9cd5982f..b392351e 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -153,7 +153,10 @@ async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { tokio::time::sleep(Duration::from_millis(20)).await; } let again = runner.run(request("t3", "PLAIN again", Some(&session))).await?; - assert_eq!(again.reply.as_deref(), Some("MOCK_REPLY turns=3")); + // The same thread, without the cancelled turn's message: the binary keeps + // only turns that ended, as the spike saw too. + assert_eq!(again.reply.as_deref(), Some("MOCK_REPLY turns=2")); + assert_eq!(again.session_id, session); harness.stop("scout").await?; assert!(seat_support::processes_in(&root.path().join("instance")).is_empty()); From 4ef18bebcc09224808e00d5524a56be67851d11b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:57:38 +0000 Subject: [PATCH 33/49] feat(ci): add harness fetch script and lock file Introduce a script that downloads the pinned harness artifacts and a lock file recording their versions, so CI runs against reproducible harness builds instead of whatever is fetched at run time. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/scripts/fetch-harness.sh | 64 ++++++++++++++++++++++++++++++++ harnesses.lock | 20 ++++++++++ 2 files changed, 84 insertions(+) create mode 100755 .github/scripts/fetch-harness.sh create mode 100644 harnesses.lock diff --git a/.github/scripts/fetch-harness.sh b/.github/scripts/fetch-harness.sh new file mode 100755 index 00000000..fb84bd6b --- /dev/null +++ b/.github/scripts/fetch-harness.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# fetch-harness.sh [target] +# +# Fetch the harness binary `harnesses.lock` pins for and +# (default: this machine's), verify it, and print the binary's absolute path. +# The asset's sha256 must match the lock, and so must the binary's where the +# lock records it. Nothing is installed or run; the library takes the path. +# +# THM_OPENHUMAN_CORE=$(.github/scripts/fetch-harness.sh openhuman target/harness) +set -euo pipefail + +kind="${1:?usage: fetch-harness.sh [target]}" +dest="${2:?usage: fetch-harness.sh [target]}" +target="${3:-$(uname -m)-unknown-linux-gnu}" +root="$(cd "$(dirname "$0")/../.." && pwd)" +lock="$root/harnesses.lock" + +# The entry of the lock for this kind and target, as `key=value` lines. +entry="$(awk -v kind="[[$kind]]" -v target="$target" ' + $0 == kind { inside = 1; delete fields; next } + /^\[\[/ { inside = 0 } + inside && /^[a-z_0-9]+ = "/ { + key = $1; value = $0; sub(/^[^"]*"/, "", value); sub(/"[^"]*$/, "", value) + fields[key] = value + if (key == "binary" && fields["target"] == target) { + for (k in fields) print k "=" fields[k] + } + } + inside && /^binary_sha256 = / && fields["target"] == target { print "binary_sha256=" fields["binary_sha256"] } +' "$lock" | sort -u)" +field() { sed -n "s/^$1=//p" <<<"$entry"; } +url="$(field url)"; sha="$(field sha256)"; version="$(field version)" +binary="$(field binary)"; binary_sha="$(field binary_sha256)" +if [ -z "$url" ] || [ -z "$sha" ] || [ -z "$binary" ]; then + echo "fetch-harness: no $kind entry for $target in harnesses.lock" >&2 + exit 1 +fi + +mkdir -p "$dest" +dest="$(cd "$dest" && pwd)" +asset="$dest/$(basename "$url")" +if ! echo "$sha $asset" | sha256sum -c --status 2>/dev/null; then + curl -fsSL --proto '=https' -o "$asset.partial" "$url" + mv "$asset.partial" "$asset" +fi +if ! echo "$sha $asset" | sha256sum -c --status; then + echo "fetch-harness: $asset does not have the sha256 harnesses.lock pins" >&2 + rm -f "$asset" + exit 1 +fi + +unpacked="$dest/$kind-$version-$target" +rm -rf "$unpacked" && mkdir -p "$unpacked" +tar -xzf "$asset" -C "$unpacked" +path="$(find "$unpacked" -type f -name "$binary" | head -n 1)" +if [ -z "$path" ]; then + echo "fetch-harness: $asset holds no $binary" >&2 + exit 1 +fi +if [ -n "$binary_sha" ] && ! echo "$binary_sha $path" | sha256sum -c --status; then + echo "fetch-harness: $path does not have the sha256 harnesses.lock pins" >&2 + exit 1 +fi +echo "$path" diff --git a/harnesses.lock b/harnesses.lock new file mode 100644 index 00000000..381b5ae7 --- /dev/null +++ b/harnesses.lock @@ -0,0 +1,20 @@ +# The harness binaries process runners are tested against, one entry per +# kind and target. Library code never downloads: `.github/scripts/fetch-harness.sh` +# fetches an entry's asset, checks its sha256 (and the binary's, where it is +# recorded), and prints the binary's path for the host to pass in. +# Spec: docs/specs/harnesses.md#pins. + +[[openhuman]] +version = "0.64.15" +target = "x86_64-unknown-linux-gnu" +url = "https://github.com/tinyhumansai/openhuman/releases/download/v0.64.15/openhuman-core-0.64.15-x86_64-unknown-linux-gnu.tar.gz" +sha256 = "f86ae0157b4ed28767c580c443e04027b62fe14e6f3260786f44cd265a242587" +binary = "openhuman-core" +binary_sha256 = "4788efd57d66ee43ae398c99875a2c84e006691e9fbefab60e5a22c0fb7fefce" + +[[openhuman]] +version = "0.64.15" +target = "aarch64-unknown-linux-gnu" +url = "https://github.com/tinyhumansai/openhuman/releases/download/v0.64.15/openhuman-core-0.64.15-aarch64-unknown-linux-gnu.tar.gz" +sha256 = "eabac98af5f1feb711b4ffd48185aa06a233fa6bbcd1bcd4d733397dace03b9b" +binary = "openhuman-core" From e9376b7ed0cbf3a8d2325fc27e31e210bd2ab2f6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:57:55 +0000 Subject: [PATCH 34/49] fix(ci): suppress sha256sum stderr during harness cache check Redirect stderr to /dev/null alongside stdout so a cache miss no longer prints a checksum failure message during the harness fetch step. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/scripts/fetch-harness.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/fetch-harness.sh b/.github/scripts/fetch-harness.sh index fb84bd6b..74eca7c7 100755 --- a/.github/scripts/fetch-harness.sh +++ b/.github/scripts/fetch-harness.sh @@ -39,7 +39,7 @@ fi mkdir -p "$dest" dest="$(cd "$dest" && pwd)" asset="$dest/$(basename "$url")" -if ! echo "$sha $asset" | sha256sum -c --status 2>/dev/null; then +if ! echo "$sha $asset" | sha256sum -c --status >/dev/null 2>&1; then curl -fsSL --proto '=https' -o "$asset.partial" "$url" mv "$asset.partial" "$asset" fi From 922be66a5dbfbb9afe243fff0d67951279bdf2c7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:58:03 +0000 Subject: [PATCH 35/49] ci(assert-pure): include process harness client in host crates The purity check now treats tinyhivemind-openhuman-process as a host crate, since the process harness clients may hold a runtime and an HTTP client but must never link one. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/scripts/assert-pure.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/scripts/assert-pure.sh b/.github/scripts/assert-pure.sh index ee1c630b..69c818d1 100755 --- a/.github/scripts/assert-pure.sh +++ b/.github/scripts/assert-pure.sh @@ -17,9 +17,10 @@ set -euo pipefail # whose vocabulary dependency includes `anyhow` and `async-trait`. pure_crates=("tinyhivemind-core" "tinyhivemind-lang") tool_crates=("tinyhivemind-tools") -# Host runs harnesses as processes (ADR 0035), so it may hold a runtime, but it +# Host and the process harness clients run harnesses as processes (ADR 0035), +# so they may hold a runtime and an HTTP client, but they # must never link one. -host_crates=("tinyhivemind-host") +host_crates=("tinyhivemind-host" "tinyhivemind-openhuman-process") forbidden_pure='tokio|futures|async-trait|axum|hyper|reqwest|ureq|curl|anyhow|rusqlite|git2|openhuman|tinyagents|tinytools' # Whole families: `openhuman-embed`, `tinyagents-harness` and so on. From 7b6efc9f8fc7cf2cd4e2f29b1693b1c31cca4ed9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:58:29 +0000 Subject: [PATCH 36/49] fix(ci): exclude the checked crate's own line from purity check The dependency scan matched the crate under test itself when its name shared a prefix with a forbidden adapter family, so the crate's own line is now filtered out. The failure message was also updated to mention the process harness clients alongside the host crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/scripts/assert-pure.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/scripts/assert-pure.sh b/.github/scripts/assert-pure.sh index 69c818d1..02d00621 100755 --- a/.github/scripts/assert-pure.sh +++ b/.github/scripts/assert-pure.sh @@ -40,7 +40,9 @@ check_crate() { echo "assert-pure: cargo tree failed for '$crate'" >&2 exit 1 } - found="$(grep -Ei "^(${forbidden})(-embed)? v" <<<"$tree" || true)" + # The crate's own line is not a dependency: `tinyhivemind-openhuman-process` + # is named like the forbidden linked adapter's family. + found="$(grep -Ei "^(${forbidden})(-embed)? v" <<<"$tree" | grep -v "^${crate} v" || true)" if [ -n "$found" ]; then echo "$crate pulled in a dependency its manifest forbids:" >&2 echo "$found" >&2 @@ -64,7 +66,8 @@ if [ "$status" -ne 0 ]; then echo "A pure crate is linked into the hot path of every agent turn and must" >&2 echo "compile in a host's default build. It must stay free of async" >&2 echo "runtimes, transports, HTTP clients and web frameworks. The host crate" >&2 - echo "runs harnesses as processes and must link none (ADR 0035)." >&2 + echo "and the process harness clients run harnesses as processes and must" >&2 + echo "link none (ADR 0035)." >&2 exit 1 fi From 0944efcb49de6548479e6306ea3bc88172771b87 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:59:45 +0000 Subject: [PATCH 37/49] docs(tinyhivemind-openhuman-process): add READMEs for crate modules and tests Document the crate's top-level layout along with its capability, config, harness, instance, rpc, and turn modules, and describe the test directories including the fake, live, and support helpers. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-openhuman-process/README.md | 21 ++++++++++++++++++ .../src/README.md | 13 +++++++++++ .../src/capability/README.md | 22 +++++++++++++++++++ .../src/config/README.md | 17 ++++++++++++++ .../src/harness/README.md | 14 ++++++++++++ .../src/instance/README.md | 17 ++++++++++++++ .../src/rpc/README.md | 12 ++++++++++ .../src/turn/README.md | 15 +++++++++++++ .../tests/README.md | 9 ++++++++ .../tests/fake/README.md | 7 ++++++ .../tests/live/README.md | 6 +++++ .../tests/support/README.md | 6 +++++ 12 files changed, 159 insertions(+) create mode 100644 crates/tinyhivemind-openhuman-process/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/capability/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/config/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/harness/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/instance/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/rpc/README.md create mode 100644 crates/tinyhivemind-openhuman-process/src/turn/README.md create mode 100644 crates/tinyhivemind-openhuman-process/tests/README.md create mode 100644 crates/tinyhivemind-openhuman-process/tests/fake/README.md create mode 100644 crates/tinyhivemind-openhuman-process/tests/live/README.md create mode 100644 crates/tinyhivemind-openhuman-process/tests/support/README.md diff --git a/crates/tinyhivemind-openhuman-process/README.md b/crates/tinyhivemind-openhuman-process/README.md new file mode 100644 index 00000000..2a66aa55 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/README.md @@ -0,0 +1,21 @@ +# tinyhivemind-openhuman-process + +Hive seats on OpenHuman without linking it: each seat is one supervised +`openhuman-core run --headless-api`, pinned by version and checksum, driven +over its loopback JSON-RPC and event stream. A seat starts only once the +running instance is shown to be the child that was started, at the pinned +version, with the config that was written, offering its model exactly the +hive's tools. + +It implements the `openhuman` kind of the harness port in +[`tinyhivemind-host`](../tinyhivemind-host/README.md), names no OpenHuman type, +and is a crate of its own so that the linked +[`tinyhivemind-openhuman`](../tinyhivemind-openhuman/README.md) adapter and +`vendor/openhuman` can be deleted without touching it. +[The spec](../../docs/specs/harnesses.md) says what a seat may ask for; the +repository [README](../../README.md) says how this fits the rest. + +| Path | Purpose | +| --- | --- | +| [`src/`](src/README.md) | The crate's modules | +| [`tests/`](tests/README.md) | Conformance over a fake child, and `live_*` on the pin | diff --git a/crates/tinyhivemind-openhuman-process/src/README.md b/crates/tinyhivemind-openhuman-process/src/README.md new file mode 100644 index 00000000..87fd8641 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/README.md @@ -0,0 +1,13 @@ +# Source + +| Path | Purpose | +| --- | --- | +| `lib.rs` | Crate overview and public surface: `OpenHumanHarness`, `Program`, `Options`, `capability`. | +| `error.rs` | The crate's internal `Error`, and how it reaches the port as `harness::Error`. | +| `fixture.rs` | Unit tests only: the in-process fake surface with a written config, and a client. | +| [`capability/`](capability/README.md) | What a lowered seat may ask of this harness: `check`, `Refusal`, `SeatModel`. | +| [`config/`](config/README.md) | The generated `config.toml`, and comparing an effective config with it. | +| [`rpc/`](rpc/README.md) | The loopback client: JSON-RPC, `/health`, `/events`. | +| [`turn/`](turn/README.md) | One turn over `channel_web_chat` and its events; cancellation. | +| [`instance/`](instance/README.md) | Launching an instance, tool discovery, start-up verification. | +| [`harness/`](harness/README.md) | `OpenHumanHarness` and the seat it runs. | diff --git a/crates/tinyhivemind-openhuman-process/src/capability/README.md b/crates/tinyhivemind-openhuman-process/src/capability/README.md new file mode 100644 index 00000000..6116752e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/README.md @@ -0,0 +1,22 @@ +# Capability + +`check` holds a `LoweredSeat` to the `openhuman` column of the capability +table in [the spec](../../../../docs/specs/harnesses.md#capabilities) and +returns the `SeatModel` the config is written from, or the first `Refusal`. + +- Providers: only `openai` with an explicit endpoint and no credential. No + model, no provider (inherit), `inherit`, `openrouter`, `anthropic`, a missing + endpoint and a credential are each a `Refusal`. +- `temperature` and `max_tokens` are refused: nothing proves the binary honours them. +- `limits.iterations` above `ITERATION_CAP` (8) is refused; below it, a turn + past the limit fails. `limits.budget_usd` is refused. +- A sandbox other than `none`, a built-in tool group not `off`, `memory`, + `agent_id`, `definition_base`, `subagents`, `skills`, `context` and + `bare_prompt` are refused. +- Hive and executable tools, hooks, permissions other than `sandbox`, + `autonomy`, `access` and package MCP servers are host side and not judged here. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `check`, `Refusal`, `SeatModel`, `ITERATION_CAP` | +| `test.rs` | Every row and refusal | diff --git a/crates/tinyhivemind-openhuman-process/src/config/README.md b/crates/tinyhivemind-openhuman-process/src/config/README.md new file mode 100644 index 00000000..a631082d --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/README.md @@ -0,0 +1,17 @@ +# Config + +The `config.toml` of a seat's instance, built as one JSON tree from the spike's +`config.toml.in` and written as TOML. `Written::settings` names every leaf +written plus `api_key`, `api_url` and `inference_url`, which must stay unset; +`Written::observe` reads the same paths from a `config_get` snapshot, cutting +lists of tables down to the keys written. The binary falls back to defaults on +TOML it cannot read, so that comparison is the only proof the config took. + +Not written: the top-level `embeddings_provider`, which 0.64.15 rewrites to +its hosted default on load whatever it says; memory is off, so nothing embeds. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Input`, `Written`, `AGENT_ID`, the fixed settings and why | +| `toml.rs` | JSON as TOML, for the shapes the config has | +| `test.rs` | What the config says, that it parses back, and the comparison | diff --git a/crates/tinyhivemind-openhuman-process/src/harness/README.md b/crates/tinyhivemind-openhuman-process/src/harness/README.md new file mode 100644 index 00000000..9638dcb5 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/README.md @@ -0,0 +1,14 @@ +# Harness + +`OpenHumanHarness` refuses a seat `capability::check` refuses, then starts one +instance per seat and returns a `SeatRunner` around the seat. The seat starts +another instance when its child has died, resumes only a thread whose +transcript the instance has (`threads_transcript_get`), cancels by its +`Active` turn, and kills the instance when a cancel cannot be shown to work. +`stop` closes a running turn's events, cancels it and stops the instance +through the supervisor. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `OpenHumanHarness`, `Program`, `Options` | +| `seat.rs` | `Seat` and its `Runner` | diff --git a/crates/tinyhivemind-openhuman-process/src/instance/README.md b/crates/tinyhivemind-openhuman-process/src/instance/README.md new file mode 100644 index 00000000..1c5bc29f --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/README.md @@ -0,0 +1,17 @@ +# Instances + +`Launcher::launch` makes the seat's private directories (`ws/`, `home/`, +`action/`, the keyring key), starts a discovery instance whose allowlist +matches nothing, waits out the MCP warm-up and reads each hive tool's hashed +name, stops it, writes the exact allowlist and starts again. `verify` then +compares `/health.pid` with the child, `core.version` with the pin, `config_get` +with what was written, and the model-visible tools with the hive tools: the +agent's effective allowlist of the tools the instance has, plus +`juice_retrieve` unless `context.compaction_enabled` is off. Any difference +stops the instance and fails the start. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Launcher`, `Live`, `Layout`, the environment | +| `verify.rs` | `discover`, `verify` | +| `test.rs` | Against the fake surface, and the exact environment | diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/README.md b/crates/tinyhivemind-openhuman-process/src/rpc/README.md new file mode 100644 index 00000000..c486eacc --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/README.md @@ -0,0 +1,12 @@ +# Loopback client + +`Client` talks to one instance at `http://127.0.0.1:` with its core +token as bearer: `call` for JSON-RPC at `/rpc` (30 s each), `health` for +`/health`, and `events` for the `/events` stream of one `client_id`, parsed by +`sse::Parser`. No proxy, no TLS, and no URL, token or body in an error. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Client`, `Events`, `Error` | +| `sse.rs` | Server-Sent Events framing | +| `test.rs` | Against the fake surface, and the parser on every split | diff --git a/crates/tinyhivemind-openhuman-process/src/turn/README.md b/crates/tinyhivemind-openhuman-process/src/turn/README.md new file mode 100644 index 00000000..307c16d6 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/README.md @@ -0,0 +1,15 @@ +# Turns + +`run` subscribes to `/events` for the turn's own `client_id`, then submits +`channel_web_chat` on the seat's thread, records the returned `request_id` in +the seat's `Active`, and follows that request's events: progress, approvals +through the seat's approver and `approval_decide`, `chat_done` with the turn's +own usage, `chat_error` and `chat_cancelled` as failures. Reaching the +eight-iteration cap is a failed turn, as is passing a lower seat limit. +`cancel` is `channel_web_cancel` scoped to the request, then a wait for its end. +A turn is never submitted twice. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `run`, `cancel`, `Turn`, `Active`, `Ended`, `Error` | +| `test.rs` | Against the fake surface | diff --git a/crates/tinyhivemind-openhuman-process/tests/README.md b/crates/tinyhivemind-openhuman-process/tests/README.md new file mode 100644 index 00000000..4841cee4 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/README.md @@ -0,0 +1,9 @@ +# Tests + +| Path | Purpose | +| --- | --- | +| `conformance.rs` | The host's conformance suite over this runner and the fake child; refusals through the port. Needs `--features conformance`. | +| `live.rs` | `live_*`: the suite and the spike gate on the pinned binary, opted into with `THM_OPENHUMAN_CORE` (and Node, from `THM_NODE` or `PATH`). | +| [`fake/`](fake/README.md) | The fake `openhuman-core` surface and child | +| [`live/`](live/README.md) | The live subject and scripted model | +| [`support/`](support/README.md) | Shared HTTP server and seat helpers | diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/README.md b/crates/tinyhivemind-openhuman-process/tests/fake/README.md new file mode 100644 index 00000000..e5eef41b --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/README.md @@ -0,0 +1,7 @@ +# The fake openhuman-core + +| File | Purpose | +| --- | --- | +| `surface.rs` | The scripted RPC, `/health` and `/events` surface, recorded from 0.64.15; driven by a control directory. Also compiled into the unit tests. | +| `child.rs` | The `tinyhivemind-fake-openhuman` binary: the surface on `--port`, with the runner's environment, and a grandchild that escapes its session on request. | +| `subject.rs` | Both as a conformance `Subject`, launched through a wrapper script that sets `CONTROL`. | diff --git a/crates/tinyhivemind-openhuman-process/tests/live/README.md b/crates/tinyhivemind-openhuman-process/tests/live/README.md new file mode 100644 index 00000000..c4f2744e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/README.md @@ -0,0 +1,6 @@ +# Live + +| File | Purpose | +| --- | --- | +| `subject.rs` | The pinned binary as a conformance `Subject`, with the spike fixture's MCP stub run by Node, and a wrapper that can corrupt the written config. | +| `model.rs` | A scripted Chat Completions model that plays the suite's steps and sees a hang-up. | diff --git a/crates/tinyhivemind-openhuman-process/tests/support/README.md b/crates/tinyhivemind-openhuman-process/tests/support/README.md new file mode 100644 index 00000000..1e13b514 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/README.md @@ -0,0 +1,6 @@ +# Support + +| File | Purpose | +| --- | --- | +| `http.rs` | A small HTTP/1.1 server: JSON answers, close-delimited streams, hang-up notice. | +| `seat.rs` | The test seat, and the processes of an instance directory. | From 70af08d93c94f056b1bcd351f2b8eede86757854 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:00:08 +0000 Subject: [PATCH 38/49] docs(harnesses): document the openhuman process runner The harness spec and process-harness plan now record the `openhuman` client in `tinyhivemind-openhuman-process`, which passes the conformance suite offline and on the pinned 0.64.15 binary, along with the behaviours that implementing it settled. AGENTS.md lists the new crate and notes that it links no harness. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- AGENTS.md | 6 +++- docs/plans/2026-11-25-process-harnesses.md | 9 ++++-- docs/specs/harnesses.md | 34 ++++++++++++++++++---- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d3678b94..063f7896 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ is not advisory — do not add an exception to it to land a change. ## Project Structure -This is a Rust 2024 virtual Cargo workspace with seven packages. Core owns all +This is a Rust 2024 virtual Cargo workspace with eight packages. Core owns all host-neutral behavior; lang is where a hive mind is defined, integrations included; tools renders native tool definitions and records calls; exec runs a package's executable tools and hooks; host is the harness-neutral @@ -76,6 +76,7 @@ crates/ ├── tinyhivemind-exec/ # runs a package's executable tools and script hooks ├── tinyhivemind-host/ # hive tool belt, policies, package plans, harness processes ├── tinyhivemind-openhuman/ # package deployment, seat runners, host integration +├── tinyhivemind-openhuman-process/ # OpenHuman seats as supervised processes ├── tinyhivemind-hives/ # durable cross-hive coordinator └── tinyhivemind-lang/ # pure hive packages: structure, integrations, edits, lineage wiki/ # GitHub wiki submodule @@ -97,6 +98,9 @@ permissions, profiles, hooks, session, Jev, features and workflows — as data, and lowering resolves it per seat; it names no harness type and starts no process. `tinyhivemind-exec` runs those executable tools and hooks (`docs/specs/executable-tools.md`) and is not one of the pure crates. +`tinyhivemind-openhuman-process` implements the host's harness port for the +`openhuman` kind over a pinned `openhuman-core` binary (`harnesses.lock`); it +links no harness either. `tinyhivemind-host` depends on core, hives and lang, and owns what every harness shares: the hive tools and their dispatch, the send and management policy ports, turn scope and prompt, package loading, the deployment plan, and supervised diff --git a/docs/plans/2026-11-25-process-harnesses.md b/docs/plans/2026-11-25-process-harnesses.md index c13cbe8c..3ef77b45 100644 --- a/docs/plans/2026-11-25-process-harnesses.md +++ b/docs/plans/2026-11-25-process-harnesses.md @@ -72,9 +72,12 @@ cases are diagnosed at their location; a roster-only edit cannot change `harness - **4a. `tinyhivemind-openclaw`:** handshake with Ed25519 device identity, `agent` and its second response, `chat.abort`, generated config, recovery hold. -- **4b. OpenHuman process runner** in `tinyhivemind-openhuman`, beside the linked - path: workspace and config per seat, `web_chat` and `/events`, `web_cancel`, - start-up verification, approvals through `list_pending` and `decide`. +- **4b. OpenHuman process runner** in `tinyhivemind-openhuman-process`, a crate + beside the linked adapter rather than a module of it, so that step 6 deletes + the adapter without touching it: workspace and config per seat, `web_chat` and + `/events`, `web_cancel`, start-up verification, approvals through the + `approval_request` event and `decide`. Done: conformance offline and `live_*` + on 0.64.15. - **4c. `tinyhivemind-codex`:** app-server over stdio, pinned catalog, per-thread MCP. Medulla's `codex_app_server` is the reference for framing; its silent new thread on a failed resume is not copied. diff --git a/docs/specs/harnesses.md b/docs/specs/harnesses.md index aab73c61..04a83d5a 100644 --- a/docs/specs/harnesses.md +++ b/docs/specs/harnesses.md @@ -7,10 +7,11 @@ Evidence: [the harness spike](../experiments/2026-11-25-process-harnesses.md). Implemented so far, by step 1 of the plan: the harness-neutral host crate, the harness port with the seat rules below, start verification, process supervision -on Linux, and a conformance suite that a scripted fake harness passes. No client -for a real harness, no MCP server and no `harnesses` section exist yet. Until the -plan's removal phase lands, the linked OpenHuman adapter remains the way a -package is deployed. +on Linux, and a conformance suite that a scripted fake harness passes. Step 4b adds the +`openhuman` client, `crates/tinyhivemind-openhuman-process`, which passes that +suite offline and on the pinned binary. No MCP server and no `harnesses` +section exist yet, so no deployment uses it. Until the plan's removal phase +lands, the linked OpenHuman adapter remains the way a package is deployed. ## Problem @@ -322,6 +323,28 @@ reports it as a normal end. Until that is configurable, a package asking for mor iterations is rejected for this kind, and a turn that reaches the cap is reported as failed. The runner counts `iteration_start` events to tell. +What implementing it on 0.64.15 settled: + +- `context.compaction_enabled` defaults on, and while it is on the binary adds + `juice_retrieve` to every allowlist. The config turns it off, and the start + check counts `juice_retrieve` as model-visible unless the effective config + has it off. +- The hashed names are known only to a running instance, so a start is two: + one whose allowlist matches nothing, to read them, and the verified one. +- A session is a `thread_id`, the same for a seat's life. A turn that names a + session runs only if `threads_transcript_get` has a transcript for it; + otherwise the turn fails as a resume failure and nothing reaches the model. +- Every turn has its own `client_id`, and its `/events` subscription is open + before `channel_web_chat` is called, since the first events can precede its + answer. Events are taken only for the returned `request_id`, except + `approval_request`, whose `request_id` is the approval's. +- A cancelled turn leaves no message in the thread. +- The top-level `embeddings_provider` is rewritten to the hosted default on + load whatever the file says, so it is neither written nor compared; memory + is off, so nothing embeds. The binary also carries a compiled-in Sentry DSN + that no config or environment entry empties, which is one more reason live + runs block egress. + **OpenClaw.** Tool search and code mode off; `tools.allow` exactly the seat's server; the deny groups recorded in the experiment; agent-to-agent off. After a crash, do not admit a turn for a seat until its recovery is known to be settled. @@ -339,7 +362,8 @@ Login tokens are a host secret and enter only the instance's environment. ## Pins -A lock file records version, target and sha256 for each kind. A script fetches +A lock file records version, target and sha256 for each kind: `harnesses.lock` +at the repository root. A script, `.github/scripts/fetch-harness.sh`, fetches and verifies; the library takes a path. Live tests run against exactly the pin, with outbound network blocked except to the model endpoint under test. From 191bac374d1ae2a49538aaf9aa220012b4a95309 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:01:26 +0000 Subject: [PATCH 39/49] style(tinyhivemind-openhuman-process): apply rustfmt formatting Reformatted the crate's source and test files to satisfy rustfmt, wrapping long method chains and type annotations without changing any behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/capability/mod.rs | 11 ++- .../src/capability/test.rs | 24 +++-- .../src/config/mod.rs | 14 +-- .../src/config/test.rs | 10 +- .../src/fixture.rs | 4 +- .../src/harness/mod.rs | 5 +- .../src/harness/seat.rs | 16 ++- .../src/instance/mod.rs | 20 +++- .../src/instance/test.rs | 79 ++++++++++++--- .../src/instance/verify.rs | 30 ++++-- .../tinyhivemind-openhuman-process/src/lib.rs | 10 +- .../src/rpc/mod.rs | 15 ++- .../src/rpc/sse.rs | 3 +- .../src/rpc/test.rs | 58 ++++++++--- .../src/turn/mod.rs | 30 +++--- .../src/turn/test.rs | 42 ++++++-- .../tests/conformance.rs | 4 +- .../tests/fake/child.rs | 4 +- .../tests/fake/subject.rs | 2 +- .../tests/fake/surface.rs | 97 +++++++++++++++---- .../tests/live.rs | 64 +++++++++--- .../tests/live/model.rs | 25 ++++- .../tests/live/subject.rs | 31 ++++-- .../tests/support/http.rs | 5 +- .../tests/support/seat.rs | 1 - 25 files changed, 453 insertions(+), 151 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/capability/mod.rs b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs index 0a4ab0c2..b976ba09 100644 --- a/crates/tinyhivemind-openhuman-process/src/capability/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs @@ -1,4 +1,4 @@ -//! What a lowered seat may ask of an OpenHuman process, and what it gets. +//! What a lowered seat may ask of an `OpenHuman` process, and what it gets. //! //! [`check`] reads a [`LoweredSeat`] against the `openhuman` column of the //! capability table in `docs/specs/harnesses.md` and returns the [`SeatModel`] @@ -103,9 +103,12 @@ pub fn check(seat: &LoweredSeat) -> Result { let integration = &seat.integration; let lowered = integration.model.as_ref().ok_or(Refusal::NoModel)?; let model = &lowered.model; - let provider = lowered.provider.as_ref().ok_or_else(|| Refusal::NoProvider { - model: model.id.clone(), - })?; + let provider = lowered + .provider + .as_ref() + .ok_or_else(|| Refusal::NoProvider { + model: model.id.clone(), + })?; let kind = match provider.kind { ProviderKind::Openai => None, ProviderKind::Inherit => Some("inherit"), diff --git a/crates/tinyhivemind-openhuman-process/src/capability/test.rs b/crates/tinyhivemind-openhuman-process/src/capability/test.rs index 7bddde31..e010bd8b 100644 --- a/crates/tinyhivemind-openhuman-process/src/capability/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/capability/test.rs @@ -46,13 +46,21 @@ fn refused(change: impl FnOnce(&mut LoweredSeat)) -> Refusal { } fn provider(seat: &mut LoweredSeat) -> &mut Provider { - let model = seat.integration.model.as_mut().map(|model| &mut model.provider); + let model = seat + .integration + .model + .as_mut() + .map(|model| &mut model.provider); let provider = model.and_then(Option::as_mut); provider.unwrap_or_else(|| unreachable!("the seat has a provider")) } fn model(seat: &mut LoweredSeat) -> &mut Model { - let model = seat.integration.model.as_mut().map(|model| &mut model.model); + let model = seat + .integration + .model + .as_mut() + .map(|model| &mut model.model); model.unwrap_or_else(|| unreachable!("the seat has a model")) } @@ -160,7 +168,9 @@ fn a_sandbox_and_built_in_tools_are_rejected() { } let mut none = seat(); none.integration.permissions.push(PermissionSet::default()); - none.integration.groups.insert("shell".into(), GroupMode::Off); + none.integration + .groups + .insert("shell".into(), GroupMode::Off); assert!(check(&none).is_ok()); for mode in [GroupMode::Advertised, GroupMode::Withheld] { let refusal = refused(|seat| { @@ -175,7 +185,8 @@ fn a_sandbox_and_built_in_tools_are_rejected() { #[test] fn fields_this_harness_does_not_take_are_named() { - let cases: [(&str, fn(&mut LoweredSeat)); 6] = [ + type Change = fn(&mut LoweredSeat); + let cases: [(&str, Change); 6] = [ ("agent_id", |seat| { seat.integration.agent_id = Some("a".into()); }), @@ -192,9 +203,8 @@ fn fields_this_harness_does_not_take_are_named() { ("bare_prompt", |seat| seat.integration.bare_prompt = true), ("skills", |seat| { let skill = serde_json::json!({"id": "s"}); - let skill = serde_json::from_value(skill).unwrap_or_else(|error| { - unreachable!("a skill of an id and a path: {error}") - }); + let skill = serde_json::from_value(skill) + .unwrap_or_else(|error| unreachable!("a skill of an id and a path: {error}")); seat.integration.skills.push(skill); }), ]; diff --git a/crates/tinyhivemind-openhuman-process/src/config/mod.rs b/crates/tinyhivemind-openhuman-process/src/config/mod.rs index aa4648ab..57c50d62 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/mod.rs @@ -182,12 +182,14 @@ fn lookup<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { fn project(written: &Value, found: Value) -> Value { match (written, found) { (Value::Array(written), Value::Array(found)) => { - let entries = found.into_iter().enumerate().map(|(index, entry)| { - match written.get(index) { - Some(shape) => project(shape, entry), - None => entry, - } - }); + let entries = + found + .into_iter() + .enumerate() + .map(|(index, entry)| match written.get(index) { + Some(shape) => project(shape, entry), + None => entry, + }); Value::Array(entries.collect()) } (Value::Object(written), Value::Object(mut found)) => { diff --git a/crates/tinyhivemind-openhuman-process/src/config/test.rs b/crates/tinyhivemind-openhuman-process/src/config/test.rs index 3def9c54..e39cf95a 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/test.rs @@ -27,7 +27,10 @@ fn written(prompt: &str, tools: &[String]) -> Written { } fn tools() -> Vec { - vec!["mcp_hivemind_post_1a2b3c".into(), "mcp_hivemind_ask_4d5e6f".into()] + vec![ + "mcp_hivemind_post_1a2b3c".into(), + "mcp_hivemind_ask_4d5e6f".into(), + ] } /// The file as `openhuman-core` reads it. @@ -111,7 +114,10 @@ fn memory_search_hooks_suggestions_and_compression_are_off() { fn a_prompt_cannot_break_out_of_its_string() { let prompt = "line one\n[hooks]\nenabled = true\n\"\"\" ' \\ \u{1}"; let config = parsed(&written(prompt, &tools())); - assert_eq!(config["agent_registry"]["entries"][0]["system_prompt"], prompt); + assert_eq!( + config["agent_registry"]["entries"][0]["system_prompt"], + prompt + ); assert_eq!(config["hooks"], json!({"enabled": false})); } diff --git a/crates/tinyhivemind-openhuman-process/src/fixture.rs b/crates/tinyhivemind-openhuman-process/src/fixture.rs index c20add33..ad4f77e5 100644 --- a/crates/tinyhivemind-openhuman-process/src/fixture.rs +++ b/crates/tinyhivemind-openhuman-process/src/fixture.rs @@ -112,7 +112,9 @@ impl Fixture { /// Each line of a control file the fake writes. pub(crate) fn log(&self, name: &str) -> Vec { let text = fs::read_to_string(self.control.join(name)).unwrap_or_default(); - text.lines().filter_map(|line| serde_json::from_str(line).ok()).collect() + text.lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() } /// The states of the model calls, in order. diff --git a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs index 3f53c7f3..31e5707f 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs @@ -62,7 +62,7 @@ impl Default for Options { } } -/// Runs seats on OpenHuman, one supervised `openhuman-core` per seat. +/// Runs seats on `OpenHuman`, one supervised `openhuman-core` per seat. /// /// Its futures must be driven within a Tokio runtime with time and I/O /// enabled. @@ -108,7 +108,8 @@ impl Harness for OpenHumanHarness { let options = self.options; let seats = self.seats.clone(); Box::pin(async move { - let model = capability::check(&plan.seat).map_err(|refusal| Error::Refused(Box::new(refusal)))?; + let model = capability::check(&plan.seat) + .map_err(|refusal| Error::Refused(Box::new(refusal)))?; let id = plan.seat.id.clone(); if lock(&seats).contains_key(&id) { return Err(Error::Harness(format!("seat {id} is already running"))); diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs index 05953b14..7e3ed81f 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -8,7 +8,9 @@ use serde_json::json; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use tinyhivemind_hives::{AgentRunner, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest}; -use tinyhivemind_host::harness::{self, CancelFuture, CancellableRunner, Event, SeatPlan, ToolEndpoint}; +use tinyhivemind_host::harness::{ + self, CancelFuture, CancellableRunner, Event, SeatPlan, ToolEndpoint, +}; use tokio::sync::{Mutex as AsyncMutex, watch}; /// A seat and its instance, if one is running. @@ -26,7 +28,10 @@ pub(super) struct Seat { } fn current(active: &Mutex>) -> Option { - active.lock().unwrap_or_else(PoisonError::into_inner).clone() + active + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() } fn clear(active: &Mutex>) { @@ -91,7 +96,10 @@ impl Seat { if let Some(session) = &request.session_id { let found = live .client - .call("openhuman.threads_transcript_get", json!({"thread_id": session})) + .call( + "openhuman.threads_transcript_get", + json!({"thread_id": session}), + ) .await?; if found["data"]["hasTranscript"] != true { return Err(Error::Resume(session.clone())); @@ -104,7 +112,7 @@ impl Seat { client: &live.client, seat: &self.plan.seat.id, thread: &thread, - turn_id: &request.turn_id, + id: &request.turn_id, client_id: format!("thm-turn-{number}"), iterations: self.model.iterations, observer: self.plan.observer.as_ref(), diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs index 4ccf7090..2dc56458 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -27,6 +27,7 @@ use crate::config::{Input, Written}; use crate::error::{Error, Result}; use crate::harness::{Options, Program}; use crate::rpc::Client; +use std::fmt::Write as _; use std::fs; use std::io::{Read as _, Write as _}; use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _}; @@ -73,7 +74,9 @@ impl Layout { let mut builder = fs::DirBuilder::new(); builder.recursive(true).mode(0o700); for dir in [self.workspace(), self.home(), self.action()] { - builder.create(dir).map_err(Error::io("the instance directories"))?; + builder + .create(dir) + .map_err(Error::io("the instance directories"))?; } Ok(()) } @@ -91,7 +94,8 @@ impl Layout { .mode(0o600) .open(&path) .map_err(Error::io("the keyring key"))?; - file.write_all(key.as_bytes()).map_err(Error::io("the keyring key"))?; + file.write_all(key.as_bytes()) + .map_err(Error::io("the keyring key"))?; Ok(key) } @@ -104,7 +108,8 @@ impl Layout { .mode(0o600) .open(path) .map_err(Error::io("the config"))?; - file.write_all(written.toml().as_bytes()).map_err(Error::io("the config")) + file.write_all(written.toml().as_bytes()) + .map_err(Error::io("the config")) } } @@ -112,8 +117,13 @@ impl Layout { fn random() -> Result { let mut bytes = [0_u8; 32]; let mut source = fs::File::open("/dev/urandom").map_err(Error::io("/dev/urandom"))?; - source.read_exact(&mut bytes).map_err(Error::io("/dev/urandom"))?; - Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) + source + .read_exact(&mut bytes) + .map_err(Error::io("/dev/urandom"))?; + Ok(bytes.iter().fold(String::new(), |mut hex, byte| { + let _ = write!(hex, "{byte:02x}"); + hex + })) } /// The child's whole environment, besides what the supervisor adds. diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index 5def44bb..c9bb6fb5 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -1,6 +1,6 @@ //! Start-up verification and tool discovery, against the fake surface. -use super::{Layout, environment, turn_secs}; use super::verify::{discover, verify}; +use super::{Layout, environment, turn_secs}; use crate::error::Error; use crate::fixture::{Fixture, PID, SERVER, hashed_tools, served}; use std::collections::BTreeSet; @@ -9,9 +9,20 @@ use tinyhivemind_host::harness::Mismatch; const WARM: Duration = Duration::from_secs(5); -async fn verified(fixture: &Fixture, pid: u32) -> Result { +async fn verified( + fixture: &Fixture, + pid: u32, +) -> Result { let tools = hashed_tools(); - verify(&fixture.client, pid, "0.64.15", &fixture.written, &tools, WARM).await + verify( + &fixture.client, + pid, + "0.64.15", + &fixture.written, + &tools, + WARM, + ) + .await } #[tokio::test] @@ -20,7 +31,10 @@ async fn the_instance_that_was_written_is_verified_after_its_warm_up() { let started = verified(&fixture, PID).await; let started = started.unwrap_or_else(|error| unreachable!("verified: {error}")); assert_eq!(started.pid, PID); - assert_eq!(started.tools, hashed_tools().into_iter().collect::>()); + assert_eq!( + started.tools, + hashed_tools().into_iter().collect::>() + ); assert!(started.settings.contains("agent_registry.entries")); assert!(started.settings.contains("api_url")); } @@ -29,21 +43,30 @@ async fn the_instance_that_was_written_is_verified_after_its_warm_up() { async fn another_process_answering_is_refused() { let fixture = Fixture::new().await; let refused = verified(&fixture, PID + 1).await; - assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Pid { .. }))), "{refused:?}"); + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Pid { .. }))), + "{refused:?}" + ); } #[tokio::test] async fn another_version_is_refused() { let fixture = Fixture::with(&[("version", "0.64.14")]).await; let refused = verified(&fixture, PID).await; - assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Version { .. }))), "{refused:?}"); + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Version { .. }))), + "{refused:?}" + ); } #[tokio::test] async fn a_config_that_fell_back_to_defaults_is_refused() { let fixture = Fixture::with(&[("misconfigured", "")]).await; let refused = verified(&fixture, PID).await; - assert!(matches!(refused, Err(Error::Mismatch(Mismatch::Settings { .. }))), "{refused:?}"); + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Settings { .. }))), + "{refused:?}" + ); } #[tokio::test] @@ -57,12 +80,24 @@ async fn a_tool_the_model_would_see_besides_the_hive_tools_is_refused() { async fn a_hive_tool_the_model_would_not_see_is_refused() { let fixture = Fixture::with(&[("tools", "missing"), ("warm", "0")]).await; let tools = hashed_tools(); - let refused = verify(&fixture.client, PID, "0.64.15", &fixture.written, &tools, Duration::ZERO).await; - let Err(Error::Mismatch(Mismatch::Tools { missing, unexpected })) = refused else { + let refused = verify( + &fixture.client, + PID, + "0.64.15", + &fixture.written, + &tools, + Duration::ZERO, + ) + .await; + let Err(Error::Mismatch(Mismatch::Tools { + missing, + unexpected, + })) = refused + else { unreachable!("refused for its tools: {refused:?}") }; assert_eq!(missing, [tools[1].clone()]); - assert!(unexpected.is_empty()); + assert_eq!(unexpected, Vec::::new()); } #[tokio::test] @@ -116,7 +151,12 @@ fn the_environment_is_exactly_the_recipe_and_never_turns_the_sandbox_off() { "RUST_LOG", ] ); - let value = |name: &str| environment.iter().find(|(key, _)| *key == name).map(|(_, value)| value.as_str()); + let value = |name: &str| { + environment + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| value.as_str()) + }; assert_eq!(value("OPENHUMAN_WORKSPACE"), Some("/seat/state/ws")); assert_eq!(value("OPENHUMAN_KEYRING_BACKEND"), Some("encrypted_file")); assert_eq!(value("OPENHUMAN_BACKEND_API_KEY"), Some("dummy")); @@ -133,9 +173,13 @@ fn the_binary_lets_a_turn_run_past_the_seats_own_limit() { #[test] fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { let available = ["juice_retrieve".to_owned(), "mcp_s_post_1".to_owned()]; - let agent = serde_json::json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); + let agent = + serde_json::json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); let on = serde_json::json!({"agent_registry": {"entries": [agent.clone()]}}); - assert_eq!(super::verify::visible(&on, &available), ["mcp_s_post_1", "juice_retrieve"]); + assert_eq!( + super::verify::visible(&on, &available), + ["mcp_s_post_1", "juice_retrieve"] + ); let off = serde_json::json!({"agent_registry": {"entries": [agent]}, "context": {"compaction_enabled": false}}); assert_eq!(super::verify::visible(&off, &available), ["mcp_s_post_1"]); } @@ -143,6 +187,11 @@ fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { #[test] fn the_written_config_turns_compaction_off() { let settings = Fixture::written_for_test().settings(); - let compaction = settings.iter().find(|(name, _)| name == "context.compaction_enabled"); - assert_eq!(compaction.map(|(_, value)| value.clone()), Some(serde_json::json!(false))); + let compaction = settings + .iter() + .find(|(name, _)| name == "context.compaction_enabled"); + assert_eq!( + compaction.map(|(_, value)| value.clone()), + Some(serde_json::json!(false)) + ); } diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs index 1db729fc..ffc40913 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -14,9 +14,13 @@ const POLL: Duration = Duration::from_millis(100); /// Every tool name the instance offers. async fn available(client: &Client) -> Result> { - let listed = client.call("openhuman.agent_registry_available_tools", json!({})).await?; + let listed = client + .call("openhuman.agent_registry_available_tools", json!({})) + .await?; let tools = listed["tools"].as_array().cloned().unwrap_or_default(); - let names = tools.iter().filter_map(|tool| tool["name"].as_str().map(str::to_owned)); + let names = tools + .iter() + .filter_map(|tool| tool["name"].as_str().map(str::to_owned)); Ok(names.collect()) } @@ -46,7 +50,10 @@ pub(crate) async fn discover( let deadline = Instant::now() + warm_up; loop { let names = available(client).await?; - let found: Vec<_> = tools.iter().map(|tool| name_of(&names, server, tool)).collect(); + let found: Vec<_> = tools + .iter() + .map(|tool| name_of(&names, server, tool)) + .collect(); if found.iter().all(Option::is_some) { let mut found: Vec = found.into_iter().flatten().cloned().collect(); found.sort(); @@ -72,12 +79,17 @@ const RECOVERY: &str = "juice_retrieve"; /// binary defaults it to. pub(super) fn visible(config: &Value, available: &[String]) -> Vec { let entries = config["agent_registry"]["entries"].as_array().cloned(); - let agent = entries.unwrap_or_default().into_iter().find(|entry| entry["id"] == AGENT_ID); - let allowed = agent.map(|agent| agent["tool_allowlist"].clone()).unwrap_or(Value::Null); + let agent = entries + .unwrap_or_default() + .into_iter() + .find(|entry| entry["id"] == AGENT_ID); + let allowed = agent.map_or(Value::Null, |agent| agent["tool_allowlist"].clone()); let allowed = allowed.as_array().cloned().unwrap_or_default(); let names = allowed.iter().filter_map(Value::as_str); - let mut seen: Vec = - names.filter(|name| available.iter().any(|tool| tool == name)).map(str::to_owned).collect(); + let mut seen: Vec = names + .filter(|name| available.iter().any(|tool| tool == name)) + .map(str::to_owned) + .collect(); if config["context"]["compaction_enabled"] != false { seen.push(RECOVERY.to_owned()); } @@ -99,7 +111,9 @@ pub(crate) async fn verify( warm_up: Duration, ) -> Result { let health = client.health().await?; - let answering = health["pid"].as_u64().and_then(|pid| u32::try_from(pid).ok()); + let answering = health["pid"] + .as_u64() + .and_then(|pid| u32::try_from(pid).ok()); let running = client.call("core.version", json!({})).await?; let running = running["version"].as_str().unwrap_or_default().to_owned(); let snapshot = client.call("openhuman.config_get", json!({})).await?; diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs index feba8f53..d68df61b 100644 --- a/crates/tinyhivemind-openhuman-process/src/lib.rs +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -1,4 +1,4 @@ -//! Hive seats on OpenHuman, each a supervised `openhuman-core` process. +//! Hive seats on `OpenHuman`, each a supervised `openhuman-core` process. //! //! [`OpenHumanHarness`] implements the host's //! [`Harness`](tinyhivemind_host::harness::Harness) port for the `openhuman` @@ -35,7 +35,7 @@ //! # drop(runner); Ok(()) } //! ``` //! -//! What this crate does not hold: it names no OpenHuman type and links no +//! What this crate does not hold: it names no `OpenHuman` type and links no //! harness, so it outlives the linked adapter; it serves no tools (the host's //! MCP server does, and judges their policy); and it never downloads a //! binary: `.github/scripts/fetch-harness.sh` fetches the one pinned in @@ -50,11 +50,11 @@ mod turn; pub use harness::{OpenHumanHarness, Options, Program}; -#[cfg(test)] -#[path = "../tests/support/http.rs"] -mod http; #[cfg(test)] #[path = "../tests/fake/surface.rs"] mod fake; #[cfg(test)] mod fixture; +#[cfg(test)] +#[path = "../tests/support/http.rs"] +mod http; diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs index eee6c822..1d154a77 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs @@ -76,7 +76,10 @@ impl Client { let response = self.http.get(url).timeout(CALL).send().await?; let status = response.status().as_u16(); if status != 200 { - return Err(Error::Status { what: "/health", status }); + return Err(Error::Status { + what: "/health", + status, + }); } decode(&response.bytes().await?) } @@ -95,7 +98,10 @@ impl Client { .await?; let status = response.status().as_u16(); if status != 200 { - return Err(Error::Status { what: "/rpc", status }); + return Err(Error::Status { + what: "/rpc", + status, + }); } let mut answer = decode(&response.bytes().await?)?; if let Some(error) = answer.get("error").filter(|error| !error.is_null()) { @@ -120,7 +126,10 @@ impl Client { .await?; let status = response.status().as_u16(); if status != 200 { - return Err(Error::Status { what: "/events", status }); + return Err(Error::Status { + what: "/events", + status, + }); } Ok(Events { response, diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs index 02ce17e8..9ac143ce 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs @@ -33,7 +33,8 @@ impl Parser { } let line = String::from_utf8_lossy(&line); if let Some(data) = line.strip_prefix("data:") { - self.data.push(data.strip_prefix(' ').unwrap_or(data).to_owned()); + self.data + .push(data.strip_prefix(' ').unwrap_or(data).to_owned()); } } frames diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs index 84376ffc..e5e470a4 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -8,7 +8,10 @@ use serde_json::json; async fn health_reports_the_process_that_answers() { let fixture = Fixture::new().await; let health = fixture.client.health().await; - assert_eq!(health.ok().map(|health| health["pid"].clone()), Some(json!(PID))); + assert_eq!( + health.ok().map(|health| health["pid"].clone()), + Some(json!(PID)) + ); } #[tokio::test] @@ -48,7 +51,7 @@ async fn nobody_listening_is_a_transport_error() { let port = { let listener = std::net::TcpListener::bind("127.0.0.1:0"); let listener = listener.unwrap_or_else(|error| unreachable!("{error}")); - listener.local_addr().map(|address| address.port()).unwrap_or(1) + listener.local_addr().map_or(1, |address| address.port()) }; let client = Client::new(port, "t").unwrap_or_else(|error| unreachable!("{error}")); let refused = client.health().await; @@ -59,10 +62,20 @@ async fn nobody_listening_is_a_transport_error() { async fn events_are_those_of_the_subscribed_client_in_order() { let fixture = Fixture::new().await; fixture.script(&[json!({"reply": "hi", "tokens": 5})]); - let mut mine = fixture.client.events("mine").await.unwrap_or_else(|error| unreachable!("{error}")); + let mut mine = fixture + .client + .events("mine") + .await + .unwrap_or_else(|error| unreachable!("{error}")); let params = json!({"client_id": "mine", "thread_id": "t", "message": "go"}); - let ack = fixture.client.call("openhuman.channel_web_chat", params).await; - assert_eq!(ack.ok().map(|ack| ack["result"]["accepted"].clone()), Some(json!(true))); + let ack = fixture + .client + .call("openhuman.channel_web_chat", params) + .await; + assert_eq!( + ack.ok().map(|ack| ack["result"]["accepted"].clone()), + Some(json!(true)) + ); let mut names = Vec::new(); while let Ok(Some(event)) = mine.next().await { let name = event["event"].as_str().unwrap_or_default().to_owned(); @@ -72,27 +85,45 @@ async fn events_are_those_of_the_subscribed_client_in_order() { break; } } - assert_eq!(names, ["iteration_start", "text_delta", "turn_cost", "chat_done"]); + assert_eq!( + names, + ["iteration_start", "text_delta", "turn_cost", "chat_done"] + ); } #[tokio::test] async fn a_stream_the_server_drops_ends() { let fixture = Fixture::new().await; - let mut events = fixture.client.events("c").await.unwrap_or_else(|error| unreachable!("{error}")); + let mut events = fixture + .client + .events("c") + .await + .unwrap_or_else(|error| unreachable!("{error}")); drop(fixture); let ended = events.next().await; - assert!(matches!(ended, Ok(None) | Err(Error::Transport(_))), "{ended:?}"); + assert!( + matches!(ended, Ok(None) | Err(Error::Transport(_))), + "{ended:?}" + ); } #[test] fn sse_frames_split_anywhere_are_put_back_together() { - let text = ": keep-alive\n\nevent: a\ndata: {\"n\":\ndata: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; + let text = + ": keep-alive\n\nevent: a\ndata: {\"n\":\ndata: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; for split in 0..text.len() { let mut parser = Parser::default(); let mut found = parser.push(&text.as_bytes()[..split]); found.extend(parser.push(&text.as_bytes()[split..])); - let found: Vec<_> = found.into_iter().map(|frame| frame.map_err(|error| error.to_string())).collect(); - assert_eq!(found, [Ok(json!({"n": 1})), Ok(json!({"n": 2}))], "split at {split}"); + let found: Vec<_> = found + .into_iter() + .map(|frame| frame.map_err(|error| error.to_string())) + .collect(); + assert_eq!( + found, + [Ok(json!({"n": 1})), Ok(json!({"n": 2}))], + "split at {split}" + ); } } @@ -100,5 +131,8 @@ fn sse_frames_split_anywhere_are_put_back_together() { fn an_sse_frame_that_is_not_json_is_an_error() { let mut parser = Parser::default(); let found = parser.push(b"data: nope\n\n"); - assert!(matches!(found.as_slice(), [Err(Error::Decode(_))]), "{found:?}"); + assert!( + matches!(found.as_slice(), [Err(Error::Decode(_))]), + "{found:?}" + ); } diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs index a4d63230..cf628d5e 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -74,7 +74,8 @@ pub(crate) struct Turn<'a> { pub(crate) client: &'a Client, pub(crate) seat: &'a str, pub(crate) thread: &'a str, - pub(crate) turn_id: &'a str, + /// The coordinator's turn id. + pub(crate) id: &'a str, pub(crate) client_id: String, /// The seat's iteration limit, at most [`ITERATION_CAP`]. pub(crate) iterations: usize, @@ -103,9 +104,14 @@ pub(crate) async fn run( }; set(active, Some(submitted.clone())); let params = json!({"client_id": turn.client_id, "thread_id": turn.thread, "message": message}); - let ack = turn.client.call("openhuman.channel_web_chat", params).await?; + let ack = turn + .client + .call("openhuman.channel_web_chat", params) + .await?; let ack = &ack["result"]; - let request_id = ack["request_id"].as_str().filter(|_| ack["accepted"] == true); + let request_id = ack["request_id"] + .as_str() + .filter(|_| ack["accepted"] == true); let request_id = request_id.ok_or_else(|| Error::NotAccepted(ack.to_string()))?; submitted.request_id = Some(request_id.to_owned()); set(active, Some(submitted)); @@ -124,14 +130,10 @@ pub(crate) async fn run( /// Read events until the request ends, or fails while it runs on: whether /// the instance's turn is over. -async fn follow( - turn: &Turn<'_>, - request_id: &str, - events: &mut Events, -) -> Result<(Ended, bool)> { +async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Result<(Ended, bool)> { let mut iterations = 0_usize; let progress = |progress| Event::Progress { - turn_id: turn.turn_id.to_owned(), + turn_id: turn.id.to_owned(), progress, }; while let Some(event) = events.next().await? { @@ -163,7 +165,9 @@ async fn follow( } } "text_delta" if event["delta_kind"] == "text" => { - let delta = Progress::Text { delta: text("delta") }; + let delta = Progress::Text { + delta: text("delta"), + }; turn.observer.event(turn.seat, progress(delta)); } "tool_call" => { @@ -222,7 +226,7 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { let id = event["request_id"].as_str().unwrap_or_default().to_owned(); let request = ToolApproval { seat: turn.seat.to_owned(), - turn_id: turn.turn_id.to_owned(), + turn_id: turn.id.to_owned(), call_id: id.clone(), tool: event["tool_name"].as_str().unwrap_or_default().to_owned(), arguments: event["args"].clone(), @@ -232,7 +236,9 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { ToolDecision::Deny { .. } => "deny", }; let params = json!({"request_id": id, "decision": decision}); - turn.client.call("openhuman.approval_decide", params).await?; + turn.client + .call("openhuman.approval_decide", params) + .await?; Ok(()) } diff --git a/crates/tinyhivemind-openhuman-process/src/turn/test.rs b/crates/tinyhivemind-openhuman-process/src/turn/test.rs index 2a03d7b9..8e3a0826 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/test.rs @@ -14,7 +14,10 @@ struct Recorder(Mutex>); impl Observer for Recorder { fn event(&self, _: &str, event: Event) { - self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event); + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(event); } } @@ -61,7 +64,7 @@ impl Harnessed { client: &self.fixture.client, seat: "scout", thread: "thm-scout", - turn_id: "t1", + id: "t1", client_id: "thm-1".into(), iterations, observer: self.events.as_ref(), @@ -93,11 +96,14 @@ async fn a_turn_ends_with_its_reply_and_its_own_usage() { assert_eq!(ended.ok(), Some(expected)); // Published before `channel_web_chat` answered, and still seen. let progress = harnessed.events.progress(); - assert_eq!(progress.first(), Some(&Progress::ModelCall { iteration: 1 })); + assert_eq!( + progress.first(), + Some(&Progress::ModelCall { iteration: 1 }) + ); assert!(progress.contains(&Progress::Text { delta: "done".into() })); - assert!(harnessed.active.lock().ok().is_some_and(|active| active.is_none())); + assert!(harnessed.active.lock().is_ok_and(|active| active.is_none())); } #[tokio::test] @@ -105,7 +111,10 @@ async fn another_requests_events_are_not_this_turns() { let step = json!({"reply": "mine", "tokens": 1, "stray": true}); let harnessed = Harnessed::new(&[step]).await; let ended = harnessed.run(8).await; - assert_eq!(ended.ok().and_then(|ended| ended.reply), Some("mine".into())); + assert_eq!( + ended.ok().and_then(|ended| ended.reply), + Some("mine".into()) + ); } #[tokio::test] @@ -142,13 +151,19 @@ async fn a_seat_limit_below_the_cap_fails_the_turn_past_it() { #[tokio::test] async fn a_harness_approval_is_decided_by_the_approver() { let step = json!({"reply": "after", "approval": "shell"}); - let harnessed = Harnessed::new(&[step.clone()]).await; + let harnessed = Harnessed::new(std::slice::from_ref(&step)).await; assert!(harnessed.run(8).await.is_ok()); let allowed = Harnessed::new(&[step]).await; - assert!(run(allowed.turn(&AllowAll, 8), "go", &allowed.active).await.is_ok()); + assert!( + run(allowed.turn(&AllowAll, 8), "go", &allowed.active) + .await + .is_ok() + ); let decided = |harnessed: &Harnessed| { let log = harnessed.fixture.log("decisions.jsonl"); - log.iter().map(|entry| entry["decision"].clone()).collect::>() + log.iter() + .map(|entry| entry["decision"].clone()) + .collect::>() }; assert_eq!(decided(&harnessed), [json!("deny")]); assert_eq!(decided(&allowed), [json!("approve_once")]); @@ -168,7 +183,10 @@ async fn a_tool_call_and_its_result_are_progress() { call_id: "call_1".into(), failed: true, }; - assert!(progress.contains(&call) && progress.contains(&result), "{progress:?}"); + assert!( + progress.contains(&call) && progress.contains(&result), + "{progress:?}" + ); } #[tokio::test] @@ -180,7 +198,11 @@ async fn a_cancelled_turn_is_shown_to_have_stopped() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; } task.abort(); - let active = harnessed.active.lock().ok().and_then(|mut active| active.take()); + let active = harnessed + .active + .lock() + .ok() + .and_then(|mut active| active.take()); let active = active.unwrap_or_else(|| unreachable!("a dropped turn leaves itself")); assert!(active.request_id.is_some()); let cancelled = cancel(&harnessed.fixture.client, &active).await; diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index dbac896b..4ec3f5e5 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -65,7 +65,7 @@ async fn a_seat_it_cannot_honour_is_refused_before_anything_starts() -> Result<( }; let refusal = refusal.downcast_ref::(); assert_eq!(refusal, Some(&Refusal::Iterations { asked: 20, cap: 8 })); - assert!(subject.processes().is_empty()); + assert_eq!(subject.processes(), Vec::::new()); Ok(()) } @@ -78,7 +78,7 @@ async fn a_running_seat_is_not_started_twice_and_a_stopped_one_is_already_stoppe assert!(matches!(again, Err(Error::Harness(reason)) if reason.contains("already running"))); harness.stop("scout").await?; harness.stop("scout").await?; - assert!(subject.processes().is_empty()); + assert_eq!(subject.processes(), Vec::::new()); drop(runner); Ok(()) } diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs index 9b1df9c7..dd157eea 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs @@ -39,7 +39,9 @@ fn main() -> ExitCode { ) else { return ExitCode::from(2); }; - let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); let Ok(runtime) = runtime else { return ExitCode::FAILURE; }; diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs index 8fa7fc40..199144d9 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -8,8 +8,8 @@ use std::collections::BTreeMap; use std::fs; use std::os::unix::fs::PermissionsExt as _; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use tinyhivemind_host::harness::conformance::{ CallState, EscapeFuture, ModelCall, ModelStep, Subject, ToolFault, diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index c5a122f2..208acbcd 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -72,7 +72,7 @@ impl Fake { let serving = state.clone(); let task = tokio::spawn(serve(listener, move |request| { let state = serving.clone(); - async move { state.handle(request).await } + async move { state.handle(&request) } })); Self { port, task, state } } @@ -138,7 +138,7 @@ impl State { } } - async fn handle(self: Arc, request: Request) -> Reply { + fn handle(self: Arc, request: &Request) -> Reply { if request.method == "GET" && request.path == "/health" { let health = json!({"pid": self.setup.pid, "healthy": true, "components": {}}); return Reply::Json(200, health); @@ -148,14 +148,14 @@ impl State { return Reply::Json(401, json!({"ok": false, "error": "unauthorized"})); } match (request.method.as_str(), request.path.as_str()) { - ("GET", "/events") => self.subscribe(&request), + ("GET", "/events") => self.subscribe(request), ("POST", "/rpc") => { let body = request.json(); let id = body["id"].clone(); let method = body["method"].as_str().unwrap_or_default().to_owned(); self.append("methods.jsonl", &json!(method)); let params = body["params"].clone(); - let answer = match self.clone().call(&method, ¶ms).await { + let answer = match self.clone().call(&method, ¶ms) { Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), Err(message) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": message, "data": null}}), @@ -189,7 +189,7 @@ impl State { } } - async fn call(self: Arc, method: &str, params: &Value) -> Result { + fn call(self: Arc, method: &str, params: &Value) -> Result { let envelope = |result: Value| json!({"logs": ["fake"], "result": result}); match method { "core.version" => { @@ -224,7 +224,10 @@ impl State { fn tools(&self) -> Vec { let builtin = ["shell", "mcp_call_tool", "juice_retrieve"]; let mut tools: Vec = builtin.map(String::from).to_vec(); - let warm: usize = self.read("warm").and_then(|n| n.trim().parse().ok()).unwrap_or(2); + let warm: usize = self + .read("warm") + .and_then(|n| n.trim().parse().ok()) + .unwrap_or(2); if self.listed.fetch_add(1, Ordering::Relaxed) >= warm { let mut served: Vec = self .read("served") @@ -241,31 +244,61 @@ impl State { } } } - let tools = tools.into_iter().map(|name| json!({"name": name, "description": ""})); + let tools = tools + .into_iter() + .map(|name| json!({"name": name, "description": ""})); tools.collect() } fn transcript(&self, thread: &str) -> PathBuf { let safe: String = thread .chars() - .map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }) + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) .collect(); - self.setup.workspace.join("workspace/session_raw").join(format!("{safe}.jsonl")) + self.setup + .workspace + .join("workspace/session_raw") + .join(format!("{safe}.jsonl")) } fn chat(self: Arc, params: &Value) -> Result { - let known = ["client_id", "thread_id", "message", "model_override", "queue_mode"]; + let known = [ + "client_id", + "thread_id", + "message", + "model_override", + "queue_mode", + ]; for key in params.as_object().into_iter().flatten().map(|(key, _)| key) { if !known.contains(&key.as_str()) { return Err(format!("unknown param '{key}' for channel.web_chat")); } } - let agent = self.config["agent"]["chat_agent_id"].as_str().unwrap_or("orchestrator"); + let agent = self.config["agent"]["chat_agent_id"] + .as_str() + .unwrap_or("orchestrator"); let entries = self.config["agent_registry"]["entries"].as_array().cloned(); - if !entries.unwrap_or_default().iter().any(|entry| entry["id"] == agent) { - return Err(format!("chat_agent_id '{agent}' is not a runnable agent definition")); + if !entries + .unwrap_or_default() + .iter() + .any(|entry| entry["id"] == agent) + { + return Err(format!( + "chat_agent_id '{agent}' is not a runnable agent definition" + )); } - let text = |key: &str| params[key].as_str().filter(|text| !text.is_empty()).map(str::to_owned); + let text = |key: &str| { + params[key] + .as_str() + .filter(|text| !text.is_empty()) + .map(str::to_owned) + }; let (Some(client), Some(thread), Some(message)) = (text("client_id"), text("thread_id"), text("message")) else { @@ -287,7 +320,11 @@ impl State { self.publish(&client, &thread, &request_id, "iteration_start", first); let ack = json!({"accepted": true, "client_id": client, "thread_id": thread, "request_id": request_id}); - let ids = Ids { client, thread, request_id }; + let ids = Ids { + client, + thread, + request_id, + }; tokio::spawn(async move { self.run(ids, message, cancel).await }); Ok(ack) } @@ -299,7 +336,11 @@ impl State { let target = in_flight .get(thread) .is_some_and(|flight| scoped.is_none_or(|id| id == flight.request_id)); - let cancelled = if target { in_flight.remove(thread) } else { None }; + let cancelled = if target { + in_flight.remove(thread) + } else { + None + }; let request_id = cancelled.as_ref().map(|flight| flight.request_id.clone()); if let Some(flight) = cancelled { flight.cancel.notify_one(); @@ -361,13 +402,19 @@ impl State { if step.is_null() { cancel.notified().await; self.append("calls.jsonl", &json!({"call": call, "state": "aborted"})); - say("chat_error", json!({"message": "Cancelled", "error_type": "cancelled"})); + say( + "chat_error", + json!({"message": "Cancelled", "error_type": "cancelled"}), + ); return; } self.append("calls.jsonl", &json!({"call": call, "state": "answered"})); self.finish(&ids.thread, &ids.request_id); if let Some(error) = step["error"].as_str() { - say("chat_error", json!({"message": error, "error_type": "inference"})); + say( + "chat_error", + json!({"message": error, "error_type": "inference"}), + ); return; } let reply = step["reply"].as_str().unwrap_or_default(); @@ -375,7 +422,10 @@ impl State { let tokens = step["tokens"].as_u64().unwrap_or(0); let usage = json!({"input_tokens": tokens, "output_tokens": 2, "cached_input_tokens": tokens / 10, "cost_usd": 0.0, "context_window": 0}); - say("text_delta", json!({"delta": reply, "delta_kind": "text", "round": 1})); + say( + "text_delta", + json!({"delta": reply, "delta_kind": "text", "round": 1}), + ); say("turn_cost", json!({"usage": usage, "round": 1})); say("chat_done", json!({"full_response": reply, "usage": usage})); } @@ -383,7 +433,10 @@ impl State { /// The turn on `thread` ended, unless a newer one replaced it. fn finish(&self, thread: &str, request_id: &str) { let mut in_flight = lock(&self.in_flight); - if in_flight.get(thread).is_some_and(|flight| flight.request_id == request_id) { + if in_flight + .get(thread) + .is_some_and(|flight| flight.request_id == request_id) + { in_flight.remove(thread); } } @@ -399,7 +452,9 @@ impl State { let _ = writeln!(file, "{}", json!({"role": role, "text": text})); } let text = fs::read_to_string(&path).unwrap_or_default(); - text.lines().filter(|line| line.contains("\"user\"")).count() + text.lines() + .filter(|line| line.contains("\"user\"")) + .count() } fn open(&self, seen: usize) -> u64 { diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs index b392351e..f984adbd 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -63,7 +63,10 @@ struct Recorder(Mutex>); impl Observer for Recorder { fn event(&self, _: &str, event: Event) { - self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event); + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(event); } } @@ -119,14 +122,25 @@ async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { assert_eq!(outcome.disposition, TurnDisposition::Completed); assert_eq!(outcome.reply.as_deref(), Some("MOCK_REPLY turns=1")); let entries: Vec = fixture.entries().split_off(since); - let calls: Vec<&Value> = entries.iter().filter(|entry| entry["rpc"] == "tools/call").collect(); + let calls: Vec<&Value> = entries + .iter() + .filter(|entry| entry["rpc"] == "tools/call") + .collect(); assert_eq!(calls.len(), 1, "{entries:?}"); assert_eq!(calls[0]["seat"], "a"); - let models: Vec<&Value> = entries.iter().filter(|entry| entry["kind"] == "model").collect(); - let started = events.0.lock().unwrap_or_else(PoisonError::into_inner).iter().find_map(|event| match event { - Event::Started(started) => Some(started.clone()), - _ => None, - }); + let models: Vec<&Value> = entries + .iter() + .filter(|entry| entry["kind"] == "model") + .collect(); + let started = events + .0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find_map(|event| match event { + Event::Started(started) => Some(started.clone()), + _ => None, + }); let started = started.context("no started event")?; assert_eq!(started.version, PINNED); let offered: Vec = started.tools.iter().map(|tool| json!(tool)).collect(); @@ -134,31 +148,49 @@ async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { for model in &models { assert_eq!(model["tools"], json!(offered), "the model saw other tools"); } - let usage = events.0.lock().unwrap_or_else(PoisonError::into_inner).iter().find_map(|event| match event { - Event::Usage { turn_id, usage } if turn_id == "t1" => Some(*usage), - _ => None, - }); + let usage = events + .0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find_map(|event| match event { + Event::Usage { turn_id, usage } if turn_id == "t1" => Some(*usage), + _ => None, + }); assert_eq!(usage.map(|usage| usage.input_tokens), Some(200)); let session = outcome.session_id; let slow = tokio::spawn(runner.run(request("t2", "SLOW please", Some(&session)))); let deadline = tokio::time::Instant::now() + Duration::from_secs(30); while !fixture.entries().iter().any(|entry| entry["key"] == "SLOW") { - anyhow::ensure!(tokio::time::Instant::now() < deadline, "the slow turn never reached the model"); + anyhow::ensure!( + tokio::time::Instant::now() < deadline, + "the slow turn never reached the model" + ); tokio::time::sleep(Duration::from_millis(20)).await; } slow.abort(); - while !fixture.entries().iter().any(|entry| entry["kind"] == "model-disconnect") { - anyhow::ensure!(tokio::time::Instant::now() < deadline, "the dropped turn kept its model call open"); + while !fixture + .entries() + .iter() + .any(|entry| entry["kind"] == "model-disconnect") + { + anyhow::ensure!( + tokio::time::Instant::now() < deadline, + "the dropped turn kept its model call open" + ); tokio::time::sleep(Duration::from_millis(20)).await; } - let again = runner.run(request("t3", "PLAIN again", Some(&session))).await?; + let again = runner + .run(request("t3", "PLAIN again", Some(&session))) + .await?; // The same thread, without the cancelled turn's message: the binary keeps // only turns that ended, as the spike saw too. assert_eq!(again.reply.as_deref(), Some("MOCK_REPLY turns=2")); assert_eq!(again.session_id, session); harness.stop("scout").await?; - assert!(seat_support::processes_in(&root.path().join("instance")).is_empty()); + let left = seat_support::processes_in(&root.path().join("instance")); + assert_eq!(left, Vec::::new()); Ok(()) } diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs index d73602c5..c7448352 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/model.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -60,17 +60,26 @@ impl Drop for ScriptedModel { fn answer(state: &Arc, request: &Request) -> Reply { if request.method == "GET" && request.path.ends_with("/models") { - return Reply::Json(200, json!({"object": "list", "data": [{"id": "mock", "object": "model"}]})); + return Reply::Json( + 200, + json!({"object": "list", "data": [{"id": "mock", "object": "model"}]}), + ); } if !request.path.ends_with("/chat/completions") { return Reply::Json(404, json!({})); } let body = request.json(); let messages = body["messages"].as_array().cloned().unwrap_or_default(); - let seen = messages.iter().filter(|message| message["role"] == "user").count(); + let seen = messages + .iter() + .filter(|message| message["role"] == "user") + .count(); let index = { let mut calls = lock(&state.calls); - calls.push(ModelCall { seen, state: CallState::Open }); + calls.push(ModelCall { + seen, + state: CallState::Open, + }); calls.len() - 1 }; let step = lock(&state.steps).pop_front().unwrap_or(ModelStep::Hang); @@ -108,8 +117,14 @@ fn answer(state: &Arc, request: &Request) -> Reply { format!("data: {chunk}\n\n") }; let frames = [ - chunk(json!([{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]), None), - chunk(json!([{"index": 0, "delta": {}, "finish_reason": "stop"}]), None), + chunk( + json!([{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]), + None, + ), + chunk( + json!([{"index": 0, "delta": {}, "finish_reason": "stop"}]), + None, + ), chunk(json!([]), Some(usage)), "data: [DONE]\n\n".to_owned(), ]; diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs index 4bcedc4a..ca9f547e 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -9,7 +9,9 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering}; use std::time::Duration; -use tinyhivemind_host::harness::conformance::{EscapeFuture, ModelCall, ModelStep, Subject, ToolFault}; +use tinyhivemind_host::harness::conformance::{ + EscapeFuture, ModelCall, ModelStep, Subject, ToolFault, +}; use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; use tinyhivemind_host::process::StopPolicy; use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; @@ -26,7 +28,9 @@ pub(crate) fn requirements() -> Result<(PathBuf, PathBuf), String> { .ok_or("THM_OPENHUMAN_CORE is not set to the pinned openhuman-core")?; let node = std::env::var_os("THM_NODE").map(PathBuf::from).or_else(|| { let path = std::env::var_os("PATH")?; - std::env::split_paths(&path).map(|dir| dir.join("node")).find(|node| node.is_file()) + std::env::split_paths(&path) + .map(|dir| dir.join("node")) + .find(|node| node.is_file()) }); let node = node.ok_or("node is neither THM_NODE nor on PATH, and the fixture needs it")?; Ok((binary, node)) @@ -42,7 +46,9 @@ pub(crate) struct Fixture { impl Fixture { pub(crate) async fn start(node: &Path, dir: &Path) -> std::io::Result { - let port = std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let port = std::net::TcpListener::bind("127.0.0.1:0")? + .local_addr()? + .port(); let script = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../docs/experiments/2026-11-25-process-harnesses/fixture/server.mjs"); let log = dir.join("fixture.jsonl"); @@ -57,7 +63,11 @@ impl Fixture { let mut lines = BufReader::new(stdout).lines(); while let Some(line) = lines.next_line().await? { if line.trim() == "ready" { - return Ok(Self { port, log, _child: child }); + return Ok(Self { + port, + log, + _child: child, + }); } } Err(std::io::ErrorKind::UnexpectedEof.into()) @@ -153,7 +163,12 @@ impl Subject for LiveSubject { fn lose_sessions(&self) { let workspace = self.instance().join("state/ws/workspace"); - for store in ["session_raw", "sessions", "session_db", "memory/conversations"] { + for store in [ + "session_raw", + "sessions", + "session_db", + "memory/conversations", + ] { let _ = fs::remove_dir_all(workspace.join(store)); } } @@ -169,7 +184,11 @@ impl Subject for LiveSubject { }; self.fault.store(code, Ordering::Relaxed); let marker = self.root.path().join("misconfigured"); - let _ = if misconfigured { fs::write(marker, "") } else { fs::remove_file(marker) }; + let _ = if misconfigured { + fs::write(marker, "") + } else { + fs::remove_file(marker) + }; } fn misconfigure(&self) { diff --git a/crates/tinyhivemind-openhuman-process/tests/support/http.rs b/crates/tinyhivemind-openhuman-process/tests/support/http.rs index 8f85bc2f..7145bb72 100644 --- a/crates/tinyhivemind-openhuman-process/tests/support/http.rs +++ b/crates/tinyhivemind-openhuman-process/tests/support/http.rs @@ -27,7 +27,10 @@ pub(crate) struct Request { impl Request { /// The header `name`, case-insensitively. pub(crate) fn header(&self, name: &str) -> Option<&str> { - let found = self.headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)); + let found = self + .headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)); found.map(|(_, value)| value.as_str()) } diff --git a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs index 8e29aed9..b706df10 100644 --- a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs +++ b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs @@ -66,4 +66,3 @@ pub(crate) fn kill_all(pids: Vec) { } } } - From 8fb62c5483d55c7ac125fd403aa84706b344a87a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:21:26 +0000 Subject: [PATCH 40/49] refactor(tinyhivemind-openhuman-process): move error module into a directory The crate's error type now lives in an `error/` module directory with its own README and test module, and the crate README points at the new location. A test was added covering the TOML writer's handling of nulls, empty arrays, mixed arrays, and nested tables. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/README.md | 2 +- .../src/config/test.rs | 23 +++++++ .../src/error/README.md | 12 ++++ .../src/{error.rs => error/mod.rs} | 3 + .../src/error/test.rs | 67 +++++++++++++++++++ 5 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 crates/tinyhivemind-openhuman-process/src/error/README.md rename crates/tinyhivemind-openhuman-process/src/{error.rs => error/mod.rs} (99%) create mode 100644 crates/tinyhivemind-openhuman-process/src/error/test.rs diff --git a/crates/tinyhivemind-openhuman-process/src/README.md b/crates/tinyhivemind-openhuman-process/src/README.md index 87fd8641..b515e2cc 100644 --- a/crates/tinyhivemind-openhuman-process/src/README.md +++ b/crates/tinyhivemind-openhuman-process/src/README.md @@ -3,7 +3,7 @@ | Path | Purpose | | --- | --- | | `lib.rs` | Crate overview and public surface: `OpenHumanHarness`, `Program`, `Options`, `capability`. | -| `error.rs` | The crate's internal `Error`, and how it reaches the port as `harness::Error`. | +| [`error/`](error/README.md) | The crate's internal `Error`, and how it reaches the port as `harness::Error`. | | `fixture.rs` | Unit tests only: the in-process fake surface with a written config, and a client. | | [`capability/`](capability/README.md) | What a lowered seat may ask of this harness: `check`, `Refusal`, `SeatModel`. | | [`config/`](config/README.md) | The generated `config.toml`, and comparing an effective config with it. | diff --git a/crates/tinyhivemind-openhuman-process/src/config/test.rs b/crates/tinyhivemind-openhuman-process/src/config/test.rs index e39cf95a..353e0c57 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/test.rs @@ -187,3 +187,26 @@ fn an_effective_config_that_differs_anywhere_written_is_another_one() { assert_ne!(written.observe(&config), written.settings(), "{config}"); } } + +#[test] +fn the_writer_leaves_out_null_and_writes_other_shapes_inline() { + let tree = json!({ + "gone": null, + "empty": [], + "mixed": [1, {"a": "b"}], + "table": {"inner": {"deep": true}}, + }); + let text = super::toml::write(&tree); + assert!(!text.contains("gone"), "{text}"); + let table: ::toml::Table = text + .parse() + .unwrap_or_else(|error| unreachable!("{error}\n{text}")); + let parsed = serde_json::to_value(table).unwrap_or_else(|error| unreachable!("{error}")); + let expected = json!({ + "empty": [], + "mixed": [1, {"a": "b"}], + "table": {"inner": {"deep": true}}, + }); + assert_eq!(parsed, expected); + assert_eq!(super::toml::write(&json!("not a table")), ""); +} diff --git a/crates/tinyhivemind-openhuman-process/src/error/README.md b/crates/tinyhivemind-openhuman-process/src/error/README.md new file mode 100644 index 00000000..bdf14a8e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error/README.md @@ -0,0 +1,12 @@ +# Errors + +The crate's internal `Error`. At the port a refusal becomes +`harness::Error::Refused` holding the `capability::Refusal`, supervision, +mismatch and resume failures keep the port's own variants, and the rest +become `harness::Error::Harness` with their message. No message holds a token, +a bearer or a config value. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Error`, `Result` and the conversion | +| `test.rs` | Every variant through the port | diff --git a/crates/tinyhivemind-openhuman-process/src/error.rs b/crates/tinyhivemind-openhuman-process/src/error/mod.rs similarity index 99% rename from crates/tinyhivemind-openhuman-process/src/error.rs rename to crates/tinyhivemind-openhuman-process/src/error/mod.rs index c22d148f..61029106 100644 --- a/crates/tinyhivemind-openhuman-process/src/error.rs +++ b/crates/tinyhivemind-openhuman-process/src/error/mod.rs @@ -70,3 +70,6 @@ impl From for harness::Error { } } } + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/error/test.rs b/crates/tinyhivemind-openhuman-process/src/error/test.rs new file mode 100644 index 00000000..b7eda967 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error/test.rs @@ -0,0 +1,67 @@ +//! How each failure reaches the port. +use super::Error; +use crate::capability::Refusal; +use tinyhivemind_host::harness::{self, Mismatch}; + +#[test] +fn a_refusal_stays_typed_through_the_port() { + let error: harness::Error = Error::from(Refusal::Budget).into(); + let harness::Error::Refused(refusal) = error else { + unreachable!("refused") + }; + assert_eq!(refusal.downcast_ref::(), Some(&Refusal::Budget)); +} + +#[test] +fn supervision_mismatch_and_resume_keep_the_ports_own_variants() { + let process: harness::Error = Error::from(tinyhivemind_host::process::Error::Unproven).into(); + assert!(matches!(process, harness::Error::Process(_))); + let mismatch = Mismatch::Pid { + expected: 1, + found: 2, + }; + let mismatch: harness::Error = Error::from(mismatch).into(); + assert!(matches!( + mismatch, + harness::Error::Mismatch(Mismatch::Pid { .. }) + )); + let resume: harness::Error = Error::Resume("thm-scout".into()).into(); + let harness::Error::Resume { session_id, reason } = resume else { + unreachable!("a resume failure") + }; + assert_eq!(session_id, "thm-scout"); + assert_eq!(reason, "the instance has no thread thm-scout"); +} + +#[test] +fn everything_else_is_a_harness_failure_with_its_message() { + let cases = [ + ( + Error::ToolsNotListed { + server: "hivemind".into(), + missing: vec!["hivemind_ask".into()], + }, + "the instance did not list [\"hivemind_ask\"] of server hivemind", + ), + ( + Error::io("the config")(std::io::Error::other("disk full")), + "the config: disk full", + ), + ( + Error::Render("bad request".into()), + "the turn could not be rendered: bad request", + ), + ( + Error::from(crate::turn::Error::StreamEnded), + "the event stream ended before the turn did", + ), + ( + Error::from(crate::rpc::Error::Decode("eof".into())), + "the instance answered with something unreadable: eof", + ), + ]; + for (error, message) in cases { + let error: harness::Error = error.into(); + assert_eq!(error.to_string(), format!("harness failed: {message}")); + } +} From 004ab8dd3dd9fee5f28df53771a56bc65f81fdf4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:29:39 +0000 Subject: [PATCH 41/49] test(instance): cover every tool source the start check must see Add a test asserting that the start check counts tools contributed by deferred tool search, the REPL handle tools, the orchestrator summary stage, extra_tools, and subagent delegation, matching what resolved_scope adds to an allowlist. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/instance/test.rs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index c9bb6fb5..ad176380 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -195,3 +195,60 @@ fn the_written_config_turns_compaction_off() { Some(serde_json::json!(false)) ); } + +/// What `resolved_scope` in 0.64.15's `definition_registry.rs` adds to an +/// allowlist, each of which the start check must see. +#[test] +fn every_source_the_binary_adds_tools_from_is_counted() { + use serde_json::json; + let available: Vec = ["mcp_s_post_1", "tool_search", "juice_retrieve", "juice_find", "juice_extract", "juice_summarize", "shell"] + .map(String::from) + .to_vec(); + let entry = |extra: serde_json::Value| { + let mut entry = json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); + if let (Some(entry), Some(extra)) = (entry.as_object_mut(), extra.as_object()) { + entry.extend(extra.clone()); + } + entry + }; + let config = |entry: serde_json::Value, rest: serde_json::Value| { + let mut config = json!({ + "agent_registry": {"entries": [entry]}, + "context": {"compaction_enabled": false}, + "agent": {"chat_agent_id": crate::config::AGENT_ID}, + }); + if let (Some(config), Some(rest)) = (config.as_object_mut(), rest.as_object()) { + for (key, value) in rest { + config.insert(key.clone(), value.clone()); + } + } + config + }; + let seen = |config: &serde_json::Value| super::verify::visible(config, &available); + assert_eq!(seen(&config(entry(json!({})), json!({}))), ["mcp_s_post_1"]); + // Deferred tools, when the allowlist names the tool search. + let search = entry(json!({"tool_allowlist": ["mcp_s_post_1", "tool_search"]})); + assert!(seen(&config(search, json!({}))).iter().any(|tool| tool.contains("deferred"))); + // The REPL tools, while results are stored behind a handle. + let repl = json!({ + "context": {"compaction_enabled": true}, + "tokenjuice": {"router_enabled": true, "ccr_enabled": true, "repl_handle_enabled": true}, + }); + let repl = seen(&config(entry(json!({})), repl)); + for tool in ["juice_retrieve", "juice_find", "juice_extract", "juice_summarize"] { + assert!(repl.contains(&tool.to_owned()), "{tool} in {repl:?}"); + } + // The summary stage, which only the orchestrator gets. + let orchestrator = json!({"id": "orchestrator", "tool_allowlist": ["mcp_s_post_1"]}); + let summary = json!({ + "agent": {"chat_agent_id": "orchestrator"}, + "context": {"compaction_enabled": false, "summarizer_payload_threshold_tokens": 100}, + }); + let summary = seen(&config(orchestrator, summary)); + assert!(summary.contains(&"juice_retrieve".to_owned()), "{summary:?}"); + // `extra_tools`, and a session's delegation tools for an agent with subagents. + let extra = seen(&config(entry(json!({"extra_tools": ["shell"]})), json!({}))); + assert!(extra.contains(&"shell".to_owned()), "{extra:?}"); + let delegating = seen(&config(entry(json!({"subagents": ["helper"]})), json!({}))); + assert!(delegating.iter().any(|tool| tool.contains("delegation")), "{delegating:?}"); +} From 75fdc8f0f5242d5f234e8752f26f21b8be3dff5a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:31:11 +0000 Subject: [PATCH 42/49] fix(openhuman-process): resolve visible tools from the chat agent's allowlist The visible-tool check now looks up the configured chat agent instead of a fixed id, and mirrors 0.64.15's resolved_scope by adding deferred, delegation, recovery and REPL tools under the conditions the binary uses. This keeps the live tests honest about what the model actually sees. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/instance/test.rs | 8 +- .../src/instance/verify.rs | 85 ++++++++++++++----- 2 files changed, 72 insertions(+), 21 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index ad176380..2c411f3e 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -175,13 +175,17 @@ fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { let available = ["juice_retrieve".to_owned(), "mcp_s_post_1".to_owned()]; let agent = serde_json::json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); - let on = serde_json::json!({"agent_registry": {"entries": [agent.clone()]}}); + let chat = serde_json::json!({"chat_agent_id": crate::config::AGENT_ID}); + let on = serde_json::json!({"agent": chat, "agent_registry": {"entries": [agent.clone()]}}); assert_eq!( super::verify::visible(&on, &available), ["mcp_s_post_1", "juice_retrieve"] ); - let off = serde_json::json!({"agent_registry": {"entries": [agent]}, "context": {"compaction_enabled": false}}); + let off = serde_json::json!({"agent": chat, "agent_registry": {"entries": [agent]}, "context": {"compaction_enabled": false}}); assert_eq!(super::verify::visible(&off, &available), ["mcp_s_post_1"]); + // Another chat agent is a built-in one, whose tools are not these. + let other = serde_json::json!({"agent_registry": {"entries": []}}); + assert_eq!(super::verify::visible(&other, &available), [""]); } #[test] diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs index ffc40913..c74a4c2d 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -70,30 +70,77 @@ pub(crate) async fn discover( } } -/// The tool 0.64.15 adds to any allowlist while tool-output compaction is -/// on, so that the model can recover a compacted result. +/// The recovery tool 0.64.15 adds to a non-empty allowlist while tool +/// output can be compacted or summarized. const RECOVERY: &str = "juice_retrieve"; +/// The tools it adds while results are stored behind a handle. +const REPL: [&str; 3] = ["juice_find", "juice_extract", "juice_summarize"]; +/// The tool whose presence in an allowlist adds every deferred tool. +const TOOL_SEARCH: &str = "tool_search"; +/// Stand-ins for tools only a running session knows the names of. None is +/// ever expected, so any of them fails the check. +const DEFERRED: &str = ""; +const DELEGATION: &str = ""; -/// The tools the model sees: the agent's effective allowlist, of those the -/// instance has, and the recovery tool unless compaction is off, which the -/// binary defaults it to. +fn enabled(value: &Value) -> bool { + // A switch the snapshot leaves out is the binary's default, on. + value != false +} + +/// The tools the model sees, computed as 0.64.15's `resolved_scope` does +/// (`agent/tinyagents/host/definition_registry.rs`): the chat agent's +/// allowlist, of the tools the instance has; every deferred tool if it names +/// `tool_search`; the session's delegation tools for an agent with +/// subagents; the recovery tool while compaction or the orchestrator's +/// summary stage is on, and the REPL tools while results are stored behind a +/// handle, both only for a non-empty allowlist; and `extra_tools`. No RPC +/// reports the set, so the live tests check it at the model. pub(super) fn visible(config: &Value, available: &[String]) -> Vec { + let agent = config["agent"]["chat_agent_id"].as_str().unwrap_or("orchestrator"); let entries = config["agent_registry"]["entries"].as_array().cloned(); - let agent = entries - .unwrap_or_default() - .into_iter() - .find(|entry| entry["id"] == AGENT_ID); - let allowed = agent.map_or(Value::Null, |agent| agent["tool_allowlist"].clone()); - let allowed = allowed.as_array().cloned().unwrap_or_default(); - let names = allowed.iter().filter_map(Value::as_str); - let mut seen: Vec = names - .filter(|name| available.iter().any(|tool| tool == name)) - .map(str::to_owned) - .collect(); - if config["context"]["compaction_enabled"] != false { - seen.push(RECOVERY.to_owned()); + let Some(entry) = entries.unwrap_or_default().into_iter().find(|entry| entry["id"] == agent) + else { + return vec![format!("")]; + }; + let has = |name: &str| available.iter().any(|tool| tool == name); + let list = |key: &str| { + let names = entry[key].as_array().cloned().unwrap_or_default(); + names.iter().filter_map(Value::as_str).map(str::to_owned).collect::>() + }; + let allowed = list("tool_allowlist"); + let mut seen: Vec = allowed.iter().filter(|name| has(name)).cloned().collect(); + if allowed.iter().any(|name| name == TOOL_SEARCH) { + seen.push(DEFERRED.to_owned()); + } + if !list("subagents").is_empty() { + seen.push(DELEGATION.to_owned()); + } + let compaction = enabled(&config["context"]["compaction_enabled"]); + let threshold = &config["context"]["summarizer_payload_threshold_tokens"]; + let summarizes = agent == "orchestrator" && threshold.as_u64() != Some(0); + let juice = &config["tokenjuice"]; + let repl = compaction + && enabled(&juice["router_enabled"]) + && enabled(&juice["ccr_enabled"]) + && enabled(&juice["repl_handle_enabled"]); + if !allowed.is_empty() { + let mut companions = Vec::new(); + if compaction || summarizes { + companions.push(RECOVERY); + } + if repl { + companions.extend(REPL); + } + seen.extend(companions.into_iter().filter(|name| has(name)).map(str::to_owned)); + } + seen.extend(list("extra_tools")); + let mut unique = Vec::new(); + for tool in seen { + if !unique.contains(&tool) { + unique.push(tool); + } } - seen + unique } /// Hold the instance at `client` against the child `pid`, the pinned From 375b7c667103ac858a5c7f91488ee272b625bc2b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:31:42 +0000 Subject: [PATCH 43/49] test(conformance): cover a failed first turn leaving the seat startable Add a conformance case asserting that when a seat's first turn fails, the next turn starts the thread afresh and completes rather than failing to resume. The fake surface now records a user message only once a turn ends, matching 0.64.15, and a shared helper builds turn requests for the test seat. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tests/conformance.rs | 24 +++++++++++++++++ .../tests/fake/surface.rs | 18 ++++++++----- .../tests/support/seat.rs | 26 +++++++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index 4ec3f5e5..df2d4559 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -12,6 +12,7 @@ use anyhow::Result; use subject::FakeSubject; use tinyhivemind_host::harness::conformance::{Case, Subject as _}; use tinyhivemind_host::harness::{Error, HarnessKind, SeatPlan}; +use tinyhivemind_hives::TurnDisposition; use tinyhivemind_openhuman_process::capability::Refusal; /// One test per case, and a check that no case is left out. @@ -82,3 +83,26 @@ async fn a_running_seat_is_not_started_twice_and_a_stopped_one_is_already_stoppe drop(runner); Ok(()) } + +/// A first turn that fails leaves no session behind: the next turn starts +/// the seat's thread afresh instead of failing to resume it forever. +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_first_turn_leaves_the_seat_able_to_start() -> Result<()> { + let subject = FakeSubject::new()?; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + let steps = subject.control().join("steps"); + std::fs::write(steps.join("a"), r#"{"error": "provider down"}"#)?; + let first = runner.run(seat_support::request("t1", None)).await; + let failed = match &first { + Ok(outcome) => matches!(outcome.disposition, TurnDisposition::Failed(_)), + Err(_) => true, + }; + assert!(failed, "{first:?}"); + std::fs::write(steps.join("b"), r#"{"reply": "works", "tokens": 1}"#)?; + let second = runner.run(seat_support::request("t2", None)).await?; + assert_eq!(second.disposition, TurnDisposition::Completed); + assert_eq!(second.reply.as_deref(), Some("works")); + harness.stop("scout").await?; + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index 208acbcd..fa30a24d 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -397,7 +397,8 @@ impl State { let result = json!({"tool_name": tool, "tool_call_id": "call_1", "success": false}); say("tool_result", result); } - let seen = self.remember(&ids.thread, "user", &message); + // Only a turn that ends is kept in the thread, as 0.64.15 does. + let seen = self.users(&ids.thread) + 1; let call = self.open(seen); if step.is_null() { cancel.notified().await; @@ -418,6 +419,7 @@ impl State { return; } let reply = step["reply"].as_str().unwrap_or_default(); + self.remember(&ids.thread, "user", &message); self.remember(&ids.thread, "assistant", reply); let tokens = step["tokens"].as_u64().unwrap_or(0); let usage = json!({"input_tokens": tokens, "output_tokens": 2, @@ -441,8 +443,14 @@ impl State { } } - /// Append to the thread's transcript; the user messages in it. - fn remember(&self, thread: &str, role: &str, text: &str) -> usize { + /// The user messages in the thread's transcript. + fn users(&self, thread: &str) -> usize { + let text = fs::read_to_string(self.transcript(thread)).unwrap_or_default(); + text.lines().filter(|line| line.contains("\"user\"")).count() + } + + /// Append to the thread's transcript. + fn remember(&self, thread: &str, role: &str, text: &str) { let path = self.transcript(thread); if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); @@ -451,10 +459,6 @@ impl State { if let Ok(mut file) = file { let _ = writeln!(file, "{}", json!({"role": role, "text": text})); } - let text = fs::read_to_string(&path).unwrap_or_default(); - text.lines() - .filter(|line| line.contains("\"user\"")) - .count() } fn open(&self, seen: usize) -> u64 { diff --git a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs index b706df10..9170ee09 100644 --- a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs +++ b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs @@ -66,3 +66,29 @@ pub(crate) fn kill_all(pids: Vec) { } } } + +/// A turn of the test seat, from the host. +pub(crate) fn request(turn: &str, session: Option<&str>) -> tinyhivemind_hives::TurnRequest { + use tinyhivemind_hives::{Destination, Message, TurnRequest}; + TurnRequest { + turn_id: turn.into(), + scheduled_job_id: None, + teammates: Vec::new(), + agent_id: "scout".into(), + session_id: session.map(Into::into), + messages: vec![Message { + scheduled_job_id: None, + message_id: format!("message-{turn}"), + sequence: 1, + sender: tinyhivemind_hives::HOST_ID.into(), + destination: Destination::Agent("scout".into()), + body: format!("turn {turn}"), + thread: None, + episode_id: None, + only_for: Vec::new(), + }], + memberships: Vec::new(), + episode: None, + resumption: None, + } +} From ea4cf9939b3687bd6783666bcece63bbeb8b9c6f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:32:25 +0000 Subject: [PATCH 44/49] fix(seat): report a failed first turn as having no session A turn that fails before its thread has a transcript now returns a dedicated error instead of a session id, so the next turn is not asked to resume a thread that never existed. The transcript lookup is shared between the resume check and this new check. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/error/mod.rs | 3 ++ .../src/error/test.rs | 4 ++ .../src/harness/seat.rs | 33 ++++++++++----- .../src/instance/test.rs | 42 +++++++++++++++---- .../src/instance/verify.rs | 22 ++++++++-- .../tests/conformance.rs | 2 +- .../tests/fake/surface.rs | 4 +- .../tests/live.rs | 29 +++++++++++++ .../tests/live/model.rs | 15 +++++++ .../tests/live/subject.rs | 4 ++ 10 files changed, 133 insertions(+), 25 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/error/mod.rs b/crates/tinyhivemind-openhuman-process/src/error/mod.rs index 61029106..135d3279 100644 --- a/crates/tinyhivemind-openhuman-process/src/error/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/error/mod.rs @@ -36,6 +36,9 @@ pub(crate) enum Error { /// The seat's session is gone from the instance; no new one is started. #[error("the instance has no thread {0}")] Resume(String), + /// The seat's first turn failed, so there is no session to report. + #[error("the turn failed before its thread had a transcript: {0}")] + FailedWithoutSession(String), /// The turn's request could not be rendered as its message. #[error("the turn could not be rendered: {0}")] Render(String), diff --git a/crates/tinyhivemind-openhuman-process/src/error/test.rs b/crates/tinyhivemind-openhuman-process/src/error/test.rs index b7eda967..08c536f8 100644 --- a/crates/tinyhivemind-openhuman-process/src/error/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/error/test.rs @@ -47,6 +47,10 @@ fn everything_else_is_a_harness_failure_with_its_message() { Error::io("the config")(std::io::Error::other("disk full")), "the config: disk full", ), + ( + Error::FailedWithoutSession("chat_error".into()), + "the turn failed before its thread had a transcript: chat_error", + ), ( Error::Render("bad request".into()), "the turn could not be rendered: bad request", diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs index 7e3ed81f..07e8f296 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -93,17 +93,10 @@ impl Seat { } let live = self.start().await?; let thread = request.session_id.clone().unwrap_or_else(|| self.thread()); - if let Some(session) = &request.session_id { - let found = live - .client - .call( - "openhuman.threads_transcript_get", - json!({"thread_id": session}), - ) - .await?; - if found["data"]["hasTranscript"] != true { - return Err(Error::Resume(session.clone())); - } + if let Some(session) = &request.session_id + && !has_transcript(&live, session).await? + { + return Err(Error::Resume(session.clone())); } let message = tinyhivemind_host::turn::render(&request) .map_err(|error| Error::Render(error.to_string()))?; @@ -127,6 +120,14 @@ impl Seat { }; self.plan.observer.event(&self.plan.seat.id, event); } + // A thread exists once a turn on it has ended. A failure before that + // reports no session, or the next turn would be refused its resume + // of a thread that never was. + if let Some(reason) = &ended.failure + && !has_transcript(&live, &thread).await? + { + return Err(Error::FailedWithoutSession(reason.clone())); + } let disposition = ended .failure .map_or(TurnDisposition::Completed, TurnDisposition::Failed); @@ -180,6 +181,16 @@ impl Seat { } } +/// Whether the instance keeps a transcript of `thread`. +async fn has_transcript(live: &Live, thread: &str) -> Result { + let params = json!({"thread_id": thread}); + let found = live + .client + .call("openhuman.threads_transcript_get", params) + .await?; + Ok(found["data"]["hasTranscript"] == true) +} + /// The seat as the seat runner sees it. pub(super) struct Runner(pub(super) Arc); diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index 2c411f3e..a0a87a39 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -185,7 +185,10 @@ fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { assert_eq!(super::verify::visible(&off, &available), ["mcp_s_post_1"]); // Another chat agent is a built-in one, whose tools are not these. let other = serde_json::json!({"agent_registry": {"entries": []}}); - assert_eq!(super::verify::visible(&other, &available), [""]); + assert_eq!( + super::verify::visible(&other, &available), + [""] + ); } #[test] @@ -205,9 +208,17 @@ fn the_written_config_turns_compaction_off() { #[test] fn every_source_the_binary_adds_tools_from_is_counted() { use serde_json::json; - let available: Vec = ["mcp_s_post_1", "tool_search", "juice_retrieve", "juice_find", "juice_extract", "juice_summarize", "shell"] - .map(String::from) - .to_vec(); + let available: Vec = [ + "mcp_s_post_1", + "tool_search", + "juice_retrieve", + "juice_find", + "juice_extract", + "juice_summarize", + "shell", + ] + .map(String::from) + .to_vec(); let entry = |extra: serde_json::Value| { let mut entry = json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); if let (Some(entry), Some(extra)) = (entry.as_object_mut(), extra.as_object()) { @@ -232,14 +243,23 @@ fn every_source_the_binary_adds_tools_from_is_counted() { assert_eq!(seen(&config(entry(json!({})), json!({}))), ["mcp_s_post_1"]); // Deferred tools, when the allowlist names the tool search. let search = entry(json!({"tool_allowlist": ["mcp_s_post_1", "tool_search"]})); - assert!(seen(&config(search, json!({}))).iter().any(|tool| tool.contains("deferred"))); + assert!( + seen(&config(search, json!({}))) + .iter() + .any(|tool| tool.contains("deferred")) + ); // The REPL tools, while results are stored behind a handle. let repl = json!({ "context": {"compaction_enabled": true}, "tokenjuice": {"router_enabled": true, "ccr_enabled": true, "repl_handle_enabled": true}, }); let repl = seen(&config(entry(json!({})), repl)); - for tool in ["juice_retrieve", "juice_find", "juice_extract", "juice_summarize"] { + for tool in [ + "juice_retrieve", + "juice_find", + "juice_extract", + "juice_summarize", + ] { assert!(repl.contains(&tool.to_owned()), "{tool} in {repl:?}"); } // The summary stage, which only the orchestrator gets. @@ -249,10 +269,16 @@ fn every_source_the_binary_adds_tools_from_is_counted() { "context": {"compaction_enabled": false, "summarizer_payload_threshold_tokens": 100}, }); let summary = seen(&config(orchestrator, summary)); - assert!(summary.contains(&"juice_retrieve".to_owned()), "{summary:?}"); + assert!( + summary.contains(&"juice_retrieve".to_owned()), + "{summary:?}" + ); // `extra_tools`, and a session's delegation tools for an agent with subagents. let extra = seen(&config(entry(json!({"extra_tools": ["shell"]})), json!({}))); assert!(extra.contains(&"shell".to_owned()), "{extra:?}"); let delegating = seen(&config(entry(json!({"subagents": ["helper"]})), json!({}))); - assert!(delegating.iter().any(|tool| tool.contains("delegation")), "{delegating:?}"); + assert!( + delegating.iter().any(|tool| tool.contains("delegation")), + "{delegating:?}" + ); } diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs index c74a4c2d..cadd0a0b 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -96,16 +96,25 @@ fn enabled(value: &Value) -> bool { /// handle, both only for a non-empty allowlist; and `extra_tools`. No RPC /// reports the set, so the live tests check it at the model. pub(super) fn visible(config: &Value, available: &[String]) -> Vec { - let agent = config["agent"]["chat_agent_id"].as_str().unwrap_or("orchestrator"); + let agent = config["agent"]["chat_agent_id"] + .as_str() + .unwrap_or("orchestrator"); let entries = config["agent_registry"]["entries"].as_array().cloned(); - let Some(entry) = entries.unwrap_or_default().into_iter().find(|entry| entry["id"] == agent) + let Some(entry) = entries + .unwrap_or_default() + .into_iter() + .find(|entry| entry["id"] == agent) else { return vec![format!("")]; }; let has = |name: &str| available.iter().any(|tool| tool == name); let list = |key: &str| { let names = entry[key].as_array().cloned().unwrap_or_default(); - names.iter().filter_map(Value::as_str).map(str::to_owned).collect::>() + names + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect::>() }; let allowed = list("tool_allowlist"); let mut seen: Vec = allowed.iter().filter(|name| has(name)).cloned().collect(); @@ -131,7 +140,12 @@ pub(super) fn visible(config: &Value, available: &[String]) -> Vec { if repl { companions.extend(REPL); } - seen.extend(companions.into_iter().filter(|name| has(name)).map(str::to_owned)); + seen.extend( + companions + .into_iter() + .filter(|name| has(name)) + .map(str::to_owned), + ); } seen.extend(list("extra_tools")); let mut unique = Vec::new(); diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index df2d4559..4c83d81d 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -10,9 +10,9 @@ mod subject; use anyhow::Result; use subject::FakeSubject; +use tinyhivemind_hives::TurnDisposition; use tinyhivemind_host::harness::conformance::{Case, Subject as _}; use tinyhivemind_host::harness::{Error, HarnessKind, SeatPlan}; -use tinyhivemind_hives::TurnDisposition; use tinyhivemind_openhuman_process::capability::Refusal; /// One test per case, and a check that no case is left out. diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index fa30a24d..d42175f5 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -446,7 +446,9 @@ impl State { /// The user messages in the thread's transcript. fn users(&self, thread: &str) -> usize { let text = fs::read_to_string(self.transcript(thread)).unwrap_or_default(); - text.lines().filter(|line| line.contains("\"user\"")).count() + text.lines() + .filter(|line| line.contains("\"user\"")) + .count() } /// Append to the thread's transcript. diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs index f984adbd..fa0f7088 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -194,3 +194,32 @@ async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { assert_eq!(left, Vec::::new()); Ok(()) } + +/// A first turn the provider refuses leaves the seat able to start its +/// thread on the next turn. +#[tokio::test(flavor = "multi_thread")] +async fn live_a_failed_first_turn_leaves_the_seat_able_to_start() -> Result<()> { + use tinyhivemind_host::harness::conformance::{ModelStep, Subject as _}; + let Some(subject) = LiveSubject::new().await? else { + return Ok(()); + }; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + subject.model().fail_next(); + let first = runner.run(seat_support::request("t1", None)).await; + let failed = match &first { + Ok(outcome) => matches!(outcome.disposition, TurnDisposition::Failed(_)), + Err(_) => true, + }; + anyhow::ensure!(failed, "the refused turn did not fail: {first:?}"); + let reply = ModelStep::Reply { + text: "works".into(), + usage: tinyhivemind_host::harness::TurnUsage::default(), + }; + subject.model().script(&[reply]); + let second = runner.run(seat_support::request("t2", None)).await?; + assert_eq!(second.disposition, TurnDisposition::Completed); + assert_eq!(second.reply.as_deref(), Some("works")); + harness.stop("scout").await?; + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs index c7448352..45036a17 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/model.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -19,6 +19,8 @@ fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { #[derive(Default)] struct State { + /// Requests to refuse with a 400 before the script plays on. + failures: Mutex, steps: Mutex>, calls: Mutex>, } @@ -47,6 +49,11 @@ impl ScriptedModel { *lock(&self.state.steps) = steps.iter().cloned().collect(); } + /// Refuse the next request, as a provider refuses a bad one. + pub(crate) fn fail_next(&self) { + *lock(&self.state.failures) += 1; + } + pub(crate) fn calls(&self) -> Vec { lock(&self.state.calls).clone() } @@ -68,6 +75,14 @@ fn answer(state: &Arc, request: &Request) -> Reply { if !request.path.ends_with("/chat/completions") { return Reply::Json(404, json!({})); } + { + let mut failures = lock(&state.failures); + if *failures > 0 { + *failures -= 1; + let error = json!({"error": {"message": "scripted refusal", "type": "invalid_request_error"}}); + return Reply::Json(400, error); + } + } let body = request.json(); let messages = body["messages"].as_array().cloned().unwrap_or_default(); let seen = messages diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs index ca9f547e..b222b66e 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -127,6 +127,10 @@ impl LiveSubject { })) } + pub(crate) fn model(&self) -> &ScriptedModel { + &self.model + } + fn instance(&self) -> PathBuf { self.root.path().join("instance") } From b448a9666c301440e61fe644a13cdf3898bb3334 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:33:08 +0000 Subject: [PATCH 45/49] fix(openhuman-process): redact secrets from debug output The Debug implementations for the config input, written config, and RPC client now hide the bearer, prompt, and core token, since these values carry the seat's and instance's authority and were previously printed in full. Tests cover both the types directly and a running harness. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/config/mod.rs | 25 +++++++++++-- .../src/config/test.rs | 20 +++++++++++ .../src/rpc/mod.rs | 12 ++++++- .../src/rpc/test.rs | 7 ++++ .../tests/conformance.rs | 36 +++++++++++++++++++ .../tests/fake/subject.rs | 11 ++++-- 6 files changed, 106 insertions(+), 5 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/config/mod.rs b/crates/tinyhivemind-openhuman-process/src/config/mod.rs index 57c50d62..62dae1b8 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/mod.rs @@ -37,7 +37,7 @@ const PROVIDER: &str = "thm"; const UNSET: [&str; 3] = ["api_key", "api_url", "inference_url"]; /// What a seat's config is made of. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy)] pub(crate) struct Input<'a> { /// The provider route. pub(crate) model: &'a SeatModel, @@ -59,11 +59,32 @@ pub(crate) struct Input<'a> { } /// A config as written. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, PartialEq)] pub(crate) struct Written { tree: Value, } +impl std::fmt::Debug for Input<'_> { + /// The bearer and the prompt are not shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Input") + .field("seat", &self.seat) + .field("server", &self.server) + .field("url", &self.url) + .field("tools", &self.tools) + .field("bearer", &"redacted") + .finish_non_exhaustive() + } +} + +impl std::fmt::Debug for Written { + /// Setting names only: the values hold the bearer. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let names: Vec = self.settings().into_iter().map(|(name, _)| name).collect(); + f.debug_struct("Written").field("settings", &names).finish() + } +} + impl Written { /// The config for `input`. pub(crate) fn new(input: &Input<'_>) -> Self { diff --git a/crates/tinyhivemind-openhuman-process/src/config/test.rs b/crates/tinyhivemind-openhuman-process/src/config/test.rs index 353e0c57..300e9f93 100644 --- a/crates/tinyhivemind-openhuman-process/src/config/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/config/test.rs @@ -210,3 +210,23 @@ fn the_writer_leaves_out_null_and_writes_other_shapes_inline() { assert_eq!(parsed, expected); assert_eq!(super::toml::write(&json!("not a table")), ""); } + +#[test] +fn debug_shows_neither_the_bearer_nor_the_prompt() { + let tools = tools(); + let model = model(); + let input = Input { + model: &model, + seat: "scout", + prompt: "You scout.", + server: "hivemind", + url: "http://127.0.0.1:7/mcp", + bearer: "secret-bearer", + tools: &tools, + turn_secs: 600, + }; + let written = Written::new(&input); + for shown in [format!("{input:?}"), format!("{written:?}")] { + assert!(!shown.contains("secret-bearer"), "{shown}"); + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs index 1d154a77..4b81a992 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs @@ -52,7 +52,7 @@ impl From for Error { } /// A client of one instance. -#[derive(Clone, Debug)] +#[derive(Clone)] pub(crate) struct Client { http: reqwest::Client, base: String, @@ -139,6 +139,16 @@ impl Client { } } +impl std::fmt::Debug for Client { + /// The token is the instance's whole authority, so it is not shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client") + .field("base", &self.base) + .field("token", &"redacted") + .finish_non_exhaustive() + } +} + fn decode(bytes: &[u8]) -> Result { serde_json::from_slice(bytes).map_err(|error| Error::Decode(error.to_string())) } diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs index e5e470a4..1ed2b4b3 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -136,3 +136,10 @@ fn an_sse_frame_that_is_not_json_is_an_error() { "{found:?}" ); } + +#[test] +fn debug_does_not_show_the_core_token() { + let client = Client::new(1, "secret-core-token").unwrap_or_else(|error| unreachable!("{error}")); + let shown = format!("{client:?}"); + assert!(!shown.contains("secret-core-token"), "{shown}"); +} diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index 4c83d81d..d7926649 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -106,3 +106,39 @@ async fn a_failed_first_turn_leaves_the_seat_able_to_start() -> Result<()> { harness.stop("scout").await?; Ok(()) } + +/// Neither the seat's bearer nor the instance's core token is in the +/// harness's `Debug`, running seats included. +#[tokio::test(flavor = "multi_thread")] +async fn debug_of_a_running_harness_shows_no_secret() -> Result<()> { + use std::sync::{Arc, Mutex}; + use tinyhivemind_host::harness::{Event, Harness as _, Observer}; + #[derive(Default)] + struct Pid(Mutex>); + impl Observer for Pid { + fn event(&self, _: &str, event: Event) { + if let Event::Started(started) = event { + *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(started.pid); + } + } + } + let subject = FakeSubject::new()?; + let harness = subject.openhuman(); + let pid = Arc::new(Pid::default()); + let mut plan = subject.seat(); + plan.observer = pid.clone(); + let runner = harness.start(plan, subject.endpoint()).await?; + let started = *pid.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let environ = std::fs::read(format!("/proc/{}/environ", started.unwrap_or_default()))?; + let token = String::from_utf8_lossy(&environ) + .split('\0') + .find_map(|entry| entry.strip_prefix("OPENHUMAN_CORE_TOKEN=").map(str::to_owned)) + .unwrap_or_default(); + assert!(token.len() >= 32, "the child's core token was not found"); + let shown = format!("{harness:?}"); + assert!(!shown.contains(&token), "the core token is in {shown}"); + assert!(!shown.contains("seat-bearer"), "the bearer is in {shown}"); + harness.stop("scout").await?; + drop(runner); + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs index 199144d9..aada5ac7 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -79,10 +79,17 @@ impl FakeSubject { } } +impl FakeSubject { + /// The harness itself, rather than behind the port. + pub(crate) fn openhuman(&self) -> OpenHumanHarness { + let program = Program::new(self.root.path().join("openhuman-core"), "0.64.15"); + OpenHumanHarness::new(program).with_options(Self::options()) + } +} + impl Subject for FakeSubject { fn harness(&self) -> Arc { - let program = Program::new(self.root.path().join("openhuman-core"), "0.64.15"); - Arc::new(OpenHumanHarness::new(program).with_options(Self::options())) + Arc::new(self.openhuman()) } fn seat(&self) -> SeatPlan { From 37271bc763d7afab7ab8967dfd627100a5bd925a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:40:11 +0000 Subject: [PATCH 46/49] fix(harness): reserve seats before starting and stop instances started after close Seats are now inserted into the registry before their instance starts, so a concurrent start is refused and a stop can find the seat to stop, with the entry removed again if the start fails. A seat closed while its instance was starting now stops that instance instead of leaving it running, and approvals gained a configurable timeout. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/error/mod.rs | 11 +++ .../src/harness/mod.rs | 28 +++++-- .../src/harness/seat.rs | 9 +++ .../src/instance/mod.rs | 8 ++ .../src/instance/test.rs | 68 +++++++++++++++++ .../src/rpc/test.rs | 3 +- .../src/turn/mod.rs | 7 ++ .../src/turn/test.rs | 76 +++++++++++++++++++ .../tests/conformance.rs | 55 +++++++++++++- .../tests/fake/subject.rs | 1 + .../tests/fake/surface.rs | 12 ++- .../tests/live/model.rs | 3 +- .../tests/live/subject.rs | 1 + 13 files changed, 270 insertions(+), 12 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/error/mod.rs b/crates/tinyhivemind-openhuman-process/src/error/mod.rs index 135d3279..fdd1f001 100644 --- a/crates/tinyhivemind-openhuman-process/src/error/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/error/mod.rs @@ -42,6 +42,17 @@ pub(crate) enum Error { /// The turn's request could not be rendered as its message. #[error("the turn could not be rendered: {0}")] Render(String), + /// The keyring key file is not a private 256-bit hex key. + #[error("the keyring key file is unusable: {0}")] + KeyFile(&'static str), + /// A start failed, and so did stopping what it had started. + #[error("{error}; and its instance could not be stopped: {stop}")] + Abandoned { + /// Why the start failed. + error: Box, + /// Why the stop did. + stop: process::Error, + }, /// A file of the instance could not be written or read. #[error("{what}: {source}")] Io { diff --git a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs index 31e5707f..8fcfdbba 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs @@ -49,15 +49,20 @@ pub struct Options { pub warm_up: Duration, /// Each step of a stop. pub stop: StopPolicy, + /// For the seat's approver to decide what the harness asks; then the + /// call is denied. + pub approval: Duration, } impl Default for Options { - /// 30 s to be healthy, 20 s to warm up, and the supervisor's own stop. + /// 30 s to be healthy, 20 s to warm up, the supervisor's own stop, and + /// 2 minutes for an approval. fn default() -> Self { Self { ready: Duration::from_secs(30), warm_up: Duration::from_secs(20), stop: StopPolicy::default(), + approval: Duration::from_secs(120), } } } @@ -111,13 +116,24 @@ impl Harness for OpenHumanHarness { let model = capability::check(&plan.seat) .map_err(|refusal| Error::Refused(Box::new(refusal)))?; let id = plan.seat.id.clone(); - if lock(&seats).contains_key(&id) { - return Err(Error::Harness(format!("seat {id} is already running"))); - } let timeout = plan.turn_timeout(); let seat = Arc::new(Seat::new(program, options, plan, tools, model)); - seat.start().await?; - lock(&seats).insert(id, seat.clone()); + { + // Reserved before anything starts, so that a second start is + // refused and a stop meanwhile finds the seat to stop. + let mut seats = lock(&seats); + if seats.contains_key(&id) { + return Err(Error::Harness(format!("seat {id} is already running"))); + } + seats.insert(id.clone(), seat.clone()); + } + if let Err(error) = seat.start().await { + let mut seats = lock(&seats); + if seats.get(&id).is_some_and(|held| Arc::ptr_eq(held, &seat)) { + seats.remove(&id); + } + return Err(error.into()); + } let runner = SeatRunner::new(Arc::new(Runner(seat))).with_timeout(timeout); Ok(Arc::new(runner) as Arc) }) diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs index 07e8f296..0c32581a 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -67,6 +67,9 @@ impl Seat { /// Start an instance if none is running, reporting it. pub(super) async fn start(&self) -> Result> { let mut live = self.live.lock().await; + if *self.closed.borrow() { + return Err(turn::Error::Closed.into()); + } if let Some(running) = live.as_ref().filter(|live| live.instance.exit().is_none()) { return Ok(running.clone()); } @@ -81,6 +84,11 @@ impl Seat { model: &self.model, }; let started = Arc::new(launcher.launch().await?); + if *self.closed.borrow() { + // Stopped while it started: what started is stopped too. + started.instance.stop(async {}, self.options.stop).await?; + return Err(turn::Error::Closed.into()); + } let event = Event::Started(started.started.clone()); self.plan.observer.event(&self.plan.seat.id, event); *live = Some(started.clone()); @@ -110,6 +118,7 @@ impl Seat { iterations: self.model.iterations, observer: self.plan.observer.as_ref(), approver: self.plan.approver.as_ref(), + approval_limit: self.options.approval, closed: self.closed.subscribe(), }; let ended = turn::run(turn, &message, &self.active).await?; diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs index 2dc56458..9c8d9ac6 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -113,6 +113,14 @@ impl Layout { } } +/// `error`, and the stop that followed it if that failed too. +pub(crate) fn abandon( + error: Error, + _stopped: std::result::Result, +) -> Error { + error +} + /// 256 random bits, as hex. fn random() -> Result { let mut bytes = [0_u8; 32]; diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index a0a87a39..ef1f99c5 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -282,3 +282,71 @@ fn every_source_the_binary_adds_tools_from_is_counted() { "{delegating:?}" ); } + +#[test] +fn the_keyring_key_is_made_once_and_a_bad_one_is_refused() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let layout = Layout::new(dir.path()); + let made = layout.master_key(); + let made = made.unwrap_or_else(|error| unreachable!("a new key: {error}")); + assert_eq!(made.len(), 64); + assert!(made.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(layout.master_key().ok(), Some(made)); + let path = dir.path().join("keyring.key"); + let mode = |mode| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)); + assert!(mode(0o644).is_ok()); + assert!(matches!(layout.master_key(), Err(Error::KeyFile(_)))); + for bad in ["", "abc", &"z".repeat(64)] { + assert!(std::fs::write(&path, bad).is_ok() && mode(0o600).is_ok()); + assert!( + matches!(layout.master_key(), Err(Error::KeyFile(_))), + "{bad:?}" + ); + } +} + +#[test] +fn a_config_already_there_is_made_private_when_written() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let layout = Layout::new(dir.path()); + assert!(std::fs::create_dir_all(layout.workspace()).is_ok()); + let path = layout.workspace().join("config.toml"); + assert!(std::fs::write(&path, "old").is_ok()); + assert!(std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).is_ok()); + assert!(layout.write_config(&Fixture::written_for_test()).is_ok()); + let mode = std::fs::metadata(&path).map(|meta| meta.permissions().mode() & 0o777); + assert_eq!(mode.ok(), Some(0o600)); +} + +#[test] +fn a_stop_that_fails_after_a_failed_start_keeps_both_errors() { + let start = Error::Resume("t".into()); + let kept = super::abandon(start, Ok::<(), tinyhivemind_host::process::Error>(())); + assert!(matches!(kept, Error::Resume(_))); + let stopped: Result<(), _> = Err(tinyhivemind_host::process::Error::Unproven); + let both = super::abandon(Error::Resume("t".into()), stopped); + let shown = both.to_string(); + assert!( + shown.contains("no thread t") && shown.contains("could not be proven gone"), + "{shown}" + ); +} + +#[tokio::test] +async fn tools_whose_names_differ_only_in_hex_like_suffixes_are_told_apart() { + let served = r#"["post", "post_a", "post_ab", "post_abc123"]"#; + let fixture = Fixture::with(&[("served", served), ("warm", "0")]).await; + let wanted: BTreeSet = ["post", "post_a", "post_ab", "post_abc123"] + .map(String::from) + .into_iter() + .collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + let mut expected: Vec = wanted + .iter() + .map(|tool| crate::fake::hashed(SERVER, tool)) + .collect(); + expected.sort(); + assert_eq!(found.ok(), Some(expected)); +} diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs index 1ed2b4b3..9b30036e 100644 --- a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -139,7 +139,8 @@ fn an_sse_frame_that_is_not_json_is_an_error() { #[test] fn debug_does_not_show_the_core_token() { - let client = Client::new(1, "secret-core-token").unwrap_or_else(|error| unreachable!("{error}")); + let client = + Client::new(1, "secret-core-token").unwrap_or_else(|error| unreachable!("{error}")); let shown = format!("{client:?}"); assert!(!shown.contains("secret-core-token"), "{shown}"); } diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs index cf628d5e..399a3f0a 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -81,6 +81,8 @@ pub(crate) struct Turn<'a> { pub(crate) iterations: usize, pub(crate) observer: &'a dyn Observer, pub(crate) approver: &'a dyn Approver, + /// How long the approver may take; then the call is denied. + pub(crate) approval_limit: std::time::Duration, /// Becomes true when the seat is stopped. pub(crate) closed: watch::Receiver, } @@ -242,6 +244,11 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { Ok(()) } +/// Deny every approval still pending; how many there were. +pub(crate) async fn deny_stale(_client: &Client) -> Result { + Ok(0) +} + /// Cancel `active`, returning once its request has ended. pub(crate) async fn cancel(client: &Client, active: &Active) -> Result<()> { let mut events = client.events(&active.client_id).await?; diff --git a/crates/tinyhivemind-openhuman-process/src/turn/test.rs b/crates/tinyhivemind-openhuman-process/src/turn/test.rs index 8e3a0826..1f74454c 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/test.rs @@ -69,6 +69,7 @@ impl Harnessed { iterations, observer: self.events.as_ref(), approver, + approval_limit: std::time::Duration::from_secs(5), closed: self.closed.subscribe(), } } @@ -243,3 +244,78 @@ async fn a_message_the_instance_does_not_accept_fails_and_agent_chat_is_never_us assert!(!methods.contains(&json!("openhuman.inference_agent_chat"))); assert!(methods.contains(&json!("openhuman.channel_web_chat"))); } + +/// Never answers. +struct Silent; + +impl Approver for Silent { + fn decide(&self, _: ToolApproval) -> ApprovalFuture { + Box::pin(std::future::pending()) + } +} + +#[tokio::test] +async fn an_approver_that_does_not_answer_in_time_is_a_denial() { + let harnessed = Harnessed::new(&[json!({"reply": "after", "approval": "shell"})]).await; + let mut turn = harnessed.turn(&Silent, 8); + turn.approval_limit = std::time::Duration::from_millis(100); + assert!(run(turn, "go", &harnessed.active).await.is_ok()); + let decided = harnessed.fixture.log("decisions.jsonl"); + assert_eq!( + decided.first().map(|entry| entry["decision"].clone()), + Some(json!("deny")) + ); +} + +#[tokio::test] +async fn an_approval_request_without_an_id_fails_the_turn_clearly() { + let step = json!({"reply": "after", "approval": "shell", "approval_id": ""}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await; + let error = ended.err().map(|error| error.to_string()); + assert!(error.is_some_and(|error| error.contains("approval_request without a request_id"))); +} + +#[tokio::test] +async fn an_approval_left_by_a_dropped_turn_is_denied_before_the_next() { + let harnessed = + Arc::new(Harnessed::new(&[json!({"reply": "late", "approval": "shell"})]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { + run(running.turn(&Silent, 8), "go", &running.active) + .await + .is_ok() + }); + let client = harnessed.fixture.client.clone(); + let mut pending = 0; + while pending == 0 { + let listed = client + .call("openhuman.approval_list_pending", json!({})) + .await; + pending = listed + .ok() + .and_then(|listed| listed["result"].as_array().map(Vec::len)) + .unwrap_or(0); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + task.abort(); + let denied = super::deny_stale(&client).await; + assert_eq!(denied.ok(), Some(1)); + let decided = harnessed.fixture.log("decisions.jsonl"); + assert_eq!( + decided.first().map(|entry| entry["decision"].clone()), + Some(json!("deny")) + ); + assert_eq!(super::deny_stale(&client).await.ok(), Some(0)); +} + +#[tokio::test] +async fn a_chat_error_is_bounded_and_carries_no_payload() { + let payload = format!("upstream said:\n{{\"error\": \"{}\"}}", "x".repeat(5000)); + let harnessed = Harnessed::new(&[json!({"error": payload})]).await; + let failure = harnessed.run(8).await.ok().and_then(|ended| ended.failure); + let failure = failure.unwrap_or_else(|| unreachable!("a failure")); + assert!(failure.len() <= 300, "{} bytes", failure.len()); + assert!(!failure.contains('\n'), "{failure}"); + assert!(failure.starts_with("chat_error (inference)"), "{failure}"); +} diff --git a/crates/tinyhivemind-openhuman-process/tests/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs index d7926649..9ad5e4f0 100644 --- a/crates/tinyhivemind-openhuman-process/tests/conformance.rs +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -118,7 +118,10 @@ async fn debug_of_a_running_harness_shows_no_secret() -> Result<()> { impl Observer for Pid { fn event(&self, _: &str, event: Event) { if let Event::Started(started) = event { - *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(started.pid); + *self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(started.pid); } } } @@ -128,11 +131,18 @@ async fn debug_of_a_running_harness_shows_no_secret() -> Result<()> { let mut plan = subject.seat(); plan.observer = pid.clone(); let runner = harness.start(plan, subject.endpoint()).await?; - let started = *pid.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let started = *pid + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let environ = std::fs::read(format!("/proc/{}/environ", started.unwrap_or_default()))?; let token = String::from_utf8_lossy(&environ) .split('\0') - .find_map(|entry| entry.strip_prefix("OPENHUMAN_CORE_TOKEN=").map(str::to_owned)) + .find_map(|entry| { + entry + .strip_prefix("OPENHUMAN_CORE_TOKEN=") + .map(str::to_owned) + }) .unwrap_or_default(); assert!(token.len() >= 32, "the child's core token was not found"); let shown = format!("{harness:?}"); @@ -142,3 +152,42 @@ async fn debug_of_a_running_harness_shows_no_secret() -> Result<()> { drop(runner); Ok(()) } + +/// Two starts of one seat at once: one runs, the other is refused. +#[tokio::test(flavor = "multi_thread")] +async fn a_seat_starting_twice_at_once_runs_once() -> Result<()> { + use tinyhivemind_host::harness::Harness as _; + let subject = FakeSubject::new()?; + let harness = subject.openhuman(); + let (one, two) = tokio::join!( + harness.start(subject.seat(), subject.endpoint()), + harness.start(subject.seat(), subject.endpoint()), + ); + let started = [one.is_ok(), two.is_ok()]; + assert_eq!(started.iter().filter(|ok| **ok).count(), 1, "{started:?}"); + let refused = one.err().or(two.err()).map(|error| error.to_string()); + assert!(refused.is_some_and(|reason| reason.contains("already"))); + harness.stop("scout").await?; + assert_eq!(subject.processes(), Vec::::new()); + Ok(()) +} + +/// A stop while the seat starts stops what it starts, and the start fails. +#[tokio::test(flavor = "multi_thread")] +async fn a_stop_during_start_leaves_nothing_running() -> Result<()> { + use tinyhivemind_host::harness::Harness as _; + let subject = FakeSubject::new()?; + let harness = std::sync::Arc::new(subject.openhuman()); + let starting = harness.clone(); + let (seat, endpoint) = (subject.seat(), subject.endpoint()); + let start = tokio::spawn(async move { starting.start(seat, endpoint).await.err() }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + harness.stop("scout").await?; + let refused = start.await?; + assert!(refused.is_some(), "the start succeeded after its stop"); + assert_eq!(subject.processes(), Vec::::new()); + // The seat may be started again. + harness.start(subject.seat(), subject.endpoint()).await?; + harness.stop("scout").await?; + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs index aada5ac7..e476b985 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -75,6 +75,7 @@ impl FakeSubject { terminate: Duration::from_secs(2), kill: Duration::from_secs(10), }, + approval: Duration::from_secs(5), } } } diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs index d42175f5..5856342d 100644 --- a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -208,6 +208,13 @@ impl State { } "openhuman.channel_web_chat" => self.chat(params).map(envelope), "openhuman.channel_web_cancel" => Ok(envelope(self.cancel(params))), + "openhuman.approval_list_pending" => { + let pending = lock(&self.approvals) + .keys() + .map(|id| json!({"request_id": id})) + .collect::>(); + Ok(envelope(json!(pending))) + } "openhuman.approval_decide" => { let id = params["request_id"].as_str().unwrap_or_default(); let decision = params["decision"].as_str().unwrap_or_default().to_owned(); @@ -378,7 +385,10 @@ impl State { self.publish(&ids.client, &ids.thread, "req-stray", "chat_done", stray); } if let Some(tool) = step["approval"].as_str() { - let id = format!("approval-{}", self.next.fetch_add(1, Ordering::Relaxed)); + let id = match step["approval_id"].as_str() { + Some(id) => id.to_owned(), + None => format!("approval-{}", self.next.fetch_add(1, Ordering::Relaxed)), + }; let (sender, decided) = oneshot::channel(); lock(&self.approvals).insert(id.clone(), sender); // Its `request_id` is the approval's, not the turn's. diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs index 45036a17..9d7f9b6a 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/model.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -79,7 +79,8 @@ fn answer(state: &Arc, request: &Request) -> Reply { let mut failures = lock(&state.failures); if *failures > 0 { *failures -= 1; - let error = json!({"error": {"message": "scripted refusal", "type": "invalid_request_error"}}); + let error = + json!({"error": {"message": "scripted refusal", "type": "invalid_request_error"}}); return Reply::Json(400, error); } } diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs index b222b66e..74c4fbde 100644 --- a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -88,6 +88,7 @@ pub(crate) fn options() -> Options { ready: Duration::from_secs(30), warm_up: Duration::from_secs(20), stop: StopPolicy::default(), + approval: Duration::from_secs(5), } } From d1ea13c446ea6fcc64bd21be503f1134b5f39a67 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:43:50 +0000 Subject: [PATCH 47/49] fix(instance): harden key and config file handling and surface stop failures The keyring key is now rejected unless it is a regular file with mode 0600 holding 64 hex digits, and the config is chmodded to 0600 even when it already exists. Stop failures during launch are no longer swallowed but reported alongside the original error, and the harness fetch script rejects ambiguous lock entries and forbids non-HTTPS redirects. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/scripts/fetch-harness.sh | 13 ++++- .../src/harness/seat.rs | 1 + .../src/instance/mod.rs | 47 +++++++++++---- .../src/turn/mod.rs | 57 ++++++++++++++++--- harnesses.lock | 1 + 5 files changed, 98 insertions(+), 21 deletions(-) diff --git a/.github/scripts/fetch-harness.sh b/.github/scripts/fetch-harness.sh index 74eca7c7..9ba36f5a 100755 --- a/.github/scripts/fetch-harness.sh +++ b/.github/scripts/fetch-harness.sh @@ -28,6 +28,17 @@ entry="$(awk -v kind="[[$kind]]" -v target="$target" ' } inside && /^binary_sha256 = / && fields["target"] == target { print "binary_sha256=" fields["binary_sha256"] } ' "$lock" | sort -u)" +# One entry per kind and target: two would leave the pin ambiguous. +count="$(awk -v kind="[[$kind]]" -v target="target = \"$target\"" ' + $0 == kind { inside = 1; next } + /^\[\[/ { inside = 0 } + inside && $0 == target { n++ } + END { print n + 0 } +' "$lock")" +if [ "$count" -gt 1 ]; then + echo "fetch-harness: harnesses.lock has $count $kind entries for $target" >&2 + exit 1 +fi field() { sed -n "s/^$1=//p" <<<"$entry"; } url="$(field url)"; sha="$(field sha256)"; version="$(field version)" binary="$(field binary)"; binary_sha="$(field binary_sha256)" @@ -40,7 +51,7 @@ mkdir -p "$dest" dest="$(cd "$dest" && pwd)" asset="$dest/$(basename "$url")" if ! echo "$sha $asset" | sha256sum -c --status >/dev/null 2>&1; then - curl -fsSL --proto '=https' -o "$asset.partial" "$url" + curl -fsSL --proto '=https' --proto-redir '=https' -o "$asset.partial" "$url" mv "$asset.partial" "$asset" fi if ! echo "$sha $asset" | sha256sum -c --status; then diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs index 0c32581a..747b54d5 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -106,6 +106,7 @@ impl Seat { { return Err(Error::Resume(session.clone())); } + turn::deny_stale(&live.client).await?; let message = tinyhivemind_host::turn::render(&request) .map_err(|error| Error::Render(error.to_string()))?; let number = self.turns.fetch_add(1, Ordering::Relaxed); diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs index 9c8d9ac6..f60b321a 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -30,7 +30,7 @@ use crate::rpc::Client; use std::fmt::Write as _; use std::fs; use std::io::{Read as _, Write as _}; -use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _}; +use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _}; use std::path::{Path, PathBuf}; use std::time::Duration; use tinyhivemind_host::harness::{SeatPlan, Started, ToolEndpoint}; @@ -84,7 +84,14 @@ impl Layout { /// The keyring's master key, made on first use. fn master_key(&self) -> Result { let path = self.state.join("keyring.key"); - if let Ok(key) = fs::read_to_string(&path) { + if let Ok(meta) = fs::symlink_metadata(&path) { + if !meta.is_file() || meta.permissions().mode() & 0o777 != 0o600 { + return Err(Error::KeyFile("it is not a file of mode 0600")); + } + let key = fs::read_to_string(&path).map_err(Error::io("the keyring key"))?; + if key.len() != 64 || !key.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(Error::KeyFile("it does not hold 64 hex digits")); + } return Ok(key); } let key = random()?; @@ -108,6 +115,10 @@ impl Layout { .mode(0o600) .open(path) .map_err(Error::io("the config"))?; + // The mode above applies only to a new file. + let private = fs::Permissions::from_mode(0o600); + file.set_permissions(private) + .map_err(Error::io("the config"))?; file.write_all(written.toml().as_bytes()) .map_err(Error::io("the config")) } @@ -116,9 +127,15 @@ impl Layout { /// `error`, and the stop that followed it if that failed too. pub(crate) fn abandon( error: Error, - _stopped: std::result::Result, + stopped: std::result::Result, ) -> Error { - error + match stopped { + Ok(_) => error, + Err(stop) => Error::Abandoned { + error: Box::new(error), + stop, + }, + } } /// 256 random bits, as hex. @@ -188,8 +205,14 @@ impl Launcher<'_> { let ((probe, client), _) = self.start(&dir, &layout, &key, ¬hing).await?; let server = &self.tools.server; let names = discover(&client, server, &self.tools.tools, self.options.warm_up).await; - probe.stop(async {}, self.options.stop).await?; - let names = names?; + let stopped = probe.stop(async {}, self.options.stop).await; + let names = match names { + Ok(names) => { + stopped?; + names + } + Err(error) => return Err(abandon(error, stopped)), + }; let ((instance, client), written) = self.start(&dir, &layout, &key, &names).await?; let version = &self.program.version; let pid = instance.pid(); @@ -200,10 +223,10 @@ impl Launcher<'_> { client, started, }), - Err(error) => { - instance.stop(async {}, self.options.stop).await?; - Err(error) - } + Err(error) => Err(abandon( + error, + instance.stop(async {}, self.options.stop).await, + )), } } @@ -245,8 +268,8 @@ impl Launcher<'_> { Ok::<(), String>(()) }; if let Err(error) = instance.ready(probe, self.options.ready).await { - instance.stop(async {}, self.options.stop).await?; - return Err(error.into()); + let stopped = instance.stop(async {}, self.options.stop).await; + return Err(abandon(error.into(), stopped)); } Ok(((instance, client), written)) } diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs index 399a3f0a..fd9f1ea1 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -45,6 +45,9 @@ pub(crate) enum Error { /// The seat is being stopped. #[error("the turn was closed by a stop")] Closed, + /// An event the API does not allow. + #[error("the instance broke its protocol: {0}")] + Protocol(&'static str), } /// The submitted turn of a seat, which a cancellation names. @@ -200,7 +203,7 @@ async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Resul return Ok((ended, true)); } "chat_error" | "chat_cancelled" => { - let failure = format!("{name} ({}): {}", text("error_type"), text("message")); + let failure = bounded(name, &text("error_type"), &text("message")); let ended = Ended { failure: Some(failure), ..Ended::default() @@ -225,7 +228,9 @@ fn usage(usage: &Value) -> Option { /// Ask the seat's approver, and tell the instance. async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { - let id = event["request_id"].as_str().unwrap_or_default().to_owned(); + let id = event["request_id"].as_str().filter(|id| !id.is_empty()); + let id = id.ok_or(Error::Protocol("an approval_request without a request_id"))?; + let id = id.to_owned(); let request = ToolApproval { seat: turn.seat.to_owned(), turn_id: turn.id.to_owned(), @@ -233,9 +238,12 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { tool: event["tool_name"].as_str().unwrap_or_default().to_owned(), arguments: event["args"].clone(), }; - let decision = match turn.approver.decide(request).await { - ToolDecision::Allow => "approve_once", - ToolDecision::Deny { .. } => "deny", + // 0.64.15's `approval_decide` takes no reason, so a denial's is not + // passed on; the model is told only that the call was refused. + let decision = turn.approver.decide(request); + let decision = match tokio::time::timeout(turn.approval_limit, decision).await { + Ok(ToolDecision::Allow) => "approve_once", + Ok(ToolDecision::Deny { .. }) | Err(_) => "deny", }; let params = json!({"request_id": id, "decision": decision}); turn.client @@ -244,9 +252,42 @@ async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { Ok(()) } -/// Deny every approval still pending; how many there were. -pub(crate) async fn deny_stale(_client: &Client) -> Result { - Ok(0) +/// Deny every approval still pending, which only a turn that is over can +/// have left, as a seat runs one turn at a time; how many there were. +pub(crate) async fn deny_stale(client: &Client) -> Result { + let listed = client + .call("openhuman.approval_list_pending", json!({})) + .await?; + let pending = listed["result"].as_array().cloned().unwrap_or_default(); + let ids: Vec<&str> = pending + .iter() + .filter_map(|row| row["request_id"].as_str()) + .collect(); + for id in &ids { + let params = json!({"request_id": id, "decision": "deny"}); + client.call("openhuman.approval_decide", params).await?; + } + Ok(ids.len()) +} + +/// At most this much of a `chat_error` message is kept. +const MESSAGE: usize = 200; + +/// The harness's own failure text, one bounded line, without what a +/// provider may have put after it. +fn bounded(name: &str, kind: &str, message: &str) -> String { + let kind: String = kind + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(40) + .collect(); + let line = message.lines().next().unwrap_or_default(); + let line: String = line + .chars() + .filter(|c| !c.is_control()) + .take(MESSAGE) + .collect(); + format!("{name} ({kind}): {line}") } /// Cancel `active`, returning once its request has ended. diff --git a/harnesses.lock b/harnesses.lock index 381b5ae7..45ae7b08 100644 --- a/harnesses.lock +++ b/harnesses.lock @@ -18,3 +18,4 @@ target = "aarch64-unknown-linux-gnu" url = "https://github.com/tinyhumansai/openhuman/releases/download/v0.64.15/openhuman-core-0.64.15-aarch64-unknown-linux-gnu.tar.gz" sha256 = "eabac98af5f1feb711b4ffd48185aa06a233fa6bbcd1bcd4d733397dace03b9b" binary = "openhuman-core" +binary_sha256 = "17486cc1f85a58f2b4502ee41cad44b6aa11ee8058c3bad63dbc9994578c6634" From de44427ad5c02fc9f38fb4cbbfd563d3e188c6ee Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:44:15 +0000 Subject: [PATCH 48/49] docs: document seat reservation, visible-tool computation and approval limits Update the harness, instance and turn READMEs and the harness spec to describe the behaviour settled on 0.64.15: seats are reserved by id so a second start is refused, the model-visible tool list is computed from the effective config since no RPC reports it, and approvals time out into denials while stale ones are denied before a turn starts. Also note that a failed start reports a failed stop alongside it, keyring key files must be 0600 with 64 hex digits, and a turn failing before its thread has a transcript reports no session. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/harness/README.md | 5 ++-- .../src/instance/README.md | 10 ++++--- .../src/turn/README.md | 4 +++ docs/specs/harnesses.md | 28 +++++++++++++++---- 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/harness/README.md b/crates/tinyhivemind-openhuman-process/src/harness/README.md index 9638dcb5..c30d749a 100644 --- a/crates/tinyhivemind-openhuman-process/src/harness/README.md +++ b/crates/tinyhivemind-openhuman-process/src/harness/README.md @@ -1,7 +1,8 @@ # Harness -`OpenHumanHarness` refuses a seat `capability::check` refuses, then starts one -instance per seat and returns a `SeatRunner` around the seat. The seat starts +`OpenHumanHarness` refuses a seat `capability::check` refuses, reserves the +seat's id so that a second start is refused and a stop meanwhile stops what +starts, then starts one instance per seat and returns a `SeatRunner` around the seat. The seat starts another instance when its child has died, resumes only a thread whose transcript the instance has (`threads_transcript_get`), cancels by its `Active` turn, and kills the instance when a cancel cannot be shown to work. diff --git a/crates/tinyhivemind-openhuman-process/src/instance/README.md b/crates/tinyhivemind-openhuman-process/src/instance/README.md index 1c5bc29f..b3dd056f 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/README.md +++ b/crates/tinyhivemind-openhuman-process/src/instance/README.md @@ -5,10 +5,12 @@ matches nothing, waits out the MCP warm-up and reads each hive tool's hashed name, stops it, writes the exact allowlist and starts again. `verify` then compares `/health.pid` with the child, `core.version` with the pin, `config_get` -with what was written, and the model-visible tools with the hive tools: the -agent's effective allowlist of the tools the instance has, plus -`juice_retrieve` unless `context.compaction_enabled` is off. Any difference -stops the instance and fails the start. +with what was written, and the model-visible tools with the hive tools. No +RPC reports those, so `visible` computes them as 0.64.15's `resolved_scope` +does; see the spec's OpenHuman rules for every source it counts. Any +difference stops the instance and fails the start, and a stop that then fails +too is reported with it (`Error::Abandoned`). The keyring key file must be a +0600 file of 64 hex digits; another is refused, not replaced. | File | Purpose | | --- | --- | diff --git a/crates/tinyhivemind-openhuman-process/src/turn/README.md b/crates/tinyhivemind-openhuman-process/src/turn/README.md index 307c16d6..89146aad 100644 --- a/crates/tinyhivemind-openhuman-process/src/turn/README.md +++ b/crates/tinyhivemind-openhuman-process/src/turn/README.md @@ -6,6 +6,10 @@ the seat's `Active`, and follows that request's events: progress, approvals through the seat's approver and `approval_decide`, `chat_done` with the turn's own usage, `chat_error` and `chat_cancelled` as failures. Reaching the eight-iteration cap is a failed turn, as is passing a lower seat limit. +Approvals are denied when the approver takes longer than its limit, and an +`approval_request` without an id fails the turn. `deny_stale` denies what a +turn that is over left pending. A `chat_error` message is kept to one line of +200 characters. `cancel` is `channel_web_cancel` scoped to the request, then a wait for its end. A turn is never submitted twice. diff --git a/docs/specs/harnesses.md b/docs/specs/harnesses.md index 04a83d5a..ea951625 100644 --- a/docs/specs/harnesses.md +++ b/docs/specs/harnesses.md @@ -325,10 +325,23 @@ as failed. The runner counts `iteration_start` events to tell. What implementing it on 0.64.15 settled: -- `context.compaction_enabled` defaults on, and while it is on the binary adds - `juice_retrieve` to every allowlist. The config turns it off, and the start - check counts `juice_retrieve` as model-visible unless the effective config - has it off. +- No RPC reports the tools a custom agent's turn offers + (`agent_list_definitions` and `agent_get_definition` cover built-in agents; + the offline `openhuman agent dump-prompt --with-tools` CLI reports a + definition's tools but not a session's). So the model-visible list is + computed from the effective config the way `resolved_scope` in + `agent/tinyagents/host/definition_registry.rs` builds it: the chat agent's + allowlist, of the tools the instance has; every deferred tool if the list + names `tool_search`; the session's delegation tools for an agent with + subagents; `juice_retrieve` while compaction or the orchestrator's summary + stage is on; the REPL tools while results are stored behind a handle; and + `extra_tools`. A chat agent other than the written one counts as a + built-in's set. Any of these fails the start. The config turns compaction + off, since it defaults on. The live gate test checks the list at the model. +- A turn that fails before its thread has a transcript reports no session, + as an error, so the next turn starts the thread rather than failing to + resume one that never existed. A failure on a thread with a transcript is a + failed turn in that session. - The hashed names are known only to a running instance, so a start is two: one whose allowlist matches nothing, to read them, and the verified one. - A session is a `thread_id`, the same for a seat's life. A turn that names a @@ -338,7 +351,12 @@ What implementing it on 0.64.15 settled: before `channel_web_chat` is called, since the first events can precede its answer. Events are taken only for the returned `request_id`, except `approval_request`, whose `request_id` is the approval's. -- A cancelled turn leaves no message in the thread. +- A cancelled or failed turn leaves no message in the thread. +- An approval the harness asks for goes to the seat's approver, which has a + time limit and is a denial past it. `approval_decide` takes no reason, so a + denial's reason is not passed on. Approvals still pending when a turn starts + are left by one that is over, and are denied first. A `chat_error` message is + cut to one line of at most 200 characters before it becomes the failure. - The top-level `embeddings_provider` is rewritten to the hosted default on load whatever the file says, so it is neither written nor compared; memory is off, so nothing embeds. The binary also carries a compiled-in Sentry DSN From 6b38ad50da3923d653e6bb04730fcca344b91332 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 26 Nov 2026 00:45:06 +0000 Subject: [PATCH 49/49] refactor(instance): rename chmod helper and drop unused import Renamed the local permission helper in the keyring test to chmod with a clearer parameter name, and removed an unused AGENT_ID import from the verify module. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-openhuman-process/src/instance/test.rs | 6 +++--- .../tinyhivemind-openhuman-process/src/instance/verify.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs index ef1f99c5..bcd2f5b2 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/test.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -294,11 +294,11 @@ fn the_keyring_key_is_made_once_and_a_bad_one_is_refused() { assert!(made.bytes().all(|byte| byte.is_ascii_hexdigit())); assert_eq!(layout.master_key().ok(), Some(made)); let path = dir.path().join("keyring.key"); - let mode = |mode| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)); - assert!(mode(0o644).is_ok()); + let chmod = |bits| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(bits)); + assert!(chmod(0o644).is_ok()); assert!(matches!(layout.master_key(), Err(Error::KeyFile(_)))); for bad in ["", "abc", &"z".repeat(64)] { - assert!(std::fs::write(&path, bad).is_ok() && mode(0o600).is_ok()); + assert!(std::fs::write(&path, bad).is_ok() && chmod(0o600).is_ok()); assert!( matches!(layout.master_key(), Err(Error::KeyFile(_))), "{bad:?}" diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs index cadd0a0b..aa713c47 100644 --- a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -1,6 +1,6 @@ //! Whether a started instance is the one that was asked for, and the names //! its model sees the hive tools under. -use crate::config::{AGENT_ID, Written}; +use crate::config::Written; use crate::error::{Error, Result}; use crate::rpc::Client; use serde_json::{Value, json};