Skip to content

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

test(subagent): cover the spawn-tool refusal invariant

Shanu6f8b6d6f78e0
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 0707f941cd..7e1ae09a44 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -279,6 +279,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 6.3.13 | continue_subagent durable resume (no pause checkpoint) | RU | `src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs::{continue_subagent_resumes_idle_durable_session_e2e,continue_subagent_without_checkpoint_or_durable_session_names_the_roster}` | ✅ | With no `ask_user_clarification` checkpoint, `continue_subagent` resolves the durable session by subagent_session_id / task id, resumes it via the reusable async path seeded with persisted history, and keeps the same durable id; missing sessions error with a pointer at the roster. |
| 6.3.14 | Workflow proposal durability (async builder → chat card) | RU+VU | `src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs::{extract_workflow_proposal_finds_last_proposal_tool_result,attach_workflow_proposal_persists_thread_message_and_extends_summary,attach_workflow_proposal_without_proposal_returns_summary_unchanged}`, `app/src/lib/workflows/workflowProposal.test.ts` | ✅ | A `workflow_proposal` payload in a finished async child's history is persisted as a parent-thread message (metadata scope `workflow_proposal`) and embedded in the delivery notice; the frontend rehydrates the newest unconsumed proposal into the card on thread load, and Save/Dismiss mark the source message consumed. |
| 6.3.15 | Autonomous reply persisted once (core-owned id, idempotent append) | RU+VU | `src/openhuman/agent/task_session_tests.rs::{append_final_writes_agent_outcome_keyed_by_run_id,append_final_records_failure_as_unsuccessful_agent_message,append_final_is_idempotent_per_run}`, `src/openhuman/memory/conversations/store/store_tests.rs::append_message_is_idempotent_by_message_id`, `src/openhuman/web_chat/presentation_tests.rs::single_bubble_delivery_emits_one_unsegmented_chat_done_without_reaction`, `app/src/providers/__tests__/ChatRuntimeProvider.test.tsx` (system `chat_done`/`chat_error` reuse the core id), `app/src/services/api/threadApi.test.ts` (legacy `assistant` sender folded onto `agent`), `app/src/store/__tests__/threadSlice.test.ts` (same-id cache upsert) | ✅ | #5933 — a background-delivery / autonomous-task reply is persisted by the core FIRST as `agent:<run_id>` (`sender: agent`, `extraMetadata.requestId`), announced as one unsegmented `chat_done`, and the frontend's own `chat_done` append reuses that id so the id-idempotent store keeps one row; failure outcomes land as `Run failed: …` under the same id. Previously the reply was persisted twice, the second copy as `assistant`, which rendered as a user-side raw-markdown bubble. |
+| 6.3.16 | Sub-agent spawn/delegate tool refusal (#4452 invariant) | RU | `src/openhuman/agent/harness/subagent_runner/ops/graph_tests.rs::{a_sub_agent_cannot_reach_a_spawn_tool_and_the_healthy_run_is_quiet,an_allowlist_that_readmits_a_spawn_tool_is_refused_loudly}`, `src/openhuman/agent/harness/subagent_runner/tool_prep_tests.rs::{dynamic_tools_keep_ordinary_actions_and_lose_spawn_tools,dynamic_tools_lose_unprefixed_delegate_name_overrides,a_dynamic_tool_list_without_spawn_tools_is_untouched}` | ✅ | #6157 — a sub-agent can never invoke `spawn_subagent`/`delegate_*`/`agent_prepare_context`/`spawn_worker_thread`: the runner strips them from `allowed_indices` and from the dynamic per-spawn tools, and registration re-refuses any the allowlist readmits. The registration warn fires only on that readmission case, so a healthy sub-agent run is silent instead of emitting one WRN per spawn tool. |
### 6.4 Managed Cloud File Storage
diff --git a/src/openhuman/agent/harness/subagent_runner/ops/graph_tests.rs b/src/openhuman/agent/harness/subagent_runner/ops/graph_tests.rs
index 0350d632f3..53eb46ca1f 100644
--- a/src/openhuman/agent/harness/subagent_runner/ops/graph_tests.rs
+++ b/src/openhuman/agent/harness/subagent_runner/ops/graph_tests.rs
@@ -443,3 +443,187 @@ async fn cap_hit_summarizes_a_resumable_checkpoint() {
"cap hit should return the summary checkpoint, got {output:?}"
);
}
+
+// ── Spawn-tool refusal on a sub-agent run (#6157, #4452) ────────────────
+
+/// Collects the messages of `WARN` events whose text contains a marker, so a
+/// test can assert on a log line that has no other observable side effect.
+#[derive(Clone, Default)]
+struct WarnSink(Arc<std::sync::Mutex<Vec<String>>>);
+
+impl WarnSink {
+ fn matching(&self, marker: &str) -> Vec<String> {
+ self.0
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|line| line.contains(marker))
+ .cloned()
+ .collect()
+ }
+}
+
+struct WarnLayer(WarnSink);
+
+impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for WarnLayer {
+ fn on_event(
+ &self,
+ event: &tracing::Event<'_>,
+ _ctx: tracing_subscriber::layer::Context<'_, S>,
+ ) {
+ if *event.metadata().level() != tracing::Level::WARN {
+ return;
+ }
+ struct Message(Option<String>);
+ impl tracing::field::Visit for Message {
+ fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
+ if field.name() == "message" {
+ self.0 = Some(format!("{value:?}"));
+ }
+ }
+ }
+ let mut message = Message(None);
+ event.record(&mut message);
+ if let Some(text) = message.0 {
+ self.0 .0.lock().unwrap().push(text);
+ }
+ }
+}
+
+/// Stands in for `spawn_subagent`: records whether it was ever dispatched, so a
+/// test can prove the tool was not merely absent from the advertisement but
+/// genuinely unreachable.
+struct SpawnProbeTool(Arc<std::sync::atomic::AtomicBool>);
+
+#[async_trait]
+impl Tool for SpawnProbeTool {
+ fn name(&self) -> &str {
+ "spawn_subagent"
+ }
+ fn description(&self) -> &str {
+ "spawn a sub-agent"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.0.store(true, Ordering::SeqCst);
+ Ok(ToolResult::success("spawned"))
+ }
+}
+
+/// Asks for `spawn_subagent` once, then finishes regardless of the answer.
+struct SpawnAttemptProvider {
+ calls: AtomicUsize,
+}
+
+#[async_trait]
+impl ChatModel<()> for SpawnAttemptProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ Ok(tool_response("1", "spawn_subagent", serde_json::json!({})))
+ } else {
+ Ok(ModelResponse::assistant("all done"))
+ }
+ }
+}
+
+const REFUSAL: &str = "refusing to register spawn/delegate tool";
+
+/// Runs one sub-agent turn whose parent surface carries `spawn_subagent`, with
+/// `allowed` deciding whether the allowlist readmits it. Returns
+/// (spawn tool executed?, refusal warnings emitted).
+async fn run_with_spawn_tool_in_parent_surface(allowed: HashSet<String>) -> (bool, Vec<String>) {
+ use tracing_subscriber::layer::SubscriberExt;
+
+ let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let sink = WarnSink::default();
+ let subscriber = tracing_subscriber::registry().with(WarnLayer(sink.clone()));
+ let _subscriber_guard = tracing::subscriber::set_default(subscriber);
+
+ let provider = Arc::new(SpawnAttemptProvider {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![
+ Box::new(EchoTool),
+ Box::new(SpawnProbeTool(executed.clone())),
+ ]);
+ let mut history = vec![ChatMessage::user("spawn a helper")];
+
+ run_subagent_via_graph(
+ crate::openhuman::agent::tinyagents::TurnModelSource::from_model(provider),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ allowed,
+ 10,
+ None,
+ None,
+ "researcher",
+ "task-6157",
+ false,
+ None,
+ std::env::temp_dir(),
+ None,
+ 1024,
+ false,
+ "root-session__spawn_refusal",
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ None,
+ )
+ .await
+ .expect("graph subagent runs");
+
+ (executed.load(Ordering::SeqCst), sink.matching(REFUSAL))
+}
+
+#[tokio::test]
+async fn a_sub_agent_cannot_reach_a_spawn_tool_and_the_healthy_run_is_quiet() {
+ // The real shape: `run_typed_mode` has already stripped `spawn_subagent`
+ // from the allowlist, so the registration-time backstop is re-refusing a
+ // name that was never admitted. That is the happy path and must not warn
+ // (#6157) — the old unconditional warn fired here on every sub-agent run.
+ let allowed = HashSet::from(["echo".to_string()]);
+ let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
+
+ assert!(
+ !executed,
+ "a sub-agent must never be able to invoke spawn_subagent (#4452)"
+ );
+ assert!(
+ warnings.is_empty(),
+ "an already-excluded spawn tool is the happy path, not a warning: {warnings:?}"
+ );
+}
+
+#[tokio::test]
+async fn an_allowlist_that_readmits_a_spawn_tool_is_refused_loudly() {
+ // The misbuilt-allowlist case the backstop exists for: `spawn_subagent` is
+ // admitted, so registration must still refuse it *and* say so — this is the
+ // one shape in which the warning carries information.
+ let allowed = HashSet::from(["echo".to_string(), "spawn_subagent".to_string()]);
+ let (executed, warnings) = run_with_spawn_tool_in_parent_surface(allowed).await;
+
+ assert!(
+ !executed,
+ "the backstop must still refuse the tool, not merely log about it"
+ );
+ assert_eq!(
+ warnings.len(),
+ 1,
+ "the readmitted spawn tool warns exactly once: {warnings:?}"
+ );
+}
diff --git a/src/openhuman/agent/harness/subagent_runner/tool_prep_tests.rs b/src/openhuman/agent/harness/subagent_runner/tool_prep_tests.rs
index 58d137698a..531fdac4f4 100644
--- a/src/openhuman/agent/harness/subagent_runner/tool_prep_tests.rs
+++ b/src/openhuman/agent/harness/subagent_runner/tool_prep_tests.rs
@@ -309,3 +309,108 @@ fn every_essential_action_is_read_only() {
}
}
}
+
+// ── Dynamic-tool spawn strip (#6157) ────────────────────────────────────
+
+use crate::openhuman::tools::Tool;
+use async_trait::async_trait;
+
+/// A tool that is nothing but its name — the strip reads no other field.
+struct NamedTool(&'static str);
+
+#[async_trait]
+impl Tool for NamedTool {
+ /// The caller-chosen name.
+ fn name(&self) -> &str {
+ self.0
+ }
+
+ /// Unused by the strip.
+ fn description(&self) -> &str {
+ "stub"
+ }
+
+ /// Unused by the strip.
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({})
+ }
+
+ /// Never called: the strip only inspects names.
+ async fn execute(
+ &self,
+ _args: serde_json::Value,
+ ) -> anyhow::Result<crate::openhuman::tools::traits::ToolResult> {
+ Ok(crate::openhuman::tools::traits::ToolResult::success(
+ String::new(),
+ ))
+ }
+}
+
+fn dynamic(names: &[&'static str]) -> Vec<Box<dyn Tool>> {
+ names
+ .iter()
+ .map(|name| Box::new(NamedTool(name)) as Box<dyn Tool>)
+ .collect()
+}
+
+fn names_of(tools: &[Box<dyn Tool>]) -> Vec<&str> {
+ tools.iter().map(|t| t.name()).collect()
+}
+
+#[test]
+fn dynamic_tools_keep_ordinary_actions_and_lose_spawn_tools() {
+ // The shape the runner actually builds: Composio actions plus the
+ // progressive-disclosure handoff tool, with spawn tools interleaved.
+ let mut tools = dynamic(&[
+ "GMAIL_FETCH_EMAILS",
+ "spawn_subagent",
+ "extract_from_result",
+ "delegate_graph",
+ "spawn_worker_thread",
+ "GMAIL_SEND_EMAIL",
+ "agent_prepare_context",
+ ]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec![
+ "GMAIL_FETCH_EMAILS",
+ "extract_from_result",
+ "GMAIL_SEND_EMAIL"
+ ],
+ "only spawn/delegate tools are dropped, and surviving order is preserved"
+ );
+}
+
+#[test]
+fn dynamic_tools_lose_unprefixed_delegate_name_overrides() {
+ // The whole reason the strip lives here rather than relying on the
+ // registration-time backstop: that backstop matches `delegate_*` by prefix
+ // and would keep `plan`, which is `planner`'s `delegate_name`.
+ let tmp = tempfile::TempDir::new().unwrap();
+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global(tmp.path())
+ .unwrap();
+
+ let mut tools = dynamic(&["plan", "run_code", "shell", "web_fetch"]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec!["shell", "web_fetch"],
+ "`delegate_name` overrides are spawn tools even without the prefix"
+ );
+}
+
+#[test]
+fn a_dynamic_tool_list_without_spawn_tools_is_untouched() {
+ // The live case today: no dynamic tool is named after a spawn tool, so the
+ // strip must be a no-op rather than a silent narrowing of the surface.
+ let mut tools = dynamic(&["GMAIL_FETCH_EMAILS", "extract_from_result"]);
+ strip_spawn_tools_from_dynamic(&mut tools, "researcher");
+
+ assert_eq!(
+ names_of(&tools),
+ vec!["GMAIL_FETCH_EMAILS", "extract_from_result"]
+ );
+}