From dbd8efede11152c6c031b87a048d77618015d4b1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:29:46 +0000 Subject: [PATCH 01/66] test(storage): cover running turn call records and legacy snapshots Add tests pinning the wire form of call records on running turns and verifying that snapshots written before call records existed still load with an empty map and serialize without the field. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/storage/test.rs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/tinyhivemind-hives/src/storage/test.rs b/crates/tinyhivemind-hives/src/storage/test.rs index 49308531..20ab7bf4 100644 --- a/crates/tinyhivemind-hives/src/storage/test.rs +++ b/crates/tinyhivemind-hives/src/storage/test.rs @@ -276,3 +276,54 @@ fn retention_policy_wire_form_and_omitted_defaults_are_stable() { serde_json::json!({"settled_episodes":null,"delivered":null,"interrupted":null,"pending_per_agent":null}) ); } + +/// A running turn as a snapshot written before call records existed. +const OLDER_RUNNING_TURN: &str = r#"{ + "request": { + "turn_id": "1:4:a", "agent_id": "a", "session_id": null, + "messages": [], "memberships": [], "episode": null + }, + "turn": null, + "actions": [{"Post": {"body": "hi"}}], + "delivery_sequence": 3 +}"#; + +#[test] +fn a_running_turn_from_before_call_records_loads_with_none() { + let turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + assert!(turn.calls.is_empty()); + assert_eq!(turn.delivery_sequence, Some(3)); +} + +#[test] +fn a_running_turn_without_calls_serializes_as_before() { + let turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + let value = serde_json::to_value(&turn).unwrap(); + assert!(value.get("calls").is_none()); +} + +#[test] +fn call_records_have_a_pinned_wire_form() { + let mut turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + turn.calls.insert( + "post-1".into(), + CallRecord { + tool: "hivemind_post".into(), + arguments: serde_json::json!({"episode_id": "episode:1", "body": "hi"}), + result: serde_json::Value::Null, + }, + ); + let value = serde_json::to_value(&turn).unwrap(); + assert_eq!( + value["calls"], + serde_json::json!({ + "post-1": { + "tool": "hivemind_post", + "arguments": {"episode_id": "episode:1", "body": "hi"}, + "result": null + } + }) + ); + let back: RunningTurn = serde_json::from_value(value).unwrap(); + assert_eq!(back.calls, turn.calls); +} From 02281177dcc66e4f79db0b10ec94bb3ff8cce6e9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:30:02 +0000 Subject: [PATCH 02/66] feat(storage): record identified calls on running turns Running turns now carry a map of identified calls keyed by the caller's call id, each holding the tool, its arguments and the result, so a retry of the same call can be answered from the record instead of being repeated. The field defaults to empty so snapshots written before calls were identified still load. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/coordinator/scheduler.rs | 1 + crates/tinyhivemind-hives/src/storage/mod.rs | 4 ++-- crates/tinyhivemind-hives/src/storage/test.rs | 1 + crates/tinyhivemind-hives/src/storage/types.rs | 16 ++++++++++++++++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs index 30d6e072..517befdc 100644 --- a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs +++ b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs @@ -243,6 +243,7 @@ impl Coordinator { turn, actions: Vec::new(), delivery_sequence, + calls: BTreeMap::new(), }, ); selected.insert(agent_id); diff --git a/crates/tinyhivemind-hives/src/storage/mod.rs b/crates/tinyhivemind-hives/src/storage/mod.rs index b6566b95..a0f6b352 100644 --- a/crates/tinyhivemind-hives/src/storage/mod.rs +++ b/crates/tinyhivemind-hives/src/storage/mod.rs @@ -10,8 +10,8 @@ use crate::{Error, Result}; pub use sqlite::SqliteStorage; use std::{future::Future, pin::Pin, sync::Mutex}; pub use types::{ - AgentRecord, Delivery, DeliveryStatus, EpisodeRecord, ParkedTurn, RetentionPolicy, RunningTurn, - StoredState, TranscriptRow, + AgentRecord, CallRecord, Delivery, DeliveryStatus, EpisodeRecord, ParkedTurn, RetentionPolicy, + RunningTurn, StoredState, TranscriptRow, }; /// Future returned by a [`Storage`] operation. Boxed and `Send` so the port diff --git a/crates/tinyhivemind-hives/src/storage/test.rs b/crates/tinyhivemind-hives/src/storage/test.rs index 20ab7bf4..b4c593bd 100644 --- a/crates/tinyhivemind-hives/src/storage/test.rs +++ b/crates/tinyhivemind-hives/src/storage/test.rs @@ -254,6 +254,7 @@ fn retention_keeps_a_settled_episode_a_running_turn_still_reports_to() { turn: None, actions: Vec::new(), delivery_sequence: None, + calls: BTreeMap::new(), }, ); RetentionPolicy { diff --git a/crates/tinyhivemind-hives/src/storage/types.rs b/crates/tinyhivemind-hives/src/storage/types.rs index ab006a12..4c40c3ce 100644 --- a/crates/tinyhivemind-hives/src/storage/types.rs +++ b/crates/tinyhivemind-hives/src/storage/types.rs @@ -297,4 +297,20 @@ pub struct RunningTurn { pub actions: Vec, /// Accepted direct message sequence when present. pub delivery_sequence: Option, + /// Identified calls this turn made, by the caller's `call`, each recorded + /// in the transaction that made its effect. Absent from snapshots written + /// before calls were identified, and gone with the turn. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub calls: BTreeMap, +} +/// What one identified call of a running turn did, so that a retry of it is +/// answered rather than repeated. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct CallRecord { + /// The tool the call named. + pub tool: String, + /// Its arguments, without the call's own identity. + pub arguments: serde_json::Value, + /// What the coordinator returned. + pub result: serde_json::Value, } From b84b6a981560c9f0d0e11b8eb2f88597b3e7c555 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:30:09 +0000 Subject: [PATCH 03/66] test(storage): qualify BTreeMap path in retention test Use the fully qualified std::collections::BTreeMap path in the retention test fixture so the test compiles without relying on an import that is no longer in scope. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/storage/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinyhivemind-hives/src/storage/test.rs b/crates/tinyhivemind-hives/src/storage/test.rs index b4c593bd..48d84ed5 100644 --- a/crates/tinyhivemind-hives/src/storage/test.rs +++ b/crates/tinyhivemind-hives/src/storage/test.rs @@ -254,7 +254,7 @@ fn retention_keeps_a_settled_episode_a_running_turn_still_reports_to() { turn: None, actions: Vec::new(), delivery_sequence: None, - calls: BTreeMap::new(), + calls: std::collections::BTreeMap::new(), }, ); RetentionPolicy { From f74d14d289559de5d1b6df1af160813fa363c74e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:30:20 +0000 Subject: [PATCH 04/66] test(storage): rename running turn test to describe empty calls The test name now says the loaded turn has no calls rather than none, matching what the assertion actually checks. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/storage/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinyhivemind-hives/src/storage/test.rs b/crates/tinyhivemind-hives/src/storage/test.rs index 48d84ed5..3745647e 100644 --- a/crates/tinyhivemind-hives/src/storage/test.rs +++ b/crates/tinyhivemind-hives/src/storage/test.rs @@ -290,7 +290,7 @@ const OLDER_RUNNING_TURN: &str = r#"{ }"#; #[test] -fn a_running_turn_from_before_call_records_loads_with_none() { +fn a_running_turn_from_before_call_records_loads_with_no_calls() { let turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); assert!(turn.calls.is_empty()); assert_eq!(turn.delivery_sequence, Some(3)); From eafc9a779b7ae47e7e73b0818faf2b55f9a15422 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:31:05 +0000 Subject: [PATCH 05/66] test(coordinator): add tests for hive call handling Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/coordinator/test/calls.rs | 410 ++++++++++++++++++ 1 file changed, 410 insertions(+) create mode 100644 crates/tinyhivemind-hives/src/coordinator/test/calls.rs diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs new file mode 100644 index 00000000..219cacb6 --- /dev/null +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -0,0 +1,410 @@ +//! Identified calls: one effect per (agent, turn, call), recorded with it. +use super::transactions::Recording; +use super::*; +use crate::{SqliteStorage, Storage}; +use serde_json::{Value, json}; +use tokio::sync::{Notify, mpsc}; + +/// A turn held open by its runner until the test lets it return. +struct Held { + request: TurnRequest, + finish: Arc, + drain: tokio::task::JoinHandle>, +} +impl Held { + fn episode(&self) -> String { + self.request.episode.as_ref().unwrap().episode_id.clone() + } + fn call(&self, call: &str, tool: &str, arguments: Value) -> TurnCall { + TurnCall { + agent_id: self.request.agent_id.clone(), + turn_id: self.request.turn_id.clone(), + call: call.into(), + tool: tool.into(), + arguments, + } + } + fn post(&self, call: &str, body: &str) -> TurnCall { + self.call( + call, + "hivemind_post", + json!({"episode_id": self.episode(), "body": body}), + ) + } + async fn end(self) -> RunReport { + self.finish.notify_one(); + self.drain.await.unwrap().unwrap() + } +} +/// Register `ids`, each holding its turns open, in a hive `work`. +async fn holding(c: &Coordinator, ids: &[&str]) -> (mpsc::UnboundedReceiver, Arc) { + let (started, requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + for id in ids { + let (started, finish) = (started.clone(), finish.clone()); + add(c, id, move |request| { + let (started, finish) = (started.clone(), finish.clone()); + Box::pin(async move { + started.send(request.clone()).unwrap(); + finish.notified().await; + Ok(done(&request)) + }) + }) + .await; + } + hive(c, "work", ids).await; + (requests, finish) +} +/// Open an episode for `a` and hold its turn. +async fn hold(c: &Coordinator) -> Held { + let (mut requests, finish) = holding(c, &["a"]).await; + c.send_as_host(message("task", Destination::Hive("work".into()))) + .await + .unwrap(); + let drain = tokio::spawn({ + let c = c.clone(); + async move { c.run_until_idle().await } + }); + let request = requests.recv().await.unwrap(); + Held { + request, + finish, + drain, + } +} +fn actions(c: &Coordinator, agent: &str) -> Vec { + c.lock().unwrap().durable.running[agent].actions.clone() +} +fn posted(body: &str) -> EpisodeAction { + EpisodeAction::Post { body: body.into() } +} + +#[tokio::test] +async fn the_running_turn_is_reported_by_id() { + let c = setup().await; + assert_eq!(c.running_turn("a").unwrap(), None); + let held = hold(&c).await; + assert_eq!( + c.running_turn("a").unwrap().as_deref(), + Some(held.request.turn_id.as_str()) + ); + held.end().await; + assert_eq!(c.running_turn("a").unwrap(), None); +} + +#[tokio::test] +async fn a_retried_post_acts_once_and_returns_the_first_result() { + let c = setup().await; + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + let revision = c.lock().unwrap().durable.revision; + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + assert_eq!(actions(&c, "a"), [posted("hello")]); + // The answer came from the record, so nothing was committed. + assert_eq!(c.lock().unwrap().durable.revision, revision); + held.end().await; +} + +#[tokio::test] +async fn two_identical_posts_under_different_calls_both_act() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + for call in ["post-1", "post-2"] { + c.submit_action_in_turn(&held.post(call, "hello"), &episode, posted("hello")) + .await + .unwrap(); + } + assert_eq!(actions(&c, "a"), [posted("hello"), posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn reusing_a_call_with_other_arguments_or_another_tool_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + c.submit_action_in_turn(&held.post("one", "hello"), &episode, posted("hello")) + .await + .unwrap(); + let other_arguments = held.post("one", "goodbye"); + assert!(matches!( + c.submit_action_in_turn(&other_arguments, &episode, posted("goodbye")).await, + Err(Error::CallReused(call)) if call == "one" + )); + let mut other_tool = held.post("one", "hello"); + other_tool.tool = "hivemind_complete".into(); + let complete = EpisodeAction::Complete { + body: "hello".into(), + }; + assert!(matches!( + c.submit_action_in_turn(&other_tool, &episode, complete).await, + Err(Error::CallReused(_)) + )); + assert_eq!(actions(&c, "a"), [posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn a_call_naming_another_turn_is_refused_whatever_its_call() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + let mut stale = held.post("post-1", "hello"); + stale.turn_id = "0:0:a".into(); + assert!(matches!( + c.submit_action_in_turn(&stale, &episode, posted("hello")).await, + Err(Error::StaleTurn { agent_id, turn_id }) if agent_id == "a" && turn_id == "0:0:a" + )); + assert!(actions(&c, "a").is_empty()); + assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); + held.end().await; +} + +#[tokio::test] +async fn a_call_with_no_running_turn_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + held.end().await; + assert!(matches!( + c.submit_action_in_turn(&call, &episode, posted("hello")).await, + Err(Error::StaleTurn { .. }) + )); +} + +#[tokio::test] +async fn a_call_without_an_identity_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + let blank = held.post(" ", "hello"); + assert!(matches!( + c.submit_action_in_turn(&blank, &episode, posted("hello")).await, + Err(Error::InvalidIdentifier("call")) + )); + assert!(actions(&c, "a").is_empty()); + held.end().await; +} + +#[tokio::test] +async fn another_seats_episode_is_refused_and_records_nothing() { + let c = setup().await; + let held = hold(&c).await; + let call = held.call( + "post-1", + "hivemind_post", + json!({"episode_id": "episode:99", "body": "hello"}), + ); + assert!(matches!( + c.submit_action_in_turn(&call, "episode:99", posted("hello")).await, + Err(Error::StaleEpisode(_)) + )); + assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); + held.end().await; +} + +#[tokio::test] +async fn a_failed_commit_leaves_neither_the_effect_nor_its_record() { + let storage = Arc::new(Recording::default()); + let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + storage.fail_next_commits(1); + assert!( + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .is_err() + ); + let stored = storage.load().await.unwrap(); + assert!(stored.running["a"].actions.is_empty()); + assert!(stored.running["a"].calls.is_empty()); + assert!(actions(&c, "a").is_empty()); + // The same call then acts, once. + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + assert_eq!(actions(&c, "a"), [posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn the_record_survives_a_storage_reload_of_a_running_turn() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("hive.sqlite"); + let storage = Arc::new(SqliteStorage::open(&path).unwrap()); + let c = Coordinator::new("runtime".into(), storage, CoordinatorOptions::default()) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + c.submit_action_in_turn(&call, &held.episode(), posted("hello")) + .await + .unwrap(); + let reloaded = SqliteStorage::open(&path).unwrap().load().await.unwrap(); + assert_eq!( + reloaded.running["a"].calls["post-1"], + CallRecord { + tool: "hivemind_post".into(), + arguments: call.arguments.clone(), + result: Value::Null, + } + ); + held.end().await; +} + +#[tokio::test] +async fn after_a_coordinator_restart_the_retry_is_refused() { + let storage = Arc::new(MemoryStorage::new()); + let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + let restarted = Coordinator::new("runtime".into(), storage, CoordinatorOptions::default()) + .await + .unwrap(); + assert!(matches!( + restarted + .submit_action_in_turn(&call, &episode, posted("hello")) + .await, + Err(Error::StaleTurn { .. }) + )); + held.finish.notify_one(); + held.drain.abort(); +} + +#[tokio::test] +async fn the_record_goes_when_its_turn_ends() { + let storage = Arc::new(MemoryStorage::new()); + let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + c.submit_action_in_turn(&call, &held.episode(), posted("hello")) + .await + .unwrap(); + held.end().await; + assert!(storage.load().await.unwrap().running.is_empty()); +} + +fn direct(id: &str, sender: &str) -> SendMessage { + SendMessage { + sender: sender.into(), + ..message(id, Destination::Agent("b".into())) + } +} + +#[tokio::test] +async fn a_retried_send_acts_once_and_returns_the_first_receipt() { + let c = setup().await; + let (mut requests, finish) = holding(&c, &["a", "b"]).await; + c.send_as_host(message("task", Destination::Agent("a".into()))) + .await + .unwrap(); + let drain = tokio::spawn({ + let c = c.clone(); + async move { c.run_until_idle().await } + }); + let request = requests.recv().await.unwrap(); + let held = Held { + request, + finish, + drain, + }; + let call = held.call("send-1", "hivemind_send_agent", json!({"body": "hi"})); + let first = c.send_in_turn(&call, direct("note", "a")).await.unwrap(); + let again = c.send_in_turn(&call, direct("note", "a")).await.unwrap(); + assert_eq!(first, again); + // Two calls with one `message_id` and one payload are one message. + let other = held.call("send-2", "hivemind_send_agent", json!({"body": "hi"})); + assert_eq!(c.send_in_turn(&other, direct("note", "a")).await.unwrap(), first); + let notes = c + .read_transcript(None) + .unwrap() + .into_iter() + .filter(|message| message.message_id == "note") + .count(); + assert_eq!(notes, 1); + // A send can only be the caller's own. + let forged = held.call("send-3", "hivemind_send_agent", json!({"body": "hi"})); + assert!(matches!( + c.send_in_turn(&forged, direct("forged", "b")).await, + Err(Error::InvalidIdentifier("sender")) + )); + held.finish.notify_one(); + held.finish.notify_one(); + held.drain.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn a_retried_join_acts_once_and_returns_the_first_result() { + let c = setup().await; + let held = hold(&c).await; + c.create_hive(HiveInfo { + hive_id: "side".into(), + name: "Side".into(), + description: None, + members: Vec::new(), + }) + .await + .unwrap(); + let call = held.call( + "join-1", + "hivemind_join_hive", + json!({"hive_id": "side", "agent_id": "a"}), + ); + c.join_hive_in_turn(&call, "side", "a").await.unwrap(); + c.leave_hive("side", "a").await.unwrap(); + c.join_hive_in_turn(&call, "side", "a").await.unwrap(); + let side = c.list_hives().unwrap().into_iter().find(|h| h.hive_id == "side"); + assert!(side.unwrap().members.is_empty()); + held.end().await; +} + +#[tokio::test] +async fn hive_management_in_a_turn_acts_and_is_recorded() { + let c = setup().await; + let held = hold(&c).await; + let hive = HiveInfo { + hive_id: "side".into(), + name: "Side".into(), + description: None, + members: vec!["a".into()], + }; + let create = held.call("create-1", "hivemind_create_hive", json!({"hive_id": "side"})); + c.create_hive_in_turn(&create, hive.clone()).await.unwrap(); + let leave = held.call( + "leave-1", + "hivemind_leave_hive", + json!({"hive_id": "side", "agent_id": "a"}), + ); + c.leave_hive_in_turn(&leave, "side", "a").await.unwrap(); + c.join_hive("side", "a").await.unwrap(); + // Neither retry acts again: the hive is not recreated and `a` stays. + c.create_hive_in_turn(&create, hive).await.unwrap(); + c.leave_hive_in_turn(&leave, "side", "a").await.unwrap(); + let side = c.list_hives().unwrap().into_iter().find(|h| h.hive_id == "side"); + assert_eq!(side.unwrap().members, ["a"]); + let calls = c.lock().unwrap().durable.running["a"].calls.clone(); + assert_eq!(calls.keys().collect::>(), ["create-1", "leave-1"]); + held.end().await; +} From 1a403f68ed3772cb6286cd3317cdf3fbd2f5ef06 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:31:19 +0000 Subject: [PATCH 06/66] test(coordinator): simplify retry test setup and teardown The retried-send test now holds only agent a and registers b as an immediately completing agent, so the second request no longer needs a manual finish notification. Teardown uses the held helper's end method instead of notifying and awaiting the drain by hand, and the calls test module is now declared so it is compiled. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/coordinator/test/calls.rs | 8 +++----- crates/tinyhivemind-hives/src/coordinator/test/mod.rs | 1 + 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 219cacb6..5ac4eb25 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -287,7 +287,6 @@ async fn after_a_coordinator_restart_the_retry_is_refused() { .await, Err(Error::StaleTurn { .. }) )); - held.finish.notify_one(); held.drain.abort(); } @@ -316,7 +315,8 @@ fn direct(id: &str, sender: &str) -> SendMessage { #[tokio::test] async fn a_retried_send_acts_once_and_returns_the_first_receipt() { let c = setup().await; - let (mut requests, finish) = holding(&c, &["a", "b"]).await; + let (mut requests, finish) = holding(&c, &["a"]).await; + add(&c, "b", |request| Box::pin(async move { Ok(done(&request)) })).await; c.send_as_host(message("task", Destination::Agent("a".into()))) .await .unwrap(); @@ -350,9 +350,7 @@ async fn a_retried_send_acts_once_and_returns_the_first_receipt() { c.send_in_turn(&forged, direct("forged", "b")).await, Err(Error::InvalidIdentifier("sender")) )); - held.finish.notify_one(); - held.finish.notify_one(); - held.drain.await.unwrap().unwrap(); + held.end().await; } #[tokio::test] diff --git a/crates/tinyhivemind-hives/src/coordinator/test/mod.rs b/crates/tinyhivemind-hives/src/coordinator/test/mod.rs index a43d0c99..aa6c1d97 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/mod.rs @@ -318,6 +318,7 @@ async fn membership_removed_before_claim_prevents_later_delivery() { c.leave_hive("work", "a").await.unwrap(); assert_eq!(c.run_until_idle().await.unwrap().completed, 0); } +mod calls; mod failures; mod finalization; mod lifecycle; From d393ed34fd63f5bd86758effed9da49237231d5e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:31:42 +0000 Subject: [PATCH 07/66] refactor(coordinator): extract state mutation helpers from coordinator methods Move the hive creation, join, leave, and action staging logic out of the async methods into standalone functions that take the stored state directly, so the same validation can be exercised without going through the coordinator. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-hives/src/coordinator/mod.rs | 188 ++++++++++-------- .../src/coordinator/test/calls.rs | 75 +++++-- 2 files changed, 156 insertions(+), 107 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/mod.rs b/crates/tinyhivemind-hives/src/coordinator/mod.rs index f84d42c2..b1aaaca6 100644 --- a/crates/tinyhivemind-hives/src/coordinator/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/mod.rs @@ -202,27 +202,7 @@ impl Coordinator { pub async fn create_hive(&self, hive: HiveInfo) -> Result<()> { identifier(&hive.hive_id, "hive id")?; identifier(&hive.name, "hive name")?; - self.update(|state| { - let mut unique = BTreeSet::new(); - for member in &hive.members { - if !state.agents.contains_key(member) { - return Err(Error::UnknownAgent(member.clone())); - } - if !unique.insert(member) { - return Err(Error::DuplicateMember(member.clone())); - } - } - if let Some(existing) = state.hives.get(&hive.hive_id) { - return if existing == &hive { - Ok(()) - } else { - Err(Error::HiveConflict(hive.hive_id.clone())) - }; - } - state.hives.insert(hive.hive_id.clone(), hive.clone()); - Ok(()) - }) - .await + self.update(|state| create_hive_state(state, &hive)).await } /// List current dynamic hive definitions in ID order. /// # Errors @@ -274,33 +254,15 @@ impl Coordinator { /// # Errors /// Returns unknown hive/agent or storage errors. pub async fn join_hive(&self, hive_id: &str, agent_id: &str) -> Result<()> { - self.update(|state| { - known_agent(state, agent_id)?; - let hive = state - .hives - .get_mut(hive_id) - .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; - if !hive.members.iter().any(|id| id == agent_id) { - hive.members.push(agent_id.into()); - } - Ok(()) - }) - .await + self.update(|state| join_hive_state(state, hive_id, agent_id)) + .await } /// Leave a hive; active turns keep their captured authorization and history. /// # Errors /// Returns unknown hive/agent or storage errors. pub async fn leave_hive(&self, hive_id: &str, agent_id: &str) -> Result<()> { - self.update(|state| { - known_agent(state, agent_id)?; - let hive = state - .hives - .get_mut(hive_id) - .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; - hive.members.retain(|id| id != agent_id); - Ok(()) - }) - .await + self.update(|state| leave_hive_state(state, hive_id, agent_id)) + .await } /// Record an action for the caller's currently running episode. /// # Errors @@ -311,51 +273,8 @@ impl Coordinator { episode_id: &str, action: EpisodeAction, ) -> Result<()> { - self.update(|state| { - let running = state - .running - .get_mut(agent_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let episode = running - .request - .episode - .as_ref() - .filter(|ep| ep.episode_id == episode_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - if let EpisodeAction::Ask { agents, .. } = &action { - if agents.is_empty() { - return Err(Error::InvalidIdentifier("ask recipients")); - } - let hive = running - .request - .memberships - .iter() - .find(|hive| hive.hive_id == episode.hive_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let episode_members = state - .episodes - .iter() - .find(|record| record.episode_id == episode_id) - .map(|record| &record.hive.members) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let mut unique = BTreeSet::new(); - for target in agents { - if target == agent_id - || !hive.members.contains(target) - || !episode_members.contains(target) - || !unique.insert(target) - { - return Err(Error::NotMember { - agent_id: target.clone(), - hive_id: hive.hive_id.clone(), - }); - } - } - } - running.actions.push(action.clone()); - Ok(()) - }) - .await + self.update(|state| stage_action(state, agent_id, episode_id, &action)) + .await } /// Release a parked agent after the host settles its approval. /// Equivalent to [`Self::release_with`] without a note. @@ -439,6 +358,99 @@ fn identifier(value: &str, field: &'static str) -> Result<()> { Ok(()) } } +/// Create `hive` in `state`; an identical definition is already there. +fn create_hive_state(state: &mut StoredState, hive: &HiveInfo) -> Result<()> { + let mut unique = BTreeSet::new(); + for member in &hive.members { + if !state.agents.contains_key(member) { + return Err(Error::UnknownAgent(member.clone())); + } + if !unique.insert(member) { + return Err(Error::DuplicateMember(member.clone())); + } + } + if let Some(existing) = state.hives.get(&hive.hive_id) { + return if existing == &hive { + Ok(()) + } else { + Err(Error::HiveConflict(hive.hive_id.clone())) + }; + } + state.hives.insert(hive.hive_id.clone(), hive.clone()); + Ok(()) +} +/// Add `agent_id` to `hive_id` in `state`, unless it is a member already. +fn join_hive_state(state: &mut StoredState, hive_id: &str, agent_id: &str) -> Result<()> { + known_agent(state, agent_id)?; + let hive = state + .hives + .get_mut(hive_id) + .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; + if !hive.members.iter().any(|id| id == agent_id) { + hive.members.push(agent_id.into()); + } + Ok(()) +} +/// Remove `agent_id` from `hive_id` in `state`. +fn leave_hive_state(state: &mut StoredState, hive_id: &str, agent_id: &str) -> Result<()> { + known_agent(state, agent_id)?; + let hive = state + .hives + .get_mut(hive_id) + .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; + hive.members.retain(|id| id != agent_id); + Ok(()) +} +/// Stage `action` on `agent_id`'s running turn in `state`, for `episode_id`. +fn stage_action( + state: &mut StoredState, + agent_id: &str, + episode_id: &str, + action: &EpisodeAction, +) -> Result<()> { + let running = state + .running + .get_mut(agent_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let episode = running + .request + .episode + .as_ref() + .filter(|ep| ep.episode_id == episode_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + if let EpisodeAction::Ask { agents, .. } = action { + if agents.is_empty() { + return Err(Error::InvalidIdentifier("ask recipients")); + } + let hive = running + .request + .memberships + .iter() + .find(|hive| hive.hive_id == episode.hive_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let episode_members = state + .episodes + .iter() + .find(|record| record.episode_id == episode_id) + .map(|record| &record.hive.members) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let mut unique = BTreeSet::new(); + for target in agents { + if target == agent_id + || !hive.members.contains(target) + || !episode_members.contains(target) + || !unique.insert(target) + { + return Err(Error::NotMember { + agent_id: target.clone(), + hive_id: hive.hive_id.clone(), + }); + } + } + } + running.actions.push(action.clone()); + Ok(()) +} fn known_agent(state: &StoredState, id: &str) -> Result<()> { if state.agents.contains_key(id) { Ok(()) diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 5ac4eb25..8d39101b 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -37,7 +37,10 @@ impl Held { } } /// Register `ids`, each holding its turns open, in a hive `work`. -async fn holding(c: &Coordinator, ids: &[&str]) -> (mpsc::UnboundedReceiver, Arc) { +async fn holding( + c: &Coordinator, + ids: &[&str], +) -> (mpsc::UnboundedReceiver, Arc) { let (started, requests) = mpsc::unbounded_channel(); let finish = Arc::new(Notify::new()); for id in ids { @@ -144,7 +147,8 @@ async fn reusing_a_call_with_other_arguments_or_another_tool_is_refused() { body: "hello".into(), }; assert!(matches!( - c.submit_action_in_turn(&other_tool, &episode, complete).await, + c.submit_action_in_turn(&other_tool, &episode, complete) + .await, Err(Error::CallReused(_)) )); assert_eq!(actions(&c, "a"), [posted("hello")]); @@ -175,7 +179,8 @@ async fn a_call_with_no_running_turn_is_refused() { let episode = held.episode(); held.end().await; assert!(matches!( - c.submit_action_in_turn(&call, &episode, posted("hello")).await, + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await, Err(Error::StaleTurn { .. }) )); } @@ -187,7 +192,8 @@ async fn a_call_without_an_identity_is_refused() { let episode = held.episode(); let blank = held.post(" ", "hello"); assert!(matches!( - c.submit_action_in_turn(&blank, &episode, posted("hello")).await, + c.submit_action_in_turn(&blank, &episode, posted("hello")) + .await, Err(Error::InvalidIdentifier("call")) )); assert!(actions(&c, "a").is_empty()); @@ -204,7 +210,8 @@ async fn another_seats_episode_is_refused_and_records_nothing() { json!({"episode_id": "episode:99", "body": "hello"}), ); assert!(matches!( - c.submit_action_in_turn(&call, "episode:99", posted("hello")).await, + c.submit_action_in_turn(&call, "episode:99", posted("hello")) + .await, Err(Error::StaleEpisode(_)) )); assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); @@ -214,9 +221,13 @@ async fn another_seats_episode_is_refused_and_records_nothing() { #[tokio::test] async fn a_failed_commit_leaves_neither_the_effect_nor_its_record() { let storage = Arc::new(Recording::default()); - let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) - .await - .unwrap(); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); let held = hold(&c).await; let call = held.post("post-1", "hello"); let episode = held.episode(); @@ -269,9 +280,13 @@ async fn the_record_survives_a_storage_reload_of_a_running_turn() { #[tokio::test] async fn after_a_coordinator_restart_the_retry_is_refused() { let storage = Arc::new(MemoryStorage::new()); - let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) - .await - .unwrap(); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); let held = hold(&c).await; let call = held.post("post-1", "hello"); let episode = held.episode(); @@ -293,9 +308,13 @@ async fn after_a_coordinator_restart_the_retry_is_refused() { #[tokio::test] async fn the_record_goes_when_its_turn_ends() { let storage = Arc::new(MemoryStorage::new()); - let c = Coordinator::new("runtime".into(), storage.clone(), CoordinatorOptions::default()) - .await - .unwrap(); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); let held = hold(&c).await; let call = held.post("post-1", "hello"); c.submit_action_in_turn(&call, &held.episode(), posted("hello")) @@ -316,7 +335,10 @@ fn direct(id: &str, sender: &str) -> SendMessage { async fn a_retried_send_acts_once_and_returns_the_first_receipt() { let c = setup().await; let (mut requests, finish) = holding(&c, &["a"]).await; - add(&c, "b", |request| Box::pin(async move { Ok(done(&request)) })).await; + add(&c, "b", |request| { + Box::pin(async move { Ok(done(&request)) }) + }) + .await; c.send_as_host(message("task", Destination::Agent("a".into()))) .await .unwrap(); @@ -336,7 +358,10 @@ async fn a_retried_send_acts_once_and_returns_the_first_receipt() { assert_eq!(first, again); // Two calls with one `message_id` and one payload are one message. let other = held.call("send-2", "hivemind_send_agent", json!({"body": "hi"})); - assert_eq!(c.send_in_turn(&other, direct("note", "a")).await.unwrap(), first); + assert_eq!( + c.send_in_turn(&other, direct("note", "a")).await.unwrap(), + first + ); let notes = c .read_transcript(None) .unwrap() @@ -373,7 +398,11 @@ async fn a_retried_join_acts_once_and_returns_the_first_result() { c.join_hive_in_turn(&call, "side", "a").await.unwrap(); c.leave_hive("side", "a").await.unwrap(); c.join_hive_in_turn(&call, "side", "a").await.unwrap(); - let side = c.list_hives().unwrap().into_iter().find(|h| h.hive_id == "side"); + let side = c + .list_hives() + .unwrap() + .into_iter() + .find(|h| h.hive_id == "side"); assert!(side.unwrap().members.is_empty()); held.end().await; } @@ -388,7 +417,11 @@ async fn hive_management_in_a_turn_acts_and_is_recorded() { description: None, members: vec!["a".into()], }; - let create = held.call("create-1", "hivemind_create_hive", json!({"hive_id": "side"})); + let create = held.call( + "create-1", + "hivemind_create_hive", + json!({"hive_id": "side"}), + ); c.create_hive_in_turn(&create, hive.clone()).await.unwrap(); let leave = held.call( "leave-1", @@ -400,7 +433,11 @@ async fn hive_management_in_a_turn_acts_and_is_recorded() { // Neither retry acts again: the hive is not recreated and `a` stays. c.create_hive_in_turn(&create, hive).await.unwrap(); c.leave_hive_in_turn(&leave, "side", "a").await.unwrap(); - let side = c.list_hives().unwrap().into_iter().find(|h| h.hive_id == "side"); + let side = c + .list_hives() + .unwrap() + .into_iter() + .find(|h| h.hive_id == "side"); assert_eq!(side.unwrap().members, ["a"]); let calls = c.lock().unwrap().durable.running["a"].calls.clone(); assert_eq!(calls.keys().collect::>(), ["create-1", "leave-1"]); From 5472a781b095a511466e826699b1feece29d3acd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:31:48 +0000 Subject: [PATCH 08/66] refactor(coordinator): remove redundant reference in hive comparison Simplify the equality check against the stored hive entry by comparing the value directly instead of taking an extra reference, with no change in behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/coordinator/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/mod.rs b/crates/tinyhivemind-hives/src/coordinator/mod.rs index b1aaaca6..bd91fa9c 100644 --- a/crates/tinyhivemind-hives/src/coordinator/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/mod.rs @@ -370,7 +370,7 @@ fn create_hive_state(state: &mut StoredState, hive: &HiveInfo) -> Result<()> { } } if let Some(existing) = state.hives.get(&hive.hive_id) { - return if existing == &hive { + return if existing == hive { Ok(()) } else { Err(Error::HiveConflict(hive.hive_id.clone())) From 830dac3852e0aa702aeeeeae6b8067ecba372150 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:32:04 +0000 Subject: [PATCH 09/66] refactor(coordinator): extract message admission and acceptance helpers The send path now delegates identifier validation to an `admissible` helper and the transactional body to an `accept_state` function, so the same logic can be reused outside the coordinator's update closure. Behaviour is unchanged. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/coordinator/messaging.rs | 198 ++++++++++-------- 1 file changed, 105 insertions(+), 93 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/messaging.rs b/crates/tinyhivemind-hives/src/coordinator/messaging.rs index 1d88ceab..30db0eb5 100644 --- a/crates/tinyhivemind-hives/src/coordinator/messaging.rs +++ b/crates/tinyhivemind-hives/src/coordinator/messaging.rs @@ -41,100 +41,10 @@ impl Coordinator { request: SendMessage, scheduled_job_id: Option, ) -> Result { - identifier(&request.message_id, "message id")?; - if request.message_id.starts_with("hivemind:") { - return Err(Error::InvalidIdentifier("reserved message id")); - } + admissible(&request)?; let retention = self.inner.options.retention; - self.update(|state| { - let scheduled_job_id = scheduled_job_id.clone().or_else(|| { - state - .running - .get(&request.sender) - .and_then(|running| running.request.scheduled_job_id.clone()) - }); - if let Some(receipt) = retry_receipt(state, &request, scheduled_job_id.as_deref())? { - return Ok(receipt); - } - let recipients = recipients(state, &request)?; - let only_for = narrow_readers( - state, - &request.destination, - request.thread, - request.only_for.clone(), - )?; - let sequence = next_sequence(state)?; - let episode_id = matches!(request.destination, Destination::Hive(_)) - .then(|| format!("episode:{sequence}")); - let message = Message { - scheduled_job_id: scheduled_job_id.clone(), - message_id: request.message_id.clone(), - sequence, - sender: request.sender.clone(), - destination: request.destination.clone(), - body: request.body.clone(), - thread: request.thread, - episode_id: episode_id.clone(), - only_for, - }; - match &request.destination { - Destination::Agent(_) => { - for agent_id in &recipients { - retention.admit_pending(state, agent_id)?; - } - for agent_id in recipients { - state.deliveries.push(Delivery { - sequence, - agent_id, - status: DeliveryStatus::Pending, - }); - } - } - Destination::Hive(id) => { - let mut hive = state - .hives - .get(id) - .cloned() - .ok_or_else(|| Error::UnknownHive(id.clone()))?; - if request.thread.is_some() { - let scope = thread_readers(state, &request.destination, request.thread)?; - if !scope.is_empty() { - hive.members.retain(|member| scope.contains(member)); - } - } - let id = episode_id - .ok_or_else(|| Error::InvalidState("hive message has no episode".into()))?; - state.episodes.push(EpisodeRecord { - settings: state.hive_settings.get(&hive.hive_id).cloned(), - scheduled_job_id: scheduled_job_id.clone(), - episode_id: id, - hive, - opened_at: sequence, - thread: request.thread, - starters: if request.starters.is_empty() { - recipients.clone() - } else { - request.starters.clone() - }, - conductor: None, - pending: Vec::new(), - wave_open: false, - waiting: false, - finished: false, - failure: None, - }); - } - } - state.messages.push(message); - state - .accepted - .insert(request.message_id.clone(), request.clone()); - Ok(Receipt { - message_id: request.message_id.clone(), - sequence, - }) - }) - .await + self.update(|state| accept_state(state, &request, scheduled_job_id.clone(), retention)) + .await } /// Read the caller's direct conversation with a registered peer in durable /// sequence order, including replies returned by the peer's runner. @@ -203,6 +113,108 @@ impl Coordinator { .collect()) } } +/// Refuse a request whose identity no transaction could accept. +pub(super) fn admissible(request: &SendMessage) -> Result<()> { + identifier(&request.message_id, "message id")?; + if request.message_id.starts_with("hivemind:") { + return Err(Error::InvalidIdentifier("reserved message id")); + } + Ok(()) +} +/// Accept `request` into `state`, or answer its retry with the first receipt. +pub(super) fn accept_state( + state: &mut StoredState, + request: &SendMessage, + scheduled_job_id: Option, + retention: crate::RetentionPolicy, +) -> Result { + let scheduled_job_id = scheduled_job_id.or_else(|| { + state + .running + .get(&request.sender) + .and_then(|running| running.request.scheduled_job_id.clone()) + }); + if let Some(receipt) = retry_receipt(state, request, scheduled_job_id.as_deref())? { + return Ok(receipt); + } + let recipients = recipients(state, request)?; + let only_for = narrow_readers( + state, + &request.destination, + request.thread, + request.only_for.clone(), + )?; + let sequence = next_sequence(state)?; + let episode_id = + matches!(request.destination, Destination::Hive(_)).then(|| format!("episode:{sequence}")); + let message = Message { + scheduled_job_id: scheduled_job_id.clone(), + message_id: request.message_id.clone(), + sequence, + sender: request.sender.clone(), + destination: request.destination.clone(), + body: request.body.clone(), + thread: request.thread, + episode_id: episode_id.clone(), + only_for, + }; + match &request.destination { + Destination::Agent(_) => { + for agent_id in &recipients { + retention.admit_pending(state, agent_id)?; + } + for agent_id in recipients { + state.deliveries.push(Delivery { + sequence, + agent_id, + status: DeliveryStatus::Pending, + }); + } + } + Destination::Hive(id) => { + let mut hive = state + .hives + .get(id) + .cloned() + .ok_or_else(|| Error::UnknownHive(id.clone()))?; + if request.thread.is_some() { + let scope = thread_readers(state, &request.destination, request.thread)?; + if !scope.is_empty() { + hive.members.retain(|member| scope.contains(member)); + } + } + let id = episode_id + .ok_or_else(|| Error::InvalidState("hive message has no episode".into()))?; + state.episodes.push(EpisodeRecord { + settings: state.hive_settings.get(&hive.hive_id).cloned(), + scheduled_job_id: scheduled_job_id.clone(), + episode_id: id, + hive, + opened_at: sequence, + thread: request.thread, + starters: if request.starters.is_empty() { + recipients.clone() + } else { + request.starters.clone() + }, + conductor: None, + pending: Vec::new(), + wave_open: false, + waiting: false, + finished: false, + failure: None, + }); + } + } + state.messages.push(message); + state + .accepted + .insert(request.message_id.clone(), request.clone()); + Ok(Receipt { + message_id: request.message_id.clone(), + sequence, + }) +} pub(super) fn membership(state: &StoredState, agent_id: &str, hive_id: &str) -> Result<()> { let hive = state .hives From 73d6b48ca9ad38375861700742b02aa7d267b005 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:32:21 +0000 Subject: [PATCH 10/66] feat(coordinator): add identified turn calls with replay and reuse checks Introduce a TurnCall type that binds a state-changing call to an agent, its running turn, and a caller-chosen identity, so a retry with the same tool and arguments returns the recorded result while any other reuse is refused. Two new errors report calls that name a turn which is not the agent's running one and calls that reuse an identity with different tool or arguments. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-hives/src/coordinator/mod.rs | 3 ++- .../src/coordinator/types.rs | 18 ++++++++++++++++++ crates/tinyhivemind-hives/src/error.rs | 13 +++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/mod.rs b/crates/tinyhivemind-hives/src/coordinator/mod.rs index bd91fa9c..86a83d91 100644 --- a/crates/tinyhivemind-hives/src/coordinator/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/mod.rs @@ -1,4 +1,5 @@ //! Agent registration, messaging, and conducted scheduling. +mod calls; mod conduct; mod messaging; mod observe; @@ -21,7 +22,7 @@ use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; pub use types::{ AgentRegistration, AgentRunner, CoordinatorOptions, Destination, EpisodeAction, EpisodeContext, EpisodePhase, EpisodeStatus, HOST_ID, HiveInfo, InterruptedTurn, Message, Receipt, RunReport, - SendMessage, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, + SendMessage, TurnCall, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, }; /// Cloneable shared coordinator; all clones share runners, inboxes and locks. diff --git a/crates/tinyhivemind-hives/src/coordinator/types.rs b/crates/tinyhivemind-hives/src/coordinator/types.rs index 7b44f221..c23d003e 100644 --- a/crates/tinyhivemind-hives/src/coordinator/types.rs +++ b/crates/tinyhivemind-hives/src/coordinator/types.rs @@ -179,6 +179,24 @@ pub struct SendMessage { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub starters: Vec, } +/// One state-changing call made from a running turn, and who made it. +/// +/// `(agent_id, turn_id, call)` identifies it: the first call with an identity +/// acts and is recorded with its effect, a retry with the same `tool` and +/// `arguments` returns the recorded result, and any other reuse is refused. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct TurnCall { + /// Agent the host bound the call to. + pub agent_id: String, + /// Turn the call says it belongs to; it must be the agent's running one. + pub turn_id: String, + /// Caller-chosen identity, unique per intended action within the turn. + pub call: String, + /// Tool the call names. + pub tool: String, + /// Its arguments, without `turn_id` or `call`. + pub arguments: serde_json::Value, +} /// Receipt returned without waiting for the destination agent. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct Receipt { diff --git a/crates/tinyhivemind-hives/src/error.rs b/crates/tinyhivemind-hives/src/error.rs index 9f42d1ba..1cba4363 100644 --- a/crates/tinyhivemind-hives/src/error.rs +++ b/crates/tinyhivemind-hives/src/error.rs @@ -51,6 +51,19 @@ pub enum Error { /// No active bound episode turn admits the action. #[error("stale episode {0}")] StaleEpisode(String), + /// An identified call names a turn that is not its agent's running one, + /// or its agent has no running turn. + #[error("turn {turn_id} is not the running turn of {agent_id}")] + StaleTurn { + /// Agent the call was made as. + agent_id: String, + /// Turn the call named. + turn_id: String, + }, + /// An identified call reuses a `call` its turn already made with another + /// tool or other arguments. + #[error("call {0} was already made with another tool or arguments")] + CallReused(String), /// Store revision changed before commit. #[error("storage revision conflict: expected {expected}, found {actual}")] RevisionConflict { From 8c3ed0933b75dc2eb8b0514d69118684d7e5f2ae Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:32:48 +0000 Subject: [PATCH 11/66] feat(coordinator): add calls module for coordinator hive Introduce a calls module under the coordinator to handle call-related coordination logic within the hive. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/coordinator/calls.rs | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 crates/tinyhivemind-hives/src/coordinator/calls.rs diff --git a/crates/tinyhivemind-hives/src/coordinator/calls.rs b/crates/tinyhivemind-hives/src/coordinator/calls.rs new file mode 100644 index 00000000..006e3ee0 --- /dev/null +++ b/crates/tinyhivemind-hives/src/coordinator/calls.rs @@ -0,0 +1,143 @@ +//! Identified calls: an action taken from a running turn, recorded with it. +//! +//! Each `*_in_turn` entry point checks the call's turn, answers a known call +//! from its record, or acts and records the call, all inside one transaction: +//! a commit holds both the effect and its record, or neither. The record lives +//! on the [`crate::RunningTurn`] and goes when the turn ends. A coordinator +//! restart interrupts every running turn, so a retry after one is refused as +//! stale rather than answered. +use super::{ + Coordinator, EpisodeAction, HiveInfo, Receipt, SendMessage, TurnCall, create_hive_state, + identifier, join_hive_state, leave_hive_state, + messaging::{accept_state, admissible}, + stage_action, +}; +use crate::{CallRecord, Error, Result, StoredState}; +use serde::{Serialize, de::DeserializeOwned}; + +impl Coordinator { + /// The id of `agent_id`'s running turn, if it has one. + /// # Errors + /// Returns a poisoned shared lock error. + pub fn running_turn(&self, agent_id: &str) -> Result> { + Ok(self + .lock()? + .durable + .running + .get(agent_id) + .map(|running| running.request.turn_id.clone())) + } + /// [`Self::submit_action`] as an identified call of the caller's running turn. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::submit_action`]. + pub async fn submit_action_in_turn( + &self, + call: &TurnCall, + episode_id: &str, + action: EpisodeAction, + ) -> Result<()> { + self.in_turn(call, |state| { + stage_action(state, &call.agent_id, episode_id, &action) + }) + .await + } + /// [`Self::send`] as an identified call; the sender must be the caller. + /// + /// The send's `message_id` is still checked, after `call`: two calls that + /// send one `message_id` with one payload are one message. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, a + /// sender other than the caller, or the errors of [`Self::send`]. + pub async fn send_in_turn(&self, call: &TurnCall, request: SendMessage) -> Result { + if request.sender != call.agent_id { + return Err(Error::InvalidIdentifier("sender")); + } + admissible(&request)?; + let retention = self.inner.options.retention; + self.in_turn(call, |state| accept_state(state, &request, None, retention)) + .await + } + /// [`Self::create_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::create_hive`]. + pub async fn create_hive_in_turn(&self, call: &TurnCall, hive: HiveInfo) -> Result<()> { + identifier(&hive.hive_id, "hive id")?; + identifier(&hive.name, "hive name")?; + self.in_turn(call, |state| create_hive_state(state, &hive)) + .await + } + /// [`Self::join_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::join_hive`]. + pub async fn join_hive_in_turn( + &self, + call: &TurnCall, + hive_id: &str, + agent_id: &str, + ) -> Result<()> { + self.in_turn(call, |state| join_hive_state(state, hive_id, agent_id)) + .await + } + /// [`Self::leave_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::leave_hive`]. + pub async fn leave_hive_in_turn( + &self, + call: &TurnCall, + hive_id: &str, + agent_id: &str, + ) -> Result<()> { + self.in_turn(call, |state| leave_hive_state(state, hive_id, agent_id)) + .await + } + /// Check `call`'s turn, then answer it from its record or run `act` and + /// record it, in one transaction. A recorded answer commits nothing. + async fn in_turn( + &self, + call: &TurnCall, + mut act: impl FnMut(&mut StoredState) -> Result, + ) -> Result { + identifier(&call.agent_id, "agent id")?; + identifier(&call.turn_id, "turn id")?; + identifier(&call.call, "call")?; + let stale = || Error::StaleTurn { + agent_id: call.agent_id.clone(), + turn_id: call.turn_id.clone(), + }; + let gate = self.inner.writer.lock().await; + let value = self + .transact(&gate, |state| { + let running = state + .running + .get(&call.agent_id) + .filter(|running| running.request.turn_id == call.turn_id) + .ok_or_else(stale)?; + if let Some(record) = running.calls.get(&call.call) { + if record.tool != call.tool || record.arguments != call.arguments { + return Err(Error::CallReused(call.call.clone())); + } + return Ok((false, serde_json::from_value(record.result.clone())?)); + } + let value = act(state)?; + let record = CallRecord { + tool: call.tool.clone(), + arguments: call.arguments.clone(), + result: serde_json::to_value(&value)?, + }; + state + .running + .get_mut(&call.agent_id) + .ok_or_else(stale)? + .calls + .insert(call.call.clone(), record); + Ok((true, value)) + }) + .await?; + self.inner.notify.notify_one(); + Ok(value) + } +} From fcd536ebdcc9e28ab663f9221caa9600cbb94e16 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:33:01 +0000 Subject: [PATCH 12/66] test(coordinator): import CallRecord in calls test module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/coordinator/test/calls.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 8d39101b..1197e34c 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -1,7 +1,7 @@ //! Identified calls: one effect per (agent, turn, call), recorded with it. use super::transactions::Recording; use super::*; -use crate::{SqliteStorage, Storage}; +use crate::{CallRecord, SqliteStorage, Storage}; use serde_json::{Value, json}; use tokio::sync::{Notify, mpsc}; From ad3aa263070c04529772f255114ec1ffeddd2490 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:33:18 +0000 Subject: [PATCH 13/66] test(coordinator): hold only the first turn in the holding helper The holding helper now blocks only the turn a test actually receives, so later turns such as the conductor's nudges return immediately instead of stalling on a notification that is never signalled. The doc comment was updated to match the narrower behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-hives/src/coordinator/test/calls.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 1197e34c..0a8c205b 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -36,7 +36,8 @@ impl Held { self.drain.await.unwrap().unwrap() } } -/// Register `ids`, each holding its turns open, in a hive `work`. +/// Register `ids` in a hive `work`, each holding a turn open while its +/// request is being received. async fn holding( c: &Coordinator, ids: &[&str], @@ -48,8 +49,11 @@ async fn holding( add(c, id, move |request| { let (started, finish) = (started.clone(), finish.clone()); Box::pin(async move { - started.send(request.clone()).unwrap(); - finish.notified().await; + // Only the turn a test receives is held; later ones, such as + // the conductor's nudges, return at once. + if started.send(request.clone()).is_ok() { + finish.notified().await; + } Ok(done(&request)) }) }) From 73439649b15242b3e4e1df72f709690133fc99bc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:33:47 +0000 Subject: [PATCH 14/66] refactor(storage): add constructor for freshly claimed running turns Introduce a `RunningTurn::claimed` constructor that builds a turn with no staged actions and no recorded calls, and use it in the scheduler instead of assembling the struct inline. This keeps the initial state of a claimed turn defined in one place. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/coordinator/scheduler.rs | 12 ++---------- .../src/coordinator/test/calls.rs | 6 +++--- crates/tinyhivemind-hives/src/storage/types.rs | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs index 517befdc..31f0cc1a 100644 --- a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs +++ b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs @@ -236,16 +236,8 @@ impl Coordinator { episode, resumption, }; - next.running.insert( - agent_id.clone(), - RunningTurn { - request: request.clone(), - turn, - actions: Vec::new(), - delivery_sequence, - calls: BTreeMap::new(), - }, - ); + let running = RunningTurn::claimed(request.clone(), turn, delivery_sequence); + next.running.insert(agent_id.clone(), running); selected.insert(agent_id); claims.push(Claim { runner, request }); } diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 0a8c205b..2f9d9ed4 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -170,7 +170,7 @@ async fn a_call_naming_another_turn_is_refused_whatever_its_call() { c.submit_action_in_turn(&stale, &episode, posted("hello")).await, Err(Error::StaleTurn { agent_id, turn_id }) if agent_id == "a" && turn_id == "0:0:a" )); - assert!(actions(&c, "a").is_empty()); + assert_eq!(actions(&c, "a"), Vec::::new()); assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); held.end().await; } @@ -200,7 +200,7 @@ async fn a_call_without_an_identity_is_refused() { .await, Err(Error::InvalidIdentifier("call")) )); - assert!(actions(&c, "a").is_empty()); + assert_eq!(actions(&c, "a"), Vec::::new()); held.end().await; } @@ -244,7 +244,7 @@ async fn a_failed_commit_leaves_neither_the_effect_nor_its_record() { let stored = storage.load().await.unwrap(); assert!(stored.running["a"].actions.is_empty()); assert!(stored.running["a"].calls.is_empty()); - assert!(actions(&c, "a").is_empty()); + assert_eq!(actions(&c, "a"), Vec::::new()); // The same call then acts, once. c.submit_action_in_turn(&call, &episode, posted("hello")) .await diff --git a/crates/tinyhivemind-hives/src/storage/types.rs b/crates/tinyhivemind-hives/src/storage/types.rs index 4c40c3ce..bc23904d 100644 --- a/crates/tinyhivemind-hives/src/storage/types.rs +++ b/crates/tinyhivemind-hives/src/storage/types.rs @@ -303,6 +303,22 @@ pub struct RunningTurn { #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub calls: BTreeMap, } +impl RunningTurn { + /// A turn just claimed: nothing staged and no call made yet. + pub(crate) fn claimed( + request: TurnRequest, + turn: Option, + delivery_sequence: Option, + ) -> Self { + Self { + request, + turn, + actions: Vec::new(), + delivery_sequence, + calls: BTreeMap::new(), + } + } +} /// What one identified call of a running turn did, so that a retry of it is /// answered rather than repeated. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] From 94e0cdfbb116fb317e5c563e98bd8ef0e1d4bfc9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:33:58 +0000 Subject: [PATCH 15/66] test(coordinator): use assert_eq for empty collection checks Replace the is_empty assertions on stored actions and side hive members with assert_eq against empty vectors so failures print the actual contents. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/src/coordinator/test/calls.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs index 2f9d9ed4..fe94a5cf 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -242,7 +242,7 @@ async fn a_failed_commit_leaves_neither_the_effect_nor_its_record() { .is_err() ); let stored = storage.load().await.unwrap(); - assert!(stored.running["a"].actions.is_empty()); + assert_eq!(stored.running["a"].actions, Vec::::new()); assert!(stored.running["a"].calls.is_empty()); assert_eq!(actions(&c, "a"), Vec::::new()); // The same call then acts, once. @@ -407,7 +407,7 @@ async fn a_retried_join_acts_once_and_returns_the_first_result() { .unwrap() .into_iter() .find(|h| h.hive_id == "side"); - assert!(side.unwrap().members.is_empty()); + assert_eq!(side.unwrap().members, Vec::::new()); held.end().await; } From a26a2fb2b531389abcb2bb9c130aa1f0f6d7a5d2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:34:14 +0000 Subject: [PATCH 16/66] docs(hives): document identified turn calls Adds README coverage for the `TurnCall` mechanism that lets out-of-process hosts distinguish transport retries from new actions, describing the `*_in_turn` entry points, how retries are answered from recorded results, and how stale turns and reused calls are refused. Also documents the new `RunningTurn::calls` record and its backward-compatible serialization, plus the corresponding test module. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-hives/README.md | 5 +++++ .../src/coordinator/README.md | 17 +++++++++++++++++ .../src/coordinator/test/README.md | 1 + crates/tinyhivemind-hives/src/storage/README.md | 5 +++++ 4 files changed, 28 insertions(+) diff --git a/crates/tinyhivemind-hives/README.md b/crates/tinyhivemind-hives/README.md index a37d1bb0..9141f9f1 100644 --- a/crates/tinyhivemind-hives/README.md +++ b/crates/tinyhivemind-hives/README.md @@ -25,6 +25,11 @@ The host reads everything with `read_transcript`, including replies to episode without hiding the message, and `release_with` hands a parked agent a note on its next turn. +A host serving tools out of process identifies each state-changing call with +a `TurnCall` and uses the `*_in_turn` entry points: a retry is answered from a +record written with the effect, and a call naming a turn that is not running is +refused. + Direct sends return durable receipts without awaiting peers. `read_direct` exposes only the caller/peer pair, including returned replies, and starts no turn. Hive reads enforce membership and private thread audiences. diff --git a/crates/tinyhivemind-hives/src/coordinator/README.md b/crates/tinyhivemind-hives/src/coordinator/README.md index 34293677..8d49b118 100644 --- a/crates/tinyhivemind-hives/src/coordinator/README.md +++ b/crates/tinyhivemind-hives/src/coordinator/README.md @@ -13,6 +13,7 @@ same input. `release_with` remains the host's manual release operation. | `settings.rs` | Per-hive native policy and retained roles, frozen at acceptance | | `types.rs` | Host runner port and public payloads | | `messaging.rs` | Atomic acceptance, retry IDs, starters, attribution, and private reads | +| `calls.rs` | Identified calls of a running turn: the `*_in_turn` entry points and `running_turn` | | `observe.rs` | Host transcript, committed-revision watch, episode status | | `conduct.rs` | Actual `CompletionDriver`/`Conductor` checkpoint lifecycle | | `scheduler.rs` | FIFO reservations, concurrent futures, shutdown, cancellation | @@ -98,3 +99,19 @@ use the driver's deterministic single-owner fallback. Native routing policy and roles reach the routing request, and widths remain bounded, but confidence, clarification and high-impact thresholds cannot change fallback selection. Configuring these thresholds does not activate a model client. + +## Identified calls + +A host that serves tools out of process cannot tell a transport retry from a +second intended action, so a state-changing call carries a `TurnCall`: the +agent, the turn it says it belongs to, a caller-chosen `call`, and the tool and +arguments. `submit_action_in_turn`, `send_in_turn`, `create_hive_in_turn`, +`join_hive_in_turn` and `leave_hive_in_turn` check in one transaction that the +turn is the agent's running one (`StaleTurn` otherwise), answer a known `call` +with the same tool and arguments from its record without committing, refuse +any other reuse (`CallReused`), or act and record the call with its result on +the `RunningTurn`. A failed commit leaves neither. The record ends with its +turn, and a restart interrupts every running turn, so a retry after one is +refused as stale. `send_in_turn` refuses a sender other than the caller and +still checks `message_id` after `call`. The unidentified entry points are +unchanged. diff --git a/crates/tinyhivemind-hives/src/coordinator/test/README.md b/crates/tinyhivemind-hives/src/coordinator/test/README.md index a2712df0..b961471f 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/README.md +++ b/crates/tinyhivemind-hives/src/coordinator/test/README.md @@ -12,6 +12,7 @@ | `transactions.rs` | Incremental appends, conflict reload/retry, storage failure, cancelled-turn flush, retention | | `observation.rs` | Host transcript reads, the revision watch, episode phases | | `starters.rs` | Host-chosen starters, their validation, and the unchanged wire form | +| `calls.rs` | Identified calls: retries answered once, reuse and stale turns refused, failed commits, reload and restart | | `release.rs` | Release notes delivered once, across restart, and the unchanged wire form | Tests use scripted runner futures, barriers, and notifications. They require no diff --git a/crates/tinyhivemind-hives/src/storage/README.md b/crates/tinyhivemind-hives/src/storage/README.md index 76b26eb5..18a2af0a 100644 --- a/crates/tinyhivemind-hives/src/storage/README.md +++ b/crates/tinyhivemind-hives/src/storage/README.md @@ -34,3 +34,8 @@ from current memberships. Every episode freezes its settings and scheduled job identity. Transcript rows persist scheduled authority on `Message`, while running reservations retain it in `TurnRequest`; legacy rows default to no explicit settings or scheduled origin. + +`RunningTurn::calls` maps each identified call of the turn to its +`CallRecord` (tool, arguments, result). It is omitted when empty, so a +snapshot written before it existed loads unchanged and a turn without +identified calls serializes as before. From 5dd0c26280f9ef67c9cdb7f6f94e0f425aa8cb62 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:34:45 +0000 Subject: [PATCH 17/66] feat(host): add identified tool test module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tools/test/identified.rs | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 crates/tinyhivemind-host/src/tools/test/identified.rs diff --git a/crates/tinyhivemind-host/src/tools/test/identified.rs b/crates/tinyhivemind-host/src/tools/test/identified.rs new file mode 100644 index 00000000..ed70da8f --- /dev/null +++ b/crates/tinyhivemind-host/src/tools/test/identified.rs @@ -0,0 +1,188 @@ +//! A call identified by its turn acts once, through the coordinator's record. +use super::support::{coordinator, hive}; +use crate::{ + Error, Result, + policy::{ + AgentCreator, CreateFuture, Management, ManagementAuthorizer, ManagementRequest, NewAgent, + }, + tools::{Belt, Kind, ToolCall}, +}; +use serde_json::{Value, json}; +use std::sync::Arc; +use tinyhivemind_hives::{ + AgentRegistration, AgentRunner, Coordinator, Destination, HiveInfo, SendMessage, + TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, +}; +use tokio::sync::{Notify, mpsc}; + +/// Hands its first turn's request to the test and holds that turn open. +struct Holds { + started: mpsc::UnboundedSender, + finish: Arc, +} +impl AgentRunner for Holds { + fn run(&self, request: TurnRequest) -> TurnFuture { + let (started, finish) = (self.started.clone(), self.finish.clone()); + Box::pin(async move { + if started.send(request.clone()).is_ok() { + finish.notified().await; + } + Ok(TurnOutcome { + session_id: "stable".into(), + reply: None, + disposition: TurnDisposition::Completed, + }) + }) + } +} +/// Admits everything; creates nothing. +struct Open; +impl ManagementAuthorizer for Open { + fn authorize(&self, _: &str, _: &ManagementRequest) -> Result<()> { + Ok(()) + } +} +impl AgentCreator for Open { + fn create(&self, _: NewAgent) -> CreateFuture<'_> { + Box::pin(async { Err(Error::Host("creates nothing".into())) }) + } +} + +/// `a`'s running turn in hive `h`, with `b` registered beside it. +async fn running() -> Result<(Coordinator, TurnRequest, Arc)> { + let coordinator = coordinator().await?; + let (started, mut requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + for id in ["a", "b"] { + coordinator + .register_agent(AgentRegistration { + agent_id: id.into(), + runtime_id: "r".into(), + runner: Arc::new(Holds { + started: started.clone(), + finish: finish.clone(), + }), + }) + .await?; + } + coordinator.create_hive(hive(&["a"])).await?; + coordinator + .send_as_host(SendMessage { + message_id: "start".into(), + sender: String::new(), + destination: Destination::Hive("h".into()), + body: "work".into(), + thread: None, + only_for: vec![], + starters: Vec::new(), + }) + .await?; + tokio::spawn({ + let coordinator = coordinator.clone(); + async move { coordinator.run_until_idle().await } + }); + let request = requests.recv().await.ok_or(Error::ManagementDisabled)?; + Ok((coordinator, request, finish)) +} +fn identified(request: &TurnRequest, call: &str, kind: Kind, args: Value) -> Result { + Ok(ToolCall::new(&request.agent_id, None, kind, args)?.in_turn(&request.turn_id, call)) +} +fn episode(request: &TurnRequest) -> String { + request + .episode + .as_ref() + .map(|episode| episode.episode_id.clone()) + .unwrap_or_default() +} + +#[tokio::test] +async fn an_identified_post_retried_acts_once_and_another_call_acts_again() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"episode_id": episode(&request), "body": "once"}); + let first = identified(&request, "p1", Kind::Post, args.clone())?; + assert_eq!(belt.call(&first).await?, json!({"accepted": true})); + assert_eq!(belt.call(&first).await?, json!({"accepted": true})); + let second = identified(&request, "p2", Kind::Post, args)?; + belt.call(&second).await?; + let reused = identified( + &request, + "p1", + Kind::Post, + json!({"episode_id": episode(&request), "body": "changed"}), + )?; + assert!(matches!( + belt.call(&reused).await, + Err(Error::Coordinator(tinyhivemind_hives::Error::CallReused(_))) + )); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn an_identified_call_naming_another_turn_is_refused() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"episode_id": episode(&request), "body": "late"}); + let stale = ToolCall::new("a", None, Kind::Post, args)?.in_turn("0:0:a", "p1"); + assert!(matches!( + belt.call(&stale).await, + Err(Error::Coordinator(tinyhivemind_hives::Error::StaleTurn { .. })) + )); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn an_identified_send_retried_returns_the_first_receipt() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"agent_id": "b", "message_id": "m1", "body": "hi"}); + let send = identified(&request, "s1", Kind::SendAgent, args)?; + let receipt = belt.call(&send).await?; + assert_eq!(belt.call(&send).await?, receipt); + let sent = coordinator.read_direct("a", "b", None)?; + assert_eq!(sent.len(), 1); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn identified_hive_management_acts_once() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator).with_management(Management { + authorizer: &Open, + creator: &Open, + }); + let create = identified( + &request, + "c1", + Kind::CreateHive, + json!({"hive_id": "side", "name": "Side"}), + )?; + belt.call(&create).await?; + let join = identified( + &request, + "j1", + Kind::JoinHive, + json!({"hive_id": "side", "agent_id": "b"}), + )?; + assert_eq!(belt.call(&join).await?, json!({"joined": true})); + let leave = identified( + &request, + "l1", + Kind::LeaveHive, + json!({"hive_id": "side", "agent_id": "b"}), + )?; + assert_eq!(belt.call(&leave).await?, json!({"left": true})); + // A retried join is answered from its record and joins nobody. + assert_eq!(belt.call(&join).await?, json!({"joined": true})); + let side: Vec = coordinator + .list_hives()? + .into_iter() + .filter(|hive| hive.hive_id == "side") + .collect(); + assert_eq!(side[0].members, Vec::::new()); + finish.notify_one(); + Ok(()) +} From 31dc4e3cced9851cb67325c07b25579ae4aadc20 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:34:56 +0000 Subject: [PATCH 18/66] test(tools): register identified test module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-host/src/tools/test/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/tinyhivemind-host/src/tools/test/mod.rs b/crates/tinyhivemind-host/src/tools/test/mod.rs index ff1d1c15..d6434a0f 100644 --- a/crates/tinyhivemind-host/src/tools/test/mod.rs +++ b/crates/tinyhivemind-host/src/tools/test/mod.rs @@ -1,6 +1,7 @@ //! The belt acts for its bound caller, under the host's policies. mod declarations; mod episodes; +mod identified; mod management; mod messaging; mod sends; From a8354edf6408c909921ff1bfe93a7d7cdef80340 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:35:30 +0000 Subject: [PATCH 19/66] feat(tools): route identified tool calls through coordinator turn calls Tool calls can now carry an optional turn and call identity, and management actions such as creating a hive, joining, or leaving are dispatched through the coordinator's in-turn variants when that identity is present. This lets the coordinator enforce that a turn is running and apply at-most-once semantics per call, while unidentified calls keep the existing behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-host/src/tools/call.rs | 26 +++++- crates/tinyhivemind-host/src/tools/mod.rs | 81 ++++++++++++++----- .../src/tools/test/identified.rs | 4 +- 3 files changed, 89 insertions(+), 22 deletions(-) diff --git a/crates/tinyhivemind-host/src/tools/call.rs b/crates/tinyhivemind-host/src/tools/call.rs index a45071bd..83800772 100644 --- a/crates/tinyhivemind-host/src/tools/call.rs +++ b/crates/tinyhivemind-host/src/tools/call.rs @@ -5,7 +5,7 @@ use crate::{ policy::{ManagementRequest, SendRequest}, }; use serde_json::Value; -use tinyhivemind_hives::HiveInfo; +use tinyhivemind_hives::{HiveInfo, TurnCall}; /// A hive tool call with validated arguments and a host-bound caller. /// @@ -16,6 +16,8 @@ pub struct ToolCall { session: Option, kind: Kind, args: Value, + /// The running turn and caller-chosen call this one says it is. + identity: Option<(String, String)>, } impl ToolCall { /// A call to `kind` by the seat the host bound it to. @@ -34,6 +36,28 @@ impl ToolCall { session, kind, args, + identity: None, + }) + } + /// The same call, identified as `call` of the actor's running turn + /// `turn_id`. + /// + /// A coordinator action of an identified call is refused unless that turn + /// is running, and acts at most once per `call`: a retry with the same + /// arguments returns the recorded result, and other reuse is refused. + #[must_use] + pub fn in_turn(mut self, turn_id: impl Into, call: impl Into) -> Self { + self.identity = Some((turn_id.into(), call.into())); + self + } + /// The coordinator's identity for this call, when it has one. + pub(super) fn turn_call(&self) -> Option { + self.identity.as_ref().map(|(turn_id, call)| TurnCall { + agent_id: self.actor.clone(), + turn_id: turn_id.clone(), + call: call.clone(), + tool: self.kind.name().into(), + arguments: self.args.clone(), }) } pub(super) fn actor(&self) -> &str { diff --git a/crates/tinyhivemind-host/src/tools/mod.rs b/crates/tinyhivemind-host/src/tools/mod.rs index d2647017..3802779b 100644 --- a/crates/tinyhivemind-host/src/tools/mod.rs +++ b/crates/tinyhivemind-host/src/tools/mod.rs @@ -11,7 +11,7 @@ use crate::{ }; pub use call::ToolCall; use serde_json::{Value, json}; -use tinyhivemind_hives::{Coordinator, Destination, EpisodeAction, SendMessage}; +use tinyhivemind_hives::{Coordinator, Destination, EpisodeAction, SendMessage, TurnCall}; pub use types::Kind; /// Executes hive tool calls against a coordinator under the host's policies. @@ -110,7 +110,9 @@ impl<'a> Belt<'a> { self.submit(call, EpisodeAction::Complete { body }).await } Kind::CreateHive | Kind::CreateAgent | Kind::JoinHive | Kind::LeaveHive => { - self.manage(actor, call.management()?).await + let turn = call.turn_call(); + self.manage_as(actor, call.management()?, turn.as_ref()) + .await } } } @@ -119,11 +121,25 @@ impl<'a> Belt<'a> { /// # Errors /// Disabled management, host denial, agent creation or coordinator errors. pub async fn manage(&self, actor: &str, request: ManagementRequest) -> Result { + self.manage_as(actor, request, None).await + } + /// [`Self::manage`], through the coordinator's identified calls when `turn` + /// is given. Creating an agent is the creator's, outside them. + async fn manage_as( + &self, + actor: &str, + request: ManagementRequest, + turn: Option<&TurnCall>, + ) -> Result { let management = self.management.ok_or(Error::ManagementDisabled)?; management.authorizer.authorize(actor, &request)?; + let coordinator = self.coordinator; match request { ManagementRequest::CreateHive(hive) => { - self.coordinator.create_hive(hive.clone()).await?; + match turn { + Some(turn) => coordinator.create_hive_in_turn(turn, hive.clone()).await?, + None => coordinator.create_hive(hive.clone()).await?, + } Ok(serde_json::to_value(hive)?) } ManagementRequest::CreateAgent { @@ -142,34 +158,59 @@ impl<'a> Belt<'a> { Ok(json!({"agent_id":agent_id})) } ManagementRequest::JoinHive { hive_id, agent_id } => { - self.coordinator.join_hive(&hive_id, &agent_id).await?; + match turn { + Some(turn) => { + coordinator + .join_hive_in_turn(turn, &hive_id, &agent_id) + .await?; + } + None => coordinator.join_hive(&hive_id, &agent_id).await?, + } Ok(json!({"joined":true})) } ManagementRequest::LeaveHive { hive_id, agent_id } => { - self.coordinator.leave_hive(&hive_id, &agent_id).await?; + match turn { + Some(turn) => { + coordinator + .leave_hive_in_turn(turn, &hive_id, &agent_id) + .await?; + } + None => coordinator.leave_hive(&hive_id, &agent_id).await?, + } Ok(json!({"left":true})) } } } async fn send(&self, call: &ToolCall, destination: Destination) -> Result { - let receipt = self - .coordinator - .send(SendMessage { - message_id: call.text("message_id"), - sender: call.actor().to_owned(), - destination, - body: call.text("body"), - thread: call.integer("thread"), - only_for: call.strings("only_for"), - starters: Vec::new(), - }) - .await?; + let message = SendMessage { + message_id: call.text("message_id"), + sender: call.actor().to_owned(), + destination, + body: call.text("body"), + thread: call.integer("thread"), + only_for: call.strings("only_for"), + starters: Vec::new(), + }; + let receipt = match call.turn_call() { + Some(turn) => self.coordinator.send_in_turn(&turn, message).await?, + None => self.coordinator.send(message).await?, + }; Ok(serde_json::to_value(receipt)?) } async fn submit(&self, call: &ToolCall, action: EpisodeAction) -> Result { - self.coordinator - .submit_action(call.actor(), &call.text("episode_id"), action) - .await?; + let episode = call.text("episode_id"); + match call.turn_call() { + Some(turn) => { + self.coordinator + .submit_action_in_turn(&turn, &episode, action) + .await?; + } + None => { + self.coordinator + .submit_action(call.actor(), &episode, action) + .await?; + } + } Ok(json!({"accepted":true})) } } diff --git a/crates/tinyhivemind-host/src/tools/test/identified.rs b/crates/tinyhivemind-host/src/tools/test/identified.rs index ed70da8f..6517f5b5 100644 --- a/crates/tinyhivemind-host/src/tools/test/identified.rs +++ b/crates/tinyhivemind-host/src/tools/test/identified.rs @@ -127,7 +127,9 @@ async fn an_identified_call_naming_another_turn_is_refused() -> Result<()> { let stale = ToolCall::new("a", None, Kind::Post, args)?.in_turn("0:0:a", "p1"); assert!(matches!( belt.call(&stale).await, - Err(Error::Coordinator(tinyhivemind_hives::Error::StaleTurn { .. })) + Err(Error::Coordinator( + tinyhivemind_hives::Error::StaleTurn { .. } + )) )); finish.notify_one(); Ok(()) From 33e3a7f6a1930699abdc169530a235abbed34c1d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:35:49 +0000 Subject: [PATCH 20/66] test(hook): cover tool matcher lookups on a runner Add a test asserting that a runner reports whether any hook matches a given tool name, covering wildcard and exact matchers as well as the case where only a stop hook is present. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/hook/test/matcher.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/tinyhivemind-exec/src/hook/test/matcher.rs b/crates/tinyhivemind-exec/src/hook/test/matcher.rs index 5f50c97b..e99ab5b3 100644 --- a/crates/tinyhivemind-exec/src/hook/test/matcher.rs +++ b/crates/tinyhivemind-exec/src/hook/test/matcher.rs @@ -26,3 +26,22 @@ fn a_star_matches_any_run_of_characters() { assert!(!matches(Some("a*b*c"), "a__c__b")); assert!(matches(Some("**"), "x")); } + +#[test] +fn a_runner_says_whether_a_tool_hook_names_a_tool() { + use super::support::{hook, runner}; + use serde_json::json; + let dir = std::env::temp_dir(); + let hooks = runner( + vec![ + hook("guard", "pre_tool_use", "allow", json!({"matcher": "git_*"})), + hook("audit", "post_tool_use", "record", json!({"matcher": "deploy"})), + hook("end", "stop", "record", json!({})), + ], + &dir, + ); + assert!(hooks.matches_tool("git_push")); + assert!(hooks.matches_tool("deploy")); + // A stop hook is bound to no tool. + assert!(!hooks.matches_tool("read_file")); +} From c665df3499b07a5ccfe85e5a9a623ec153f3f26f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:36:18 +0000 Subject: [PATCH 21/66] feat(hook): add matches_tool to check whether a tool has hooks Added a matches_tool method to HookRunner that reports whether any pre_tool_use or post_tool_use hook names the given tool, letting callers skip work when a tool call would run no hook. The matcher test was reformatted to fit the new hook construction. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-exec/src/hook/mod.rs | 10 ++++++++++ crates/tinyhivemind-exec/src/hook/test/matcher.rs | 14 ++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/tinyhivemind-exec/src/hook/mod.rs b/crates/tinyhivemind-exec/src/hook/mod.rs index ea522e79..b1efa7c7 100644 --- a/crates/tinyhivemind-exec/src/hook/mod.rs +++ b/crates/tinyhivemind-exec/src/hook/mod.rs @@ -68,6 +68,16 @@ impl HookRunner { self.hooks.is_empty() } + /// Whether a `pre_tool_use` or `post_tool_use` hook names `tool`, so that + /// a call of it would run a hook. + #[must_use] + pub fn matches_tool(&self, tool: &str) -> bool { + self.bound(HookEvent::PreToolUse, Some(tool)) + .chain(self.bound(HookEvent::PostToolUse, Some(tool))) + .next() + .is_some() + } + /// Ask the `pre_tool_use` hooks whether a call of `tool` with /// `arguments` may run. The first refusal wins and later hooks do not run. pub async fn pre_tool_use(&self, tool: &str, arguments: &Value) -> Verdict { diff --git a/crates/tinyhivemind-exec/src/hook/test/matcher.rs b/crates/tinyhivemind-exec/src/hook/test/matcher.rs index e99ab5b3..6756c8be 100644 --- a/crates/tinyhivemind-exec/src/hook/test/matcher.rs +++ b/crates/tinyhivemind-exec/src/hook/test/matcher.rs @@ -34,8 +34,18 @@ fn a_runner_says_whether_a_tool_hook_names_a_tool() { let dir = std::env::temp_dir(); let hooks = runner( vec![ - hook("guard", "pre_tool_use", "allow", json!({"matcher": "git_*"})), - hook("audit", "post_tool_use", "record", json!({"matcher": "deploy"})), + hook( + "guard", + "pre_tool_use", + "allow", + json!({"matcher": "git_*"}), + ), + hook( + "audit", + "post_tool_use", + "record", + json!({"matcher": "deploy"}), + ), hook("end", "stop", "record", json!({})), ], &dir, From 39f77b8587feac8372d54faaf8d9ba2499f944f2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:37:58 +0000 Subject: [PATCH 22/66] feat(mcp): add tinyhivemind-mcp crate to the workspace Register the new tinyhivemind-mcp member and declare the dependencies its Streamable HTTP server needs: hyper with server and HTTP/1 only, hyper-util for tokio I/O and graceful shutdown, http-body-util for bounded and fixed bodies, subtle for constant-time bearer comparison, and getrandom for per-seat tokens. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.toml | 19 +++++++++++- crates/tinyhivemind-mcp/Cargo.toml | 47 ++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 crates/tinyhivemind-mcp/Cargo.toml diff --git a/Cargo.toml b/Cargo.toml index 7ff9ffcf..23fa51cc 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-mcp"] # `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,23 @@ 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/1.1 server under `tinyhivemind-mcp`, which serves hive tools to +# harness processes over Streamable HTTP on loopback (ADR 0036). hyper 1 is a +# protocol implementation and no framework: no router, no TLS, no HTTP/2, no +# middleware stack, so the server's whole request surface (Host, Origin, +# bearer, body bound) is the crate's own code and nothing else is listening. +# It is already in this lockfile through the vendored harness, MIT licensed, +# and builds on 1.96. Server and HTTP/1 only; a test adds `client`. +hyper = { version = "1", default-features = false, features = ["server", "http1"] } +# hyper's tokio I/O adapter, its timer (for the header read timeout) and the +# graceful-shutdown watcher. Nothing else: no client, no auto-HTTP/2. +hyper-util = { version = "0.1", default-features = false, features = ["tokio", "server-graceful"] } +# Bounded request bodies (`Limited`) and fixed response bodies (`Full`). +http-body-util = "0.1" +# Constant-time comparison of a presented bearer with each seat's. +subtle = { version = "2", default-features = false, features = ["std"] } +# Random per-seat bearers, from the operating system. +getrandom = "0.3" # 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-mcp/Cargo.toml b/crates/tinyhivemind-mcp/Cargo.toml new file mode 100644 index 00000000..c14e8ed8 --- /dev/null +++ b/crates/tinyhivemind-mcp/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "tinyhivemind-mcp" +description = "Serves hive tools and a package's executable tools to harness processes over loopback MCP." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" +publish = false +# This crate opens a listening socket, on 127.0.0.1 only (ADR 0036), so it is +# outside the pure crates. It names no harness and links none; +# `.github/scripts/assert-pure.sh` asserts that no harness is in its graph. + +[dependencies] +# The tool belt, its policy ports, `ToolEndpoint` and the `Approver` port. +tinyhivemind-host.workspace = true +# The coordinator: running turns and identified calls. +tinyhivemind-hives.workspace = true +# Seat declarations: executable tools, hooks, permissions, autonomy. +tinyhivemind-lang.workspace = true +# Runs executable tools and hooks under the package calling convention. +tinyhivemind-exec.workspace = true +# The HTTP/1.1 server; see the workspace entry for why. +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true +# Bearer comparison and generation. +subtle.workspace = true +getrandom.workspace = true +# JSON-RPC messages and tool arguments. +serde_json.workspace = true +# Typed errors. +thiserror.workspace = true +# The listener, connection tasks, the shutdown signal and body deadlines. +tokio = { workspace = true, features = ["net", "rt", "sync", "time", "macros"] } + +[dev-dependencies] +# The loopback client the tests drive the server with. +hyper = { workspace = true, features = ["client"] } +# Async tests on a multi-threaded runtime. +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +# Seat workspaces the fixture tools write in. +tempfile.workspace = true + +[lints] +workspace = true From b1f750d3442c8f8da4faebbf4a63df4c3ca92461 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:38:36 +0000 Subject: [PATCH 23/66] test(mcp): add shared support module for integration tests Introduce a common support module that integration tests can share, so setup and helper code no longer has to be duplicated across test files. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-mcp/tests/support/mod.rs | 263 +++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 crates/tinyhivemind-mcp/tests/support/mod.rs diff --git a/crates/tinyhivemind-mcp/tests/support/mod.rs b/crates/tinyhivemind-mcp/tests/support/mod.rs new file mode 100644 index 00000000..42cd6c00 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/support/mod.rs @@ -0,0 +1,263 @@ +//! A loopback HTTP client, and a hive whose seat `a` has a turn held open. +#![allow(dead_code, unreachable_pub, clippy::expect_used, clippy::unwrap_used)] +use http_body_util::{BodyExt, Full}; +use hyper::body::Bytes; +use hyper::{HeaderMap, Request, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use tinyhivemind_exec::ExecContext; +use tinyhivemind_hives::{ + AgentRegistration, AgentRunner, Coordinator, CoordinatorOptions, Destination, HiveInfo, + MemoryStorage, SendMessage, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, +}; +use tinyhivemind_host::harness::ToolEndpoint; +use tinyhivemind_mcp::{HiveToolServer, SeatTools, ServerOptions, Services}; +use tokio::sync::{Notify, mpsc}; + +/// What the server answered. +#[derive(Debug)] +pub struct Reply { + pub status: StatusCode, + pub headers: HeaderMap, + pub body: Option, +} + +/// Send `request` to `addr` on a fresh connection. +pub async fn send(addr: SocketAddr, request: Request>) -> Reply { + let stream = tokio::net::TcpStream::connect(addr).await.expect("connect"); + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) + .await + .expect("handshake"); + tokio::spawn(connection); + let response = sender.send_request(request).await.expect("response"); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = response.into_body().collect().await.expect("body").to_bytes(); + let body = (!bytes.is_empty()).then(|| serde_json::from_slice(&bytes).expect("json body")); + Reply { + status, + headers, + body, + } +} + +/// A well-formed MCP POST of `body` to `addr`, with `bearer` if given. +pub fn post(addr: SocketAddr, bearer: Option<&str>, body: &[u8]) -> hyper::http::request::Builder { + let mut builder = Request::post("/mcp") + .header("host", format!("127.0.0.1:{}", addr.port())) + .header("content-type", "application/json") + .header("accept", "application/json, text/event-stream"); + if let Some(bearer) = bearer { + builder = builder.header("authorization", format!("Bearer {bearer}")); + } + let _ = body; + builder +} + +/// One seat's view of the server. +#[derive(Clone, Debug)] +pub struct Client { + pub addr: SocketAddr, + pub bearer: String, +} +impl Client { + pub fn of(server: &HiveToolServer, endpoint: &ToolEndpoint) -> Self { + Self { + addr: server.local_addr(), + bearer: endpoint.bearer().to_owned(), + } + } + /// POST one JSON-RPC message and return what came back. + pub async fn message(&self, message: &Value) -> Reply { + let body = serde_json::to_vec(message).unwrap(); + let request = post(self.addr, Some(&self.bearer), &body) + .body(Full::new(Bytes::from(body))) + .unwrap(); + send(self.addr, request).await + } + /// Call `method` and return the whole JSON-RPC response. + pub async fn rpc(&self, method: &str, params: Value) -> Value { + let reply = self + .message(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})) + .await; + assert_eq!(reply.status, StatusCode::OK, "{reply:?}"); + reply.body.expect("a response") + } + /// Call tool `name` with `arguments`: its text, and whether it is an error. + pub async fn call(&self, name: &str, arguments: Value) -> (String, bool) { + let response = self + .rpc("tools/call", json!({"name": name, "arguments": arguments})) + .await; + let result = &response["result"]; + assert!(result.is_object(), "{response}"); + ( + result["content"][0]["text"].as_str().unwrap().to_owned(), + result["isError"].as_bool().unwrap(), + ) + } + /// The served tools, by name, with their input schemas. + pub async fn tools(&self) -> Vec<(String, Value)> { + let response = self.rpc("tools/list", json!({})).await; + response["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| { + ( + tool["name"].as_str().unwrap().to_owned(), + tool["inputSchema"].clone(), + ) + }) + .collect() + } +} + +/// Hands its first turn to the test and holds it until told to finish. +struct Holds { + started: mpsc::UnboundedSender, + finish: Arc, +} +impl AgentRunner for Holds { + fn run(&self, request: TurnRequest) -> TurnFuture { + let (started, finish) = (self.started.clone(), self.finish.clone()); + Box::pin(async move { + if started.send(request.clone()).is_ok() { + finish.notified().await; + } + Ok(TurnOutcome { + session_id: format!("session:{}", request.agent_id), + reply: None, + disposition: TurnDisposition::Completed, + }) + }) + } +} + +/// A coordinator with seats `a` and `b` in hive `work`, `a`'s turn held +/// open on an episode, and a server serving both seats. +pub struct Hive { + pub coordinator: Coordinator, + pub server: HiveToolServer, + pub turn: TurnRequest, + pub finish: Arc, + pub a: Client, + pub b: Client, + pub endpoint: ToolEndpoint, + pub workspace: tempfile::TempDir, + requests: mpsc::UnboundedReceiver, +} +impl Hive { + /// Start with `services` adjusted by `configure` and seat `a` by `seat`. + pub async fn start( + configure: impl FnOnce(Services) -> Services, + seat: impl FnOnce(SeatTools, ExecContext) -> SeatTools, + ) -> Self { + Self::start_with(configure, seat, ServerOptions::default()).await + } + pub async fn start_with( + configure: impl FnOnce(Services) -> Services, + seat: impl FnOnce(SeatTools, ExecContext) -> SeatTools, + options: ServerOptions, + ) -> Self { + let coordinator = Coordinator::new( + "runtime".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let (started, mut requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + for id in ["a", "b"] { + coordinator + .register_agent(AgentRegistration { + agent_id: id.into(), + runtime_id: "runtime".into(), + runner: Arc::new(Holds { + started: started.clone(), + finish: finish.clone(), + }), + }) + .await + .unwrap(); + } + coordinator + .create_hive(HiveInfo { + hive_id: "work".into(), + name: "Work".into(), + description: None, + members: vec!["a".into(), "b".into()], + }) + .await + .unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let context = ExecContext { + package_root: fixtures(), + workspace: Some(workspace.path().to_path_buf()), + hive: "work".into(), + seat: "a".into(), + ..ExecContext::default() + }; + let server = HiveToolServer::start(configure(Services::new(coordinator.clone())), options) + .await + .unwrap(); + let endpoint = server.serve_seat(seat(SeatTools::new("a"), context)).unwrap(); + let other = server.serve_seat(SeatTools::new("b")).unwrap(); + coordinator + .send_as_host(SendMessage { + message_id: "task".into(), + sender: String::new(), + destination: Destination::Hive("work".into()), + body: "decide".into(), + thread: None, + only_for: Vec::new(), + starters: vec!["a".into()], + }) + .await + .unwrap(); + tokio::spawn({ + let coordinator = coordinator.clone(); + async move { coordinator.run_until_idle().await } + }); + let turn = requests.recv().await.unwrap(); + Self { + a: Client::of(&server, &endpoint), + b: Client::of(&server, &other), + coordinator, + server, + turn, + finish, + endpoint, + workspace, + requests, + } + } + /// The episode `a`'s turn works on. + pub fn episode(&self) -> String { + self.turn.episode.as_ref().unwrap().episode_id.clone() + } + /// `a`'s running turn id. + pub fn turn_id(&self) -> String { + self.turn.turn_id.clone() + } + /// Posts `a` has staged in its running turn, by body. + pub fn posts(&self) -> usize { + let rows = self.coordinator.read_hive("a", "work", None, None).unwrap(); + rows.len() + } + /// Lines `file` holds in the seat's workspace. + pub fn lines(&self, file: &str) -> usize { + std::fs::read_to_string(self.workspace.path().join(file)) + .unwrap_or_default() + .lines() + .count() + } +} + +/// The fixture package root. +pub fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} From 56ce235f3f2baa0e0191c22808a090ba88a72254 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:39:02 +0000 Subject: [PATCH 24/66] test(mcp): add http transport integration tests Add integration tests covering the MCP HTTP transport, exercising request handling and response behaviour end to end. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-mcp/tests/http.rs | 242 ++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 crates/tinyhivemind-mcp/tests/http.rs diff --git a/crates/tinyhivemind-mcp/tests/http.rs b/crates/tinyhivemind-mcp/tests/http.rs new file mode 100644 index 00000000..75bfdcc9 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/http.rs @@ -0,0 +1,242 @@ +//! Who may reach the server, how a request is bounded, and MCP framing. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use http_body_util::Full; +use hyper::body::Bytes; +use hyper::{Request, StatusCode}; +use serde_json::json; +use support::{Hive, post, send}; +use tinyhivemind_mcp::{PROTOCOL_VERSIONS, ServerOptions}; + +fn body(value: &serde_json::Value) -> Vec { + serde_json::to_vec(value).unwrap() +} +const LIST: &str = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#; + +async fn hive() -> Hive { + Hive::start(|services| services, |seat, _| seat).await +} + +#[tokio::test] +async fn a_wrong_or_missing_bearer_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + for bearer in [Some("not-a-seat"), None] { + let request = post(addr, bearer, LIST.as_bytes()) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::UNAUTHORIZED); + assert_eq!(reply.headers["www-authenticate"], "Bearer"); + } +} + +#[tokio::test] +async fn a_bad_host_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + for host in ["evil.example", "127.0.0.1:1", "localhost"] { + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("host", host) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::FORBIDDEN, "{host}"); + } + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("host", format!("localhost:{}", addr.port())) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::OK); +} + +#[tokio::test] +async fn any_origin_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let own = format!("http://127.0.0.1:{}", addr.port()); + for origin in ["https://evil.example", "null", own.as_str()] { + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("origin", origin) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::FORBIDDEN); + } +} + +#[tokio::test] +async fn an_oversized_body_is_refused() { + let options = ServerOptions { + max_body_bytes: 64, + ..ServerOptions::default() + }; + let hive = Hive::start_with(|services| services, |seat, _| seat, options).await; + let addr = hive.server.local_addr(); + let big = body(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping", "params": {"pad": "x".repeat(100)}})); + let request = post(addr, Some(&hive.a.bearer), &big) + .body(Full::new(Bytes::from(big.clone()))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::PAYLOAD_TOO_LARGE); +} + +#[tokio::test] +async fn only_post_to_the_mcp_path_is_served_and_nothing_redirects() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let host = format!("127.0.0.1:{}", addr.port()); + let auth = format!("Bearer {}", hive.a.bearer); + for method in ["GET", "DELETE", "PUT"] { + let request = Request::builder() + .method(method) + .uri("/mcp") + .header("host", &host) + .header("authorization", &auth) + .body(Full::new(Bytes::new())) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::METHOD_NOT_ALLOWED); + assert_eq!(reply.headers["allow"], "POST"); + } + for path in ["/", "/mcp/", "/other"] { + let request = Request::post(path) + .header("host", &host) + .header("authorization", &auth) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::NOT_FOUND); + assert!(reply.headers.get("location").is_none()); + } +} + +#[tokio::test] +async fn initialize_negotiates_every_version_the_harnesses_sent() { + let hive = hive().await; + // Codex 0.171 sent 2025-06-18; OpenHuman 0.64.15 and OpenClaw 2025-11-25. + for version in ["2025-06-18", "2025-11-25", "2025-03-26"] { + let response = hive + .a + .rpc( + "initialize", + json!({"protocolVersion": version, "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}), + ) + .await; + assert_eq!(response["result"]["protocolVersion"], version); + assert_eq!(response["result"]["capabilities"], json!({"tools": {"listChanged": false}})); + assert_eq!(response["result"]["serverInfo"]["name"], "hivemind"); + } + let response = hive + .a + .rpc("initialize", json!({"protocolVersion": "1999-01-01"})) + .await; + assert_eq!(response["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]); +} + +#[tokio::test] +async fn an_unsupported_protocol_version_header_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("mcp-protocol-version", "1999-01-01") + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::BAD_REQUEST); + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("mcp-protocol-version", "2025-06-18") + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::OK); +} + +#[tokio::test] +async fn notifications_and_responses_are_accepted_without_a_body() { + let hive = hive().await; + for message in [ + json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), + json!({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 1}}), + json!({"jsonrpc": "2.0", "id": 7, "result": {}}), + ] { + let reply = hive.a.message(&message).await; + assert_eq!(reply.status, StatusCode::ACCEPTED); + assert!(reply.body.is_none()); + } +} + +#[tokio::test] +async fn malformed_messages_get_json_rpc_errors() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let request = post(addr, Some(&hive.a.bearer), b"{nope") + .body(Full::new(Bytes::from_static(b"{nope"))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(reply.body.unwrap()["error"]["code"], -32700); + for message in [json!([{"jsonrpc": "2.0", "id": 1, "method": "ping"}]), json!({"id": 1})] { + let reply = hive.a.message(&message).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(reply.body.unwrap()["error"]["code"], -32600); + } + let response = hive.a.rpc("sampling/createMessage", json!({})).await; + assert_eq!(response["error"]["code"], -32601); +} + +#[tokio::test] +async fn the_surface_is_tools_only() { + let hive = hive().await; + assert_eq!(hive.a.rpc("ping", json!({})).await["result"], json!({})); + assert_eq!( + hive.a.rpc("resources/list", json!({})).await["result"], + json!({"resources": []}) + ); + assert_eq!( + hive.a.rpc("resources/templates/list", json!({})).await["result"], + json!({"resourceTemplates": []}) + ); + assert_eq!( + hive.a.rpc("prompts/list", json!({})).await["result"], + json!({"prompts": []}) + ); +} + +#[tokio::test] +async fn debug_output_never_carries_a_bearer() { + let hive = hive().await; + for printed in [format!("{:?}", hive.server), format!("{:?}", hive.endpoint)] { + assert!(!printed.contains(&hive.a.bearer), "{printed}"); + assert!(!printed.contains(&hive.b.bearer), "{printed}"); + } + assert!(hive.endpoint.url.starts_with("http://127.0.0.1:")); + assert!(hive.endpoint.url.ends_with("/mcp")); + assert_ne!(hive.a.bearer, hive.b.bearer); + assert_eq!(hive.a.bearer.len(), 64); +} + +#[tokio::test] +async fn connections_beyond_the_bound_wait_for_a_free_one() { + let options = ServerOptions { + max_connections: 1, + ..ServerOptions::default() + }; + let hive = Hive::start_with(|services| services, |seat, _| seat, options).await; + let addr = hive.server.local_addr(); + // An idle open connection holds the only slot. + let idle = tokio::net::TcpStream::connect(addr).await.unwrap(); + let waiting = tokio::spawn({ + let a = hive.a.clone(); + async move { a.rpc("ping", json!({})).await } + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert!(!waiting.is_finished()); + drop(idle); + assert_eq!(waiting.await.unwrap()["result"], json!({})); +} + +#[tokio::test] +async fn shutdown_closes_the_listener() { + let hive = hive().await; + let addr = hive.server.local_addr(); + assert_eq!(hive.a.rpc("ping", json!({})).await["result"], json!({})); + hive.server.shutdown().await.unwrap(); + assert!(tokio::net::TcpStream::connect(addr).await.is_err()); +} From 997a70bd092d8d0e9a4db65894c3fd9abb00b4a9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:39:51 +0000 Subject: [PATCH 25/66] test(mcp): add settle and written helpers to the hive test support The test harness now keeps the coordinator drain task so a new settle helper can wait for the turn to end and the coordinator to go idle, and a written helper counts transcript messages by sender and body. The old posts helper was replaced since it only counted staged rows in one hive rather than the full transcript. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyhivemind-mcp/tests/fixtures/README.md | 13 +++++++++++ .../tests/fixtures/tools/audit.sh | 4 ++++ .../tests/fixtures/tools/guard.sh | 8 +++++++ .../tests/fixtures/tools/look.sh | 5 ++++ .../tests/fixtures/tools/slow.sh | 6 +++++ .../tests/fixtures/tools/stamp.sh | 5 ++++ crates/tinyhivemind-mcp/tests/support/mod.rs | 23 ++++++++++++++----- 7 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 crates/tinyhivemind-mcp/tests/fixtures/README.md create mode 100755 crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh create mode 100755 crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh create mode 100755 crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh create mode 100755 crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh create mode 100755 crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh diff --git a/crates/tinyhivemind-mcp/tests/fixtures/README.md b/crates/tinyhivemind-mcp/tests/fixtures/README.md new file mode 100644 index 00000000..1d7de0dd --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/README.md @@ -0,0 +1,13 @@ +# Fixtures + +A package root for the integration tests. Every script runs in the seat's +temporary workspace, so the logs it writes are the test's evidence of how many +times it ran. + +| File | Does | +| --- | --- | +| `tools/stamp.sh` | Write tool; appends its arguments to `stamp.log`. | +| `tools/slow.sh` | Write tool; logs a start to `slow.log`, then waits for a `release` file. | +| `tools/look.sh` | Read tool; logs each run to `look.log`. | +| `tools/guard.sh` | `pre_tool_use` hook; logs to `guard.log` and refuses an event naming `forbidden`. | +| `tools/audit.sh` | `post_tool_use` hook; logs to `audit.log`. | diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh new file mode 100755 index 00000000..cf258fcf --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# A post_tool_use hook: logs each event. +input=$(cat) +printf '%s\n' "$input" >> audit.log diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh new file mode 100755 index 00000000..8c023d41 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# A pre_tool_use hook: logs each event and refuses one naming "forbidden". +input=$(cat) +printf '%s\n' "$input" >> guard.log +case "$input" in + *forbidden*) printf '{"permission": "deny", "message": "forbidden by guard"}\n' ;; + *) echo '{}' ;; +esac diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh new file mode 100755 index 00000000..dca37896 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# A read tool: counts its runs in look.log. +cat > /dev/null +echo look >> look.log +echo seen diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh new file mode 100755 index 00000000..ee53a944 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# A write tool that starts, then waits until the test creates `release`. +cat > /dev/null +echo started >> slow.log +while [ ! -e release ]; do sleep 0.02; done +echo released diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh new file mode 100755 index 00000000..f7f78bd4 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# A write tool: appends its argument object to stamp.log in the workspace. +input=$(cat) +printf '%s\n' "$input" >> stamp.log +printf 'stamped %s\n' "$THM_CALL_ID" diff --git a/crates/tinyhivemind-mcp/tests/support/mod.rs b/crates/tinyhivemind-mcp/tests/support/mod.rs index 42cd6c00..d7cdc648 100644 --- a/crates/tinyhivemind-mcp/tests/support/mod.rs +++ b/crates/tinyhivemind-mcp/tests/support/mod.rs @@ -148,6 +148,7 @@ pub struct Hive { pub endpoint: ToolEndpoint, pub workspace: tempfile::TempDir, requests: mpsc::UnboundedReceiver, + drain: Option>>, } impl Hive { /// Start with `services` adjusted by `configure` and seat `a` by `seat`. @@ -218,7 +219,7 @@ impl Hive { }) .await .unwrap(); - tokio::spawn({ + let drain = tokio::spawn({ let coordinator = coordinator.clone(); async move { coordinator.run_until_idle().await } }); @@ -233,8 +234,23 @@ impl Hive { endpoint, workspace, requests, + drain: Some(drain), } } + /// Let `a`'s turn end and the coordinator go idle. + pub async fn settle(&mut self) { + self.finish.notify_one(); + if let Some(drain) = self.drain.take() { + drain.await.unwrap().unwrap(); + } + } + /// Messages `sender` wrote with exactly `body`, in the whole transcript. + pub fn written(&self, sender: &str, body: &str) -> usize { + let rows = self.coordinator.read_transcript(None).unwrap(); + rows.iter() + .filter(|row| row.sender == sender && row.body == body) + .count() + } /// The episode `a`'s turn works on. pub fn episode(&self) -> String { self.turn.episode.as_ref().unwrap().episode_id.clone() @@ -243,11 +259,6 @@ impl Hive { pub fn turn_id(&self) -> String { self.turn.turn_id.clone() } - /// Posts `a` has staged in its running turn, by body. - pub fn posts(&self) -> usize { - let rows = self.coordinator.read_hive("a", "work", None, None).unwrap(); - rows.len() - } /// Lines `file` holds in the seat's workspace. pub fn lines(&self, file: &str) -> usize { std::fs::read_to_string(self.workspace.path().join(file)) From 3175248e521df52b8925ee47c8abb038695cdf6a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 25 Nov 2026 23:40:27 +0000 Subject: [PATCH 26/66] test(mcp): add tool and hook fixture builders Add helpers to the MCP test support module that construct executable tool and hook fixtures from concise arguments, so call tests can declare them without repeating the full JSON shape. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinyhivemind-mcp/tests/calls.rs | 232 +++++++++++++++++++ crates/tinyhivemind-mcp/tests/support/mod.rs | 24 ++ 2 files changed, 256 insertions(+) create mode 100644 crates/tinyhivemind-mcp/tests/calls.rs diff --git a/crates/tinyhivemind-mcp/tests/calls.rs b/crates/tinyhivemind-mcp/tests/calls.rs new file mode 100644 index 00000000..81646bba --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/calls.rs @@ -0,0 +1,232 @@ +//! Hive tools: the turn check, call identity, and policy before dispatch. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::{Value, json}; +use std::sync::Arc; +use support::{Hive, hook}; +use tinyhivemind_host::Result as HostResult; +use tinyhivemind_host::policy::{AgentCreator, CreateFuture, ManagementAuthorizer, ManagementRequest, NewAgent}; +use tinyhivemind_hives::HiveInfo; + +fn post(hive: &Hive, call: &str, body: &str) -> Value { + json!({"episode_id": hive.episode(), "body": body, "turn": hive.turn_id(), "call": call}) +} + +async fn plain() -> Hive { + Hive::start(|services| services, |seat, _| seat).await +} + +#[tokio::test] +async fn tools_list_adds_turn_and_call_to_state_changing_tools_only() { + let hive = plain().await; + let tools = hive.a.tools().await; + let names: Vec<&str> = tools.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!( + names, + [ + "hivemind_list_hives", "hivemind_list_agents", "hivemind_read", + "hivemind_send_hive", "hivemind_send_agent", "hivemind_post", + "hivemind_ask", "hivemind_broadcast", "hivemind_complete", + ] + ); + for (name, schema) in &tools { + let changes = !matches!(name.as_str(), "hivemind_list_hives" | "hivemind_list_agents" | "hivemind_read"); + for field in ["turn", "call"] { + assert_eq!(schema["properties"].get(field).is_some(), changes, "{name} {field}"); + let required = schema["required"].as_array().unwrap(); + assert_eq!(required.contains(&json!(field)), changes, "{name} {field}"); + } + } + let names: Vec = hive.endpoint.tools.iter().cloned().collect(); + assert_eq!(names.len(), 9); +} + +#[tokio::test] +async fn a_retried_post_acts_once_and_returns_the_first_result() { + let mut hive = plain().await; + let first = hive.a.call("hivemind_post", post(&hive, "p1", "once")).await; + assert_eq!(first, (r#"{"accepted":true}"#.into(), false)); + assert_eq!(hive.a.call("hivemind_post", post(&hive, "p1", "once")).await, first); + hive.settle().await; + assert_eq!(hive.written("a", "once"), 1); +} + +#[tokio::test] +async fn two_identical_posts_under_different_calls_both_act() { + let mut hive = plain().await; + for call in ["p1", "p2"] { + let (_, failed) = hive.a.call("hivemind_post", post(&hive, call, "twice")).await; + assert!(!failed); + } + hive.settle().await; + assert_eq!(hive.written("a", "twice"), 2); +} + +#[tokio::test] +async fn reusing_a_call_with_other_arguments_or_another_tool_is_refused() { + let mut hive = plain().await; + hive.a.call("hivemind_post", post(&hive, "p1", "first")).await; + let (text, failed) = hive.a.call("hivemind_post", post(&hive, "p1", "second")).await; + assert!(failed && text.contains("already made"), "{text}"); + let (text, failed) = hive.a.call("hivemind_complete", post(&hive, "p1", "first")).await; + assert!(failed && text.contains("already made"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "second"), 0); +} + +#[tokio::test] +async fn a_missing_call_or_turn_is_refused() { + let mut hive = plain().await; + let mut missing_call = post(&hive, "p1", "none"); + missing_call.as_object_mut().unwrap().remove("call"); + let (text, failed) = hive.a.call("hivemind_post", missing_call).await; + assert!(failed && text.contains("call"), "{text}"); + let mut missing_turn = post(&hive, "p1", "none"); + missing_turn.as_object_mut().unwrap().remove("turn"); + let (text, failed) = hive.a.call("hivemind_post", missing_turn).await; + assert!(failed && text.contains("turn"), "{text}"); + let (_, failed) = hive.a.call("hivemind_post", post(&hive, "", "none")).await; + assert!(failed); + hive.settle().await; + assert_eq!(hive.written("a", "none"), 0); +} + +#[tokio::test] +async fn a_stale_turn_is_refused() { + let mut hive = plain().await; + let mut stale = post(&hive, "p1", "late"); + stale["turn"] = json!("0:1:a"); + let (text, failed) = hive.a.call("hivemind_post", stale).await; + assert!(failed && text.contains("not the running turn"), "{text}"); + hive.settle().await; + // After the turn ends, its own id is stale too. + let (_, failed) = hive.a.call("hivemind_post", post(&hive, "p2", "late")).await; + assert!(failed); + assert_eq!(hive.written("a", "late"), 0); +} + +#[tokio::test] +async fn another_seats_bearer_cannot_act_in_a_turn_and_has_none_of_its_own() { + let mut hive = plain().await; + // `b` presents `a`'s turn and episode: the bearer says `b`, which is not running. + let (text, failed) = hive.b.call("hivemind_post", post(&hive, "p1", "as b")).await; + assert!(failed && text.contains("not the running turn of b"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "as b") + hive.written("b", "as b"), 0); +} + +#[tokio::test] +async fn another_seats_episode_is_refused() { + let mut hive = plain().await; + let mut other = post(&hive, "p1", "elsewhere"); + other["episode_id"] = json!("episode:999"); + let (text, failed) = hive.a.call("hivemind_post", other).await; + assert!(failed && text.contains("stale episode"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "elsewhere"), 0); +} + +#[tokio::test] +async fn a_forged_actor_is_refused() { + let mut hive = plain().await; + let mut forged = post(&hive, "p1", "forged"); + forged["sender"] = json!("b"); + let (text, failed) = hive.a.call("hivemind_post", forged).await; + assert!(failed && text.contains("unknown argument sender"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "forged") + hive.written("b", "forged"), 0); +} + +#[tokio::test] +async fn an_unknown_tool_is_a_protocol_error() { + let hive = plain().await; + let response = hive + .a + .rpc("tools/call", json!({"name": "hivemind_create_hive", "arguments": {}})) + .await; + assert_eq!(response["error"]["code"], -32602); +} + +#[tokio::test] +async fn a_read_needs_no_identity() { + let hive = plain().await; + let (text, failed) = hive.a.call("hivemind_list_hives", json!({})).await; + assert!(!failed, "{text}"); + assert!(text.contains("work")); +} + +#[tokio::test] +async fn a_retried_send_acts_once_and_one_message_id_is_one_message() { + let hive = plain().await; + let send = |call: &str| json!({"agent_id": "b", "message_id": "m1", "body": "hello b", "turn": hive.turn_id(), "call": call}); + let first = hive.a.call("hivemind_send_agent", send("s1")).await; + assert!(!first.1, "{first:?}"); + assert_eq!(hive.a.call("hivemind_send_agent", send("s1")).await, first); + assert_eq!(hive.a.call("hivemind_send_agent", send("s2")).await, first); + assert_eq!(hive.coordinator.read_direct("a", "b", None).unwrap().len(), 1); +} + +/// Admits every management request; builds no agents. +struct Open; +impl ManagementAuthorizer for Open { + fn authorize(&self, _: &str, _: &ManagementRequest) -> HostResult<()> { + Ok(()) + } +} +impl AgentCreator for Open { + fn create(&self, _: NewAgent) -> CreateFuture<'_> { + Box::pin(async { Err(tinyhivemind_host::Error::Host("no templates".into())) }) + } +} + +#[tokio::test] +async fn a_retried_join_acts_once_and_returns_the_first_result() { + let hive = Hive::start(|services| services.with_management(Arc::new(Open), Arc::new(Open)), |seat, _| seat).await; + assert_eq!(hive.a.tools().await.len(), 13); + hive.coordinator + .create_hive(HiveInfo { hive_id: "side".into(), name: "Side".into(), description: None, members: Vec::new() }) + .await + .unwrap(); + let join = json!({"hive_id": "side", "agent_id": "a", "turn": hive.turn_id(), "call": "j1"}); + let first = hive.a.call("hivemind_join_hive", join.clone()).await; + assert_eq!(first, (r#"{"joined":true}"#.into(), false)); + hive.coordinator.leave_hive("side", "a").await.unwrap(); + assert_eq!(hive.a.call("hivemind_join_hive", join).await, first); + let side = hive.coordinator.list_hives().unwrap().into_iter().find(|h| h.hive_id == "side").unwrap(); + assert_eq!(side.members, Vec::::new()); +} + +#[tokio::test] +async fn a_failed_agent_creation_is_recorded_and_not_retried() { + let hive = Hive::start(|services| services.with_management(Arc::new(Open), Arc::new(Open)), |seat, _| seat).await; + let create = json!({"template": "t", "config": {}, "turn": hive.turn_id(), "call": "c1"}); + let first = hive.a.call("hivemind_create_agent", create.clone()).await; + assert!(first.1 && first.0.contains("no templates"), "{first:?}"); + assert_eq!(hive.a.call("hivemind_create_agent", create).await, first); +} + +#[tokio::test] +async fn a_hook_denied_call_is_recorded_and_a_corrected_call_uses_a_new_call() { + let mut hive = Hive::start( + |services| services, + |seat, context| { + seat.with_context(context) + .with_hooks(vec![hook("guard", "pre_tool_use", "hivemind_post", "guard")]) + }, + ) + .await; + let denied = hive.a.call("hivemind_post", post(&hive, "p1", "forbidden")).await; + assert_eq!(denied, ("forbidden by guard".into(), true)); + assert_eq!(hive.lines("guard.log"), 1); + // The retry is answered from the record: no hook runs again. + assert_eq!(hive.a.call("hivemind_post", post(&hive, "p1", "forbidden")).await, denied); + assert_eq!(hive.lines("guard.log"), 1); + let corrected = hive.a.call("hivemind_post", post(&hive, "p2", "allowed")).await; + assert!(!corrected.1, "{corrected:?}"); + assert_eq!(hive.a.call("hivemind_post", post(&hive, "p2", "allowed")).await, corrected); + assert_eq!(hive.lines("guard.log"), 2); + hive.settle().await; + assert_eq!(hive.written("a", "forbidden"), 0); + assert_eq!(hive.written("a", "allowed"), 1); +} diff --git a/crates/tinyhivemind-mcp/tests/support/mod.rs b/crates/tinyhivemind-mcp/tests/support/mod.rs index d7cdc648..90f3722a 100644 --- a/crates/tinyhivemind-mcp/tests/support/mod.rs +++ b/crates/tinyhivemind-mcp/tests/support/mod.rs @@ -272,3 +272,27 @@ impl Hive { pub fn fixtures() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") } + +/// An executable tool `id` running `tools/