Skip to content

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

chore: files changed crates/openhuman-core/src/flows/authoring_host.rs,crates/openhuman-core/src/flo

Steven Enamakel47fb37835268
diff --git a/crates/openhuman-core/src/flows/authoring_host.rs b/crates/openhuman-core/src/flows/authoring_host.rs
index e69de29bb2..e7592c543e 100644
--- a/crates/openhuman-core/src/flows/authoring_host.rs
+++ b/crates/openhuman-core/src/flows/authoring_host.rs
@@ -0,0 +1,215 @@
+//! Scope-bound callbacks used by TinyFlows authoring and catalog operations.
+
+use std::future::Future;
+use std::sync::Arc;
+
+use serde_json::Value;
+use tinybus::Result as BusResult;
+use tinyflows_bus::catalog::{self, ClassifyManifestCandidatesRequest};
+use tinyflows_bus::{AuthoringHost, ToolContract};
+
+use crate::config::Config;
+use crate::core::runtime::{CoreContext, DispatchCtx};
+use crate::flows::ops;
+use crate::modules::tinyflows as module;
+
+#[derive(Clone)]
+struct Callbacks {
+ config: Arc<Config>,
+ context: DispatchCtx,
+ runtime: Option<tokio::runtime::Handle>,
+}
+
+impl Callbacks {
+ async fn in_context<T, F>(&self, work: F) -> Result<T, String>
+ where
+ T: Send + 'static,
+ F: Future<Output = Result<T, String>> + Send + 'static,
+ {
+ let context = self.context.clone();
+ let work = async move {
+ if let Some(core) = context.core().cloned() {
+ CoreContext::scope(core, work).await
+ } else {
+ work.await
+ }
+ };
+ match &self.runtime {
+ Some(runtime) => runtime
+ .spawn(work)
+ .await
+ .map_err(|error| format!("authoring host callback did not finish: {error}"))?,
+ None => work.await,
+ }
+ }
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.AuthoringHost")]
+impl Callbacks {
+ async fn resolve_workflow(&self, workflow_id: String) -> BusResult<Option<Value>> {
+ let config = Arc::clone(&self.config);
+ self.in_context(async move {
+ ops::load_flow_graph(&config, &workflow_id).map(|graph| {
+ graph.map(|graph| serde_json::to_value(graph).expect("graph serializes"))
+ })
+ })
+ .await
+ .map_err(|error| tinybus::Error::failed(error))
+ }
+
+ async fn check_gate(&self, stage: String, graph: Value) -> BusResult<Vec<String>> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ let graph: tinyflows::model::WorkflowGraph =
+ serde_json::from_value(graph).map_err(|error| error.to_string())?;
+ match stage.as_str() {
+ tinyflows_bus::host::TOOL_POLICY => Ok(ops::validate_upload_paths(&graph)),
+ tinyflows_bus::host::AGENT_REFERENCES => {
+ Ok(ops::validate_agent_refs(&context, &config, &graph).await)
+ }
+ tinyflows_bus::host::CONNECTIONS => {
+ Ok(ops::validate_connection_refs(&context, &config, &graph).await)
+ }
+ tinyflows_bus::host::TOOL_CONTRACTS => {
+ Ok(ops::validate_tool_contracts(&config, &graph).await)
+ }
+ _ => Err(format!("unknown TinyFlows authoring gate `{stage}`")),
+ }
+ })
+ .await
+ .map_err(|error| tinybus::Error::failed(error))
+ }
+
+ async fn lookup_tool_contract(&self, slug: String) -> BusResult<Option<ToolContract>> {
+ let config = Arc::clone(&self.config);
+ self.in_context(async move {
+ let Ok((contract, _)) =
+ crate::integrations::composio::catalog::lookup_contract(&config, &slug).await
+ else {
+ return Ok(None);
+ };
+ Ok(Some(ToolContract {
+ output_fields: contract.output_fields,
+ output_schema: contract.output_schema,
+ primary_array_path: contract.primary_array_path,
+ envelope_prefix: Some("data".into()),
+ metadata_fields: vec![
+ "successful".into(),
+ "error".into(),
+ "costUsd".into(),
+ "markdownFormatted".into(),
+ ],
+ }))
+ })
+ .await
+ .map_err(|error| tinybus::Error::failed(error))
+ }
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.ApprovalManifestHost")]
+impl ApprovalCallbacks {
+ async fn classify_manifest_candidates(
+ &self,
+ request: ClassifyManifestCandidatesRequest,
+ ) -> BusResult<catalog::ClassifyManifestCandidatesResponse> {
+ let config = Arc::clone(&self.0.config);
+ self.0
+ .in_context(async move {
+ use crate::flows::tinyflows::caps::classify_composio_action_for_tier;
+ use crate::security::{GateDecision, SecurityPolicy};
+ use tinybox_bus::CommandClass;
+ use tinyflows_bus::catalog::{ManifestCandidate, ManifestClass};
+
+ let security = SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ );
+ let gated = |class: CommandClass| {
+ Some(ManifestClass {
+ name: format!("{class:?}"),
+ blocked: security.gate_decision(class) == GateDecision::Block,
+ skip: false,
+ })
+ };
+ let mut classes = Vec::with_capacity(request.candidates.len());
+ for candidate in request.candidates {
+ let class = match candidate {
+ ManifestCandidate::Http { .. } => gated(CommandClass::Network),
+ ManifestCandidate::Code { .. } => gated(CommandClass::Write),
+ ManifestCandidate::NativeTool {
+ tool_name, args, ..
+ } => {
+ let class = crate::tools::native_ops::classify_tool_call(
+ &config, &tool_name, &args,
+ )
+ .unwrap_or(CommandClass::Network);
+ gated(class)
+ }
+ ManifestCandidate::ConnectorTool { slug, .. } => {
+ let class = classify_composio_action_for_tier(&slug).await;
+ Some(ManifestClass {
+ name: format!("{class:?}"),
+ blocked: security.gate_decision(class) == GateDecision::Block,
+ skip: class == CommandClass::Read,
+ })
+ }
+ ManifestCandidate::DynamicTool { .. } | ManifestCandidate::Agent { .. } => {
+ None
+ }
+ };
+ classes.push(class);
+ }
+ Ok(classes)
+ })
+ .await
+ .map_err(|error| tinybus::Error::failed(error))
+ }
+}
+
+#[derive(Clone)]
+struct ApprovalCallbacks(Callbacks);
+
+/// A callback registration whose lifetime is bounded by one authoring call.
+pub(crate) struct Registration {
+ _registration: module::ServedObjectRegistration,
+ pub(crate) authoring: AuthoringHost,
+ pub(crate) catalog: catalog::CallbackAddress,
+}
+
+pub(crate) async fn register(
+ config: Arc<Config>,
+ context: DispatchCtx,
+) -> Result<Registration, String> {
+ let path = format!(
+ "/ai/tinyhumans/openhuman/AuthoringHost/h{}",
+ uuid::Uuid::new_v4().simple()
+ );
+ let callbacks = Callbacks {
+ config,
+ context,
+ runtime: tokio::runtime::Handle::try_current().ok(),
+ };
+ let registration = module::serve_pair(
+ path.clone(),
+ callbacks.clone(),
+ ApprovalCallbacks(callbacks),
+ )
+ .await?;
+ Ok(Registration {
+ _registration: registration,
+ authoring: AuthoringHost {
+ bus_name: module::HOST_BUS_NAME.to_string(),
+ object_path: path.clone(),
+ },
+ catalog: catalog::CallbackAddress {
+ destination: module::HOST_BUS_NAME.to_string(),
+ object_path: path,
+ },
+ })
+}
+
+#[cfg(test)]
+#[path = "authoring_host_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/authoring_host_tests.rs b/crates/openhuman-core/src/flows/authoring_host_tests.rs
index e69de29bb2..882fb833b0 100644
--- a/crates/openhuman-core/src/flows/authoring_host_tests.rs
+++ b/crates/openhuman-core/src/flows/authoring_host_tests.rs
@@ -0,0 +1,142 @@
+use super::*;
+use serde_json::json;
+
+fn nested_conditional_fan_in() -> Value {
+ json!({
+ "nodes": [
+ {"id":"start","kind":"trigger","name":"Start"},
+ {"id":"outer","kind":"condition","name":"Outer","config":{"field":"outer"}},
+ {"id":"inner","kind":"condition","name":"Inner","config":{"field":"inner"}},
+ {"id":"outer_else","kind":"output_parser","name":"Outer else"},
+ {"id":"inner_else","kind":"output_parser","name":"Inner else"},
+ {"id":"a","kind":"output_parser","name":"A"},
+ {"id":"c","kind":"output_parser","name":"C"},
+ {"id":"merge","kind":"merge","name":"Merge"}
+ ],
+ "edges": [
+ {"from_node":"start","to_node":"outer"},
+ {"from_node":"start","to_node":"c"},
+ {"from_node":"outer","from_port":"true","to_node":"inner"},
+ {"from_node":"outer","from_port":"false","to_node":"outer_else"},
+ {"from_node":"inner","from_port":"true","to_node":"a"},
+ {"from_node":"inner","from_port":"false","to_node":"inner_else"},
+ {"from_node":"a","to_node":"merge"},
+ {"from_node":"c","to_node":"merge"}
+ ]
+ })
+}
+
+#[tokio::test]
+async fn saved_workflow_callback_uses_its_captured_profile_over_the_bus() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+ use crate::tools::toolpacks::ToolGroups;
+
+ let tmp = tempfile::tempdir().expect("temporary workspace");
+ let mut config = Config::default();
+ config.workspace_dir = tmp.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ config.config_path = tmp.path().join("config.toml");
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+
+ let root = CoreContext::for_test_with_config(DomainSet::full(), config.clone());
+ let alice = root.derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::default())
+ .profile("authoring-alice"),
+ );
+ let bob = root.derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::default())
+ .profile("authoring-bob"),
+ );
+ let shared_id = "same-child-id";
+ for (core, graph) in [
+ (&alice, nested_conditional_fan_in()),
+ (
+ &bob,
+ json!({
+ "nodes": [{"id":"start","kind":"trigger","name":"Start"}],
+ "edges": []
+ }),
+ ),
+ ] {
+ let core = Arc::clone(core);
+ let config = config.clone();
+ CoreContext::scope(core, async move {
+ let graph = tinyflows::migrate::deserialize_graph(graph).unwrap();
+ let mut flow = crate::flows::store::create_flow(
+ &config,
+ "scoped child".into(),
+ graph,
+ false,
+ false,
+ )
+ .unwrap();
+ flow.id = shared_id.into();
+ crate::flows::store::upsert_flow(&config, &flow).unwrap();
+ })
+ .await;
+ }
+
+ let alice_registration = register(
+ Arc::new(config.clone()),
+ DispatchCtx::new(Arc::clone(&alice)),
+ )
+ .await
+ .unwrap();
+ let bob_registration = register(Arc::new(config.clone()), DispatchCtx::new(Arc::clone(&bob)))
+ .await
+ .unwrap();
+ let proxy = crate::modules::tinyflows::authoring_proxy(&config)
+ .await
+ .unwrap();
+ let candidate = json!({
+ "nodes": [
+ {"id":"start","kind":"trigger","name":"Start"},
+ {"id":"child","kind":"sub_workflow","name":"Child","config":{"workflow_id":shared_id}}
+ ],
+ "edges": [{"from_node":"start","to_node":"child"}]
+ });
+ let alice_request = tinyflows_bus::ValidateGraphRequest {
+ graph: candidate.clone(),
+ host: Some(alice_registration.authoring.clone()),
+ };
+ let bob_request = tinyflows_bus::ValidateGraphRequest {
+ graph: candidate,
+ host: Some(bob_registration.authoring.clone()),
+ };
+
+ // Each bus call runs while the opposite profile is ambient. Only the
+ // callback's captured DispatchCtx can select the correct saved child.
+ let (alice_report, bob_report) = tokio::join!(
+ CoreContext::scope(Arc::clone(&bob), async {
+ proxy
+ .call::<tinyflows_bus::GraphValidation>(
+ tinyflows_bus::methods::VALIDATE_GRAPH,
+ &(alice_request,),
+ )
+ .await
+ .unwrap()
+ }),
+ CoreContext::scope(Arc::clone(&alice), async {
+ proxy
+ .call::<tinyflows_bus::GraphValidation>(
+ tinyflows_bus::methods::VALIDATE_GRAPH,
+ &(bob_request,),
+ )
+ .await
+ .unwrap()
+ })
+ );
+ assert!(
+ alice_report
+ .errors
+ .iter()
+ .any(|error| error.code == "unsupported_nested_conditional_fan_in"),
+ "Alice must resolve her incompatible child: {:?}",
+ alice_report.errors
+ );
+ assert!(
+ bob_report.errors.is_empty(),
+ "Bob's safe child: {:?}",
+ bob_report.errors
+ );
+}
diff --git a/crates/openhuman-core/src/flows/builder_host.rs b/crates/openhuman-core/src/flows/builder_host.rs
index e69de29bb2..70adf5db07 100644
--- a/crates/openhuman-core/src/flows/builder_host.rs
+++ b/crates/openhuman-core/src/flows/builder_host.rs
@@ -0,0 +1,356 @@
+//! Scope-bound host callbacks for TinyFlows Copilot over TinyBus.
+
+use std::future::Future;
+use std::sync::Arc;
+
+use serde::de::DeserializeOwned;
+use serde_json::{Value, json};
+use tinybus::Result as BusResult;
+use tinyflows_bus::copilot::{self, CopilotHost, PortOperation};
+
+use crate::config::Config;
+use crate::core::runtime::{CoreContext, DispatchCtx};
+use crate::modules::tinyflows as module;
+
+#[derive(Clone)]
+struct FlowsHost {
+ config: Arc<Config>,
+ context: DispatchCtx,
+ runtime: Option<tokio::runtime::Handle>,
+}
+
+impl FlowsHost {
+ async fn in_context<T, F>(&self, work: F) -> Result<T, String>
+ where
+ T: Send + 'static,
+ F: Future<Output = Result<T, String>> + Send + 'static,
+ {
+ let context = self.context.clone();
+ let work = async move {
+ if let Some(core) = context.core().cloned() {
+ CoreContext::scope(core, work).await
+ } else {
+ work.await
+ }
+ };
+ match &self.runtime {
+ Some(runtime) => runtime
+ .spawn(work)
+ .await
+ .map_err(|error| format!("the Copilot host callback did not finish: {error}"))?,
+ None => work.await,
+ }
+ }
+
+ async fn dispatch_call_port(&self, request: copilot::PortCallRequest) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ let payload = request.payload;
+ macro_rules! wire {
+ ($value:expr) => {
+ serde_json::to_value($value).map_err(|error| error.to_string())?
+ };
+ }
+ let value = match request.operation {
+ PortOperation::DraftGet => {
+ wire!(ops::flows_draft_get(&config, &required::<String>(&payload, "id")?)?.value)
+ }
+ PortOperation::DraftCreate => {
+ ops::flows_draft_create_from_copilot(
+ &config,
+ optional_field(&payload, "flow_id")?,
+ required(&payload, "name")?,
+ required(&payload, "graph")?,
+ required(&payload, "origin")?,
+ )?
+ }
+ PortOperation::DraftUpdate => {
+ wire!(ops::flows_draft_update(
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field(&payload, "name")?,
+ optional_field(&payload, "graph")?,
+ None,
+ )?
+ .value)
+ }
+ PortOperation::FlowsGet => {
+ wire!(ops::flows_get(&config, &required::<String>(&payload, "id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsList => wire!(ops::flows_list(&config).await?.value),
+ PortOperation::FlowsLoadGraph => {
+ wire!(ops::load_flow_graph(&config, &required::<String>(&payload, "id")?)?)
+ }
+ PortOperation::FlowsCreate => {
+ wire!(ops::flows_create(
+ &config,
+ required(&payload, "name")?,
+ required(&payload, "graph")?,
+ optional_field::<bool>(&payload, "require_approval")?.unwrap_or(true),
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsUpdate => {
+ let outcome = ops::flows_update(
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field(&payload, "name")?,
+ optional_field(&payload, "graph")?,
+ None,
+ None,
+ )
+ .await?;
+ json!({"value": outcome.value, "logs": outcome.logs})
+ }
+ PortOperation::FlowsSetEnabled => {
+ wire!(ops::flows_set_enabled(
+ &config,
+ &required::<String>(&payload, "id")?,
+ required(&payload, "enabled")?,
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsDuplicate => {
+ wire!(ops::flows_duplicate(&config, &required::<String>(&payload, "id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsHistory => wire!(ops::flows_get_history(
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field::<usize>(&payload, "limit")?.unwrap_or(20),
+ )?
+ .value),
+ PortOperation::FlowsListRuns => wire!(ops::flows_list_runs(
+ &config,
+ &required::<String>(&payload, "flow_id")?,
+ optional_field::<usize>(&payload, "limit")?.unwrap_or(20),
+ )
+ .await?
+ .value),
+ PortOperation::FlowsGetRun => {
+ wire!(ops::flows_get_run(&config, &required::<String>(&payload, "run_id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsResume => {
+ wire!(ops::flows_resume(
+ &context,
+ &config,
+ &required::<String>(&payload, "flow_id")?,
+ &required::<String>(&payload, "run_id")?,
+ optional_field(&payload, "approve")?.unwrap_or_default(),
+ optional_field(&payload, "reject")?.unwrap_or_default(),
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsCancelRun => {
+ wire!(ops::flows_cancel_run(&config, &required::<String>(&payload, "run_id")?)
+ .await?
+ .value)
+ }
+ PortOperation::AgentsList => {
+ let agents = crate::agent::registry::list_agents(&context, false)
+ .await
+ .map_err(|error| error.to_string())?;
+ wire!(agents
+ .iter()
+ .map(|agent| {
+ json!({
+ "id": agent.id,
+ "name": agent.name,
+ "description": agent.description,
+ "model": serde_json::to_value(&agent.model).unwrap_or(Value::Null),
+ "tools": serde_json::to_value(&agent.tool_allowlist).unwrap_or(Value::Null),
+ "tags": serde_json::to_value(&agent.tags).unwrap_or(Value::Null),
+ })
+ })
+ .collect::<Vec<_>>())
+ }
+ PortOperation::SuggestionsUpsert => {
+ json!(ops::flows_suggestions_upsert_from_copilot(
+ &config, payload
+ )?)
+ }
+ PortOperation::GatesValidate => wire!(ops::flows_validate(&context, &config, payload).await.value),
+ PortOperation::GatesRun => {
+ wire!(ops::run_builder_gates_json(&context, &config, payload).await?)
+ }
+ PortOperation::GatesStrict => {
+ ops::strict_gate(&context, &config, &payload).await?;
+ json!(true)
+ }
+ PortOperation::GatesEngineCompatibility => {
+ wire!(ops::engine_compatibility_errors_json(&context, &config, payload).await?)
+ }
+ PortOperation::GatesWiringWarnings => {
+ wire!(ops::wiring_warnings_json(&config, payload).await?)
+ }
+ PortOperation::GatesApprovalManifest => {
+ wire!(ops::approval_manifest_json(&context, &config, payload).await?)
+ }
+ };
+ Ok(value)
+ })
+ .await
+ }
+
+ async fn dispatch_build_proposal(
+ &self,
+ request: copilot::BuildProposalRequest,
+ ) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ ops::build_builder_proposal_json(
+ &context,
+ &config,
+ request.retry_tool,
+ request.name,
+ request.graph,
+ request.require_approval,
+ request.revision,
+ request.instruction,
+ request.draft_id,
+ request.flow_id,
+ )
+ .await
+ })
+ .await
+ }
+
+ async fn dispatch_run_flow(&self, request: copilot::RunFlowRequest) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ ops::flows_run_copilot(
+ &context,
+ &config,
+ &request.flow_id,
+ request.input,
+ request.inputs,
+ )
+ .await
+ .map(|outcome| outcome.value)
+ })
+ .await
+ }
+
+ async fn preflight_tool(&self, slug: String, args: Value) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ self.in_context(async move {
+ if let Some(backend) = crate::flows::tinyflows::caps::tools::backend_for(&slug) {
+ backend
+ .preflight(&config, &slug, &args)
+ .await
+ .map_err(|error| error.to_string())?;
+ }
+ // The module discards this acknowledgement and returns only its
+ // deterministic MockTools result. Never invoke the real backend.
+ Ok(Value::Null)
+ })
+ .await
+ }
+}
+
+fn required<T: DeserializeOwned>(value: &Value, key: &str) -> Result<T, String> {
+ optional_field(value, key)?.ok_or_else(|| format!("missing `{key}`"))
+}
+
+fn optional_field<T: DeserializeOwned>(value: &Value, key: &str) -> Result<Option<T>, String> {
+ match value.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(value) => serde_json::from_value(value.clone())
+ .map(Some)
+ .map_err(|error| format!("bad `{key}`: {error}")),
+ }
+}
+
+fn bus_error(member: &str, error: impl std::fmt::Display) -> tinybus::Error {
+ tracing::debug!(callback = member, %error, "[flows:copilot] host callback failed");
+ tinybus::Error::failed(error)
+}
+
+struct CopilotCapsHost(FlowsHost);
+
+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.CopilotHost")]
+impl FlowsHost {
+ async fn call_port(&self, request: copilot::PortCallRequest) -> BusResult<Value> {
+ self.dispatch_call_port(request)
+ .await
+ .map_err(|error| bus_error("CallPort", error))
+ }
+
+ async fn build_proposal(&self, request: copilot::BuildProposalRequest) -> BusResult<Value> {
+ self.dispatch_build_proposal(request)
+ .await
+ .map_err(|error| bus_error("BuildProposal", error))
+ }
+
+ async fn run_flow(&self, request: copilot::RunFlowRequest) -> BusResult<Value> {
+ self.dispatch_run_flow(request)
+ .await
+ .map_err(|error| bus_error("RunFlow", error))
+ }
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.CapsHost")]
+impl CopilotCapsHost {
+ /// Validate mock tool arguments only; sandbox results stay module-owned.
+ async fn tool_invoke(
+ &self,
+ slug: String,
+ args: Value,
+ _connection: Option<String>,
+ ) -> BusResult<Value> {
+ self.0
+ .preflight_tool(slug, args)
+ .await
+ .map_err(|error| bus_error("ToolInvoke", error))
+ }
+}
+
+/// A served Copilot host callback. Its address is passed in the invocation
+/// envelope and remains fixed for the entire tool call.
+pub(crate) struct HostRegistration {
+ _registration: module::ServedObjectRegistration,
+ address: CopilotHost,
+}
+
+impl HostRegistration {
+ pub(crate) fn address(&self) -> CopilotHost {
+ self.address.clone()
+ }
+}
+
+pub(crate) async fn register(
+ config: Arc<Config>,
+ context: DispatchCtx,
+) -> Result<HostRegistration, String> {
+ let path = format!(
+ "/ai/tinyhumans/openhuman/CopilotHost/h{}",
+ uuid::Uuid::new_v4().simple()
+ );
+ let host = FlowsHost {
+ config,
+ context,
+ runtime: tokio::runtime::Handle::try_current().ok(),
+ };
+ let registration =
+ module::serve_pair(path.clone(), host.clone(), CopilotCapsHost(host)).await?;
+ Ok(HostRegistration {
+ _registration: registration,
+ address: CopilotHost {
+ bus_name: module::HOST_BUS_NAME.to_string(),
+ object_path: path,
+ },
+ })
+}
+
+use super::ops;
diff --git a/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs b/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs
index e69de29bb2..d517387626 100644
--- a/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs
+++ b/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs
@@ -0,0 +1,655 @@
+use super::*;
+
+/// The module's scope gate runs BEFORE any network call, so a Write-scope
+/// action is refused entirely offline — this must never depend on a live
+/// Composio backend to prove the probe can't perform a real mutation.
+#[tokio::test]
+async fn get_tool_output_sample_refuses_a_write_scope_action() {
+ let tmp = TempDir::new().unwrap();
+ let tool = GetToolOutputSampleTool::new(test_config(&tmp));
+ let result = tool
+ .execute(json!({ "slug": "GMAIL_SEND_EMAIL" }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ assert!(
+ result.output().to_lowercase().contains("read-only"),
+ "{}",
+ result.output()
+ );
+}
+
+/// The connected-toolkit gate runs before the real call too — in a test
+/// environment with no backend session, `fetch_connected_integrations`
+/// degrades to empty (best-effort, per its own doc), so a Read-scope action
+/// against an unconnected toolkit is refused without ever reaching a client.
+#[tokio::test]
+async fn get_tool_output_sample_refuses_an_unconnected_toolkit() {
+ let tmp = TempDir::new().unwrap();
+ let tool = GetToolOutputSampleTool::new(test_config(&tmp));
+ let result = tool
+ .execute(json!({ "slug": "GITHUB_LIST_REPOSITORY_ISSUES" }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ assert!(
+ result.output().contains("not connected")
+ || result.output().contains("no active")
+ // The module refuses before the connection check when this test
+ // process has configured no connector route.
+ || result.output().contains("connector route"),
+ "{}",
+ result.output()
+ );
+}
+
+// ── dry_run_workflow ─────────────────────────────────────────────────────────
+
+#[test]
+fn dry_run_is_side_effect_free_and_ungated() {
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ assert_eq!(tool.name(), "dry_run_workflow");
+ // Mock-only + side-effect-free → PermissionLevel::None, available on every
+ // tier including read-only (audit F7).
+ assert_eq!(tool.permission_level(), PermissionLevel::None);
+ assert!(!tool.external_effect());
+}
+
+#[tokio::test]
+async fn dry_run_allowed_under_readonly_tier() {
+ // F7: dry_run is mock-only and side-effect-free, so a read-only agent must
+ // be able to self-verify its own proposal (previously refused).
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ assert_eq!(tool.permission_level(), PermissionLevel::None);
+ let result = tool
+ .execute(json!({ "graph": valid_graph() }))
+ .await
+ .unwrap();
+ // Not refused for tier reasons — it actually runs against the mocks.
+ assert!(!result.is_error, "{}", result.output());
+ assert!(!result.output().to_lowercase().contains("read-only"));
+}
+
+#[tokio::test]
+async fn dry_run_supervised_runs_against_mock_and_labels_sandbox() {
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let result = tool
+ .execute(json!({ "graph": valid_graph(), "input": { "x": 1 } }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["sandbox"], true);
+ assert_eq!(parsed["ok"], true);
+ assert!(
+ parsed["note"]
+ .as_str()
+ .unwrap()
+ .to_lowercase()
+ .contains("sandbox")
+ );
+}
+
+#[tokio::test]
+async fn dry_run_exercises_agent_ref_node_via_mock_agent_runner() {
+ // A draft whose `agent` node selects a named agent kind (`agent_ref`) routes
+ // to the `AgentRunner` capability, not the plain LLM. Before wiring the mock
+ // runner the sandbox left `agent: None`, so such a draft errored on a missing
+ // capability; now `mock_capabilities_with_agent(MockAgentRunner)` echoes the
+ // ref and the dry run goes green — proving the builder can self-test drafts
+ // that use agent-kind nodes.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": "planner", "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ });
+ let result = tool
+ .execute(json!({ "graph": graph, "input": { "topic": "x" } }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["sandbox"], true);
+ assert_eq!(
+ parsed["ok"], true,
+ "agent_ref dry-run must be green: {parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_plain_agent_with_output_parser_schema_is_green() {
+ // Regression for the transcript false-failure: a builder-generated `agent`
+ // node carries NO `agent_ref`, so the vendored engine routes it to the
+ // `llm` slot (not the `AgentRunner`). Before `SchemaAwareMockLlm` the plain
+ // `MockLlm` echo (`{ completion, connection }`) failed the node's
+ // `output_parser.schema` sub-port with `output_parser: value failed schema
+ // validation after auto-fix: missing required property ...`, sinking a
+ // correctly-built graph. Now the mock LLM synthesizes a schema-valid object,
+ // and a downstream node binds the typed placeholders (non-null).
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Schedule",
+ "config": { "trigger_kind": "schedule" } },
+ { "id": "a", "kind": "agent", "name": "Extract",
+ "config": { "prompt": "extract the fields",
+ "output_parser": { "schema": { "type": "object",
+ "required": ["subject", "priority", "recipients"],
+ "properties": {
+ "subject": { "type": "string" },
+ "priority": { "type": "integer" },
+ "recipients": { "type": "array" }
+ } } } } },
+ // Downstream node binds the schema'd agent fields: proves the
+ // placeholders are addressable and resolve to typed (non-null)
+ // values, not the vendored echo's opaque `{ completion, ... }`.
+ { "id": "down", "kind": "transform", "name": "Route",
+ "config": { "set": {
+ "subject": "=nodes.a.item.json.subject",
+ "priority": "=nodes.a.item.json.priority",
+ "recipients": "=nodes.a.item.json.recipients" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "a" },
+ { "from_node": "a", "to_node": "down" }
+ ]
+ });
+ let result = tool
+ .execute(json!({ "graph": graph, "input": { "topic": "launch" } }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let out = result.output();
+ assert!(
+ !out.to_lowercase().contains("schema validation"),
+ "plain agent with a valid schema must not hit the output_parser failure: {out}"
+ );
+ let parsed: Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(parsed["sandbox"], true);
+ assert_eq!(
+ parsed["ok"], true,
+ "plain-agent-with-schema dry-run must be green: {parsed}"
+ );
+ // The agent envelope's `json` carries the schema-synthesized placeholders.
+ // (In the run OUTPUT each Item serializes as `{ json: <value> }`, and the
+ // agent's value is the `{json,text,raw}` envelope — hence the double hop.)
+ let agent_json = &parsed["output"]["nodes"]["a"]["items"][0]["json"]["json"];
+ assert_eq!(agent_json["subject"], "", "{parsed}");
+ assert_eq!(agent_json["priority"], 0, "{parsed}");
+ assert_eq!(agent_json["recipients"], json!([]), "{parsed}");
+ // The downstream node's bindings resolved to those typed placeholders —
+ // none of them null.
+ let down_json = &parsed["output"]["nodes"]["down"]["items"][0]["json"];
+ assert!(!down_json["subject"].is_null(), "{parsed}");
+ assert_eq!(down_json["priority"], 0, "{parsed}");
+ assert_eq!(down_json["recipients"], json!([]), "{parsed}");
+}
+
+#[tokio::test]
+async fn dry_run_invalid_graph_is_error() {
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let result = tool
+ .execute(json!({ "graph": { "nodes": [], "edges": [] } }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+}
+
+#[tokio::test]
+async fn dry_run_catches_unwired_required_composio_arg() {
+ // Seed the preflight schema cache so no live Composio backend is needed.
+ // NOTE: the cache is process-global and other tests seed the `gmail`
+ // toolkit too — keep every seeding of GMAIL_SEND_EMAIL identical
+ // (`to` + `body`) so test order can't change the outcome.
+ seed_live_catalog_cache("gmail", vec![seeded_gmail_send_contract()]);
+
+ let tmp = TempDir::new().unwrap();
+ let tool = dry_run_workflow_tool(test_config(&tmp));
+
+ let graph_with = |args: Value| {
+ json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "send", "kind": "tool_call", "name": "Send email",
+ "config": { "slug": "GMAIL_SEND_EMAIL", "args": args } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "send" } ]
+ })
+ };
+
+ // `to` is a `=`-expression that misses (trigger input has no `email`):
+ // the dry run must fail BEFORE the (mock) tool call, naming the field.
+ let result = tool
+ .execute(json!({
+ "graph": graph_with(json!({ "to": "=item.email", "body": "hello" })),
+ "input": {}
+ }))
+ .await
+ .unwrap();
+ let out = result.output();
+ assert!(
+ out.contains("`to`") && out.contains("required"),
+ "dry run must name the unwired required arg: {out}"
+ );
+
+ // The same flow with `to` wired from the trigger passes the preflight.
+ let result = tool
+ .execute(json!({
+ "graph": graph_with(json!({ "to": "=item.email", "body": "hello" })),
+ "input": { "email": "[email protected]" }
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["sandbox"], true);
+ assert_eq!(
+ parsed["ok"], true,
+ "wired flow must dry-run green: {parsed}"
+ );
+}
+
+// ── dry_run_workflow: null-resolution check ─────────────────────────────────
+
+#[tokio::test]
+async fn dry_run_flags_tool_call_arg_null_resolved_from_unschemad_agent() {
+ // The `summarize` agent has no `output_parser.schema`, so (via the
+ // schema-aware mock agent) its structured output has no `channel` field —
+ // the exact "builds but does nothing" shape this check exists to catch.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "summarize", "kind": "agent", "name": "Summarize",
+ "config": { "agent_ref": "planner", "prompt": "summarize" } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "oh:noop",
+ "args": { "channel": "=nodes.summarize.item.json.channel" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "summarize" },
+ { "from_node": "summarize", "to_node": "post" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["sandbox"], true,
+ "still labeled a sandbox result: {parsed}"
+ );
+ assert_eq!(
+ parsed["ok"], false,
+ "a null-resolved tool_call arg must fail the dry run: {parsed}"
+ );
+ let null_resolutions = parsed["null_resolutions"]
+ .as_array()
+ .expect("null_resolutions array");
+ assert_eq!(null_resolutions.len(), 1, "{parsed}");
+ assert_eq!(null_resolutions[0]["node_id"], "post");
+ assert_eq!(null_resolutions[0]["location"], "args.channel");
+ assert_eq!(
+ null_resolutions[0]["expression"],
+ "=nodes.summarize.item.json.channel"
+ );
+ assert!(
+ parsed["message"]
+ .as_str()
+ .unwrap()
+ .to_lowercase()
+ .contains("output_parser"),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_flags_composio_upstream_binding_as_unverifiable_not_a_wiring_bug() {
+ // WS6: `post`'s `body` binds to the OUTPUT of an upstream Composio
+ // `tool_call` (`get_me`). The echo sandbox renders `get_me` as
+ // `{tool, args, connection}` and can NEVER produce `.item.json.data.username`,
+ // so the binding resolves `null` here even when it's wired correctly. The
+ // dry run still fails (`ok: false` — a null could hide a typo), but the
+ // diagnostic must be HONEST: mark it `unverifiable` and point at
+ // get_tool_contract / get_tool_output_sample rather than telling the agent
+ // its (possibly-correct) wiring is broken — the exact false negative that
+ // sent the transcript agent re-wiring an already-correct binding 3 times.
+ // Seed bespoke toolkits (no other test touches `ws6up`/`ws6dl`) with NO
+ // required args, so the required-arg preflight passes and the run settles
+ // into the `null_resolutions` path deterministically — independent of the
+ // process-global catalog cache other tests seed for gmail/slack/etc.
+ seed_live_catalog_cache("ws6up", vec![seeded_ws6_contract("WS6UP_LOOKUP", "ws6up")]);
+ seed_live_catalog_cache("ws6dl", vec![seeded_ws6_contract("WS6DL_SEND", "ws6dl")]);
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "get_me", "kind": "tool_call", "name": "Who am I",
+ "config": { "slug": "WS6UP_LOOKUP", "args": {} } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "WS6DL_SEND",
+ "args": { "recipient_email": "[email protected]", "subject": "hi",
+ "body": "=nodes.get_me.item.json.data.username" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "get_me" },
+ { "from_node": "get_me", "to_node": "post" }
+ ]
+ });
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["ok"], false, "{parsed}");
+ let null_resolutions = parsed["null_resolutions"]
+ .as_array()
+ .expect("null_resolutions array");
+ let entry = null_resolutions
+ .iter()
+ .find(|e| e["node_id"] == "post" && e["location"] == "args.body")
+ .unwrap_or_else(|| panic!("expected a post.body null resolution: {parsed}"));
+ assert_eq!(entry["unverifiable"], true, "{parsed}");
+ assert_eq!(entry["upstream_tool_call"], "get_me", "{parsed}");
+ let suggestion = entry["suggestion"].as_str().expect("suggestion string");
+ assert!(suggestion.contains("UNVERIFIABLE"), "{suggestion}");
+ assert!(suggestion.contains("get_tool_contract"), "{suggestion}");
+ assert!(
+ suggestion.contains("get_tool_output_sample"),
+ "{suggestion}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_keeps_generic_null_text_for_a_non_tool_call_upstream_binding() {
+ // WS6 contrast: `post`'s arg binds to a `transform` node's output (whose
+ // real output the echo sandbox DOES produce), and the transform never sets
+ // the referenced field, so the null IS a genuine wiring bug. This entry must
+ // stay the plain `{ node_id, location, expression }` shape — no
+ // `unverifiable` flag — so the honest-uncertainty treatment doesn't leak
+ // onto real mistakes.
+ seed_live_catalog_cache("ws6dl", vec![seeded_ws6_contract("WS6DL_SEND", "ws6dl")]);
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "build", "kind": "transform", "name": "Build",
+ "config": { "set": { "unrelated": "x" } } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "WS6DL_SEND",
+ "args": { "recipient_email": "[email protected]", "subject": "hi",
+ "body": "=nodes.build.item.json.missing" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "build" },
+ { "from_node": "build", "to_node": "post" }
+ ]
+ });
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["ok"], false, "{parsed}");
+ let entry = parsed["null_resolutions"]
+ .as_array()
+ .expect("null_resolutions array")
+ .iter()
+ .find(|e| e["node_id"] == "post" && e["location"] == "args.body")
+ .unwrap_or_else(|| panic!("expected a post.body null resolution: {parsed}"));
+ assert!(
+ entry.get("unverifiable").is_none(),
+ "a non-tool_call upstream must keep the generic diagnostic: {parsed}"
+ );
+ assert!(
+ entry.get("suggestion").is_none(),
+ "generic entry carries no unverifiable suggestion: {parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_passes_when_agent_schema_matches_tool_call_binding() {
+ // The FALSE-POSITIVE-PREVENTION case: `summarize` DOES declare a schema
+ // covering `channel`, and `post` binds exactly that field. Without the
+ // schema-aware mock agent (i.e. with the vendored `MockAgentRunner`, which
+ // always echoes `{ agent, request, connection }` regardless of schema)
+ // this would incorrectly fail — proving the mock is what makes the check
+ // accurate rather than perpetually red for correctly-built graphs.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "summarize", "kind": "agent", "name": "Summarize",
+ "config": { "agent_ref": "planner", "prompt": "summarize",
+ "output_parser": { "schema": { "type": "object",
+ "required": ["channel"],
+ "properties": { "channel": { "type": "string" } } } } } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "oh:noop",
+ "args": { "channel": "=nodes.summarize.item.json.channel" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "summarize" },
+ { "from_node": "summarize", "to_node": "post" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], true,
+ "schema-aware mock must satisfy the declared schema: {parsed}"
+ );
+ assert!(
+ parsed["null_resolutions"].as_array().unwrap().is_empty(),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_passes_when_tool_call_binds_to_upstream_tool_output() {
+ // A `tool_call` binding to another `tool_call`'s real output (not an
+ // agent at all) must not be affected by the agent-schema machinery above.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "lookup", "kind": "tool_call", "name": "Lookup",
+ "config": { "slug": "oh:lookup", "args": {} } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "oh:noop",
+ "args": { "channel": "=nodes.lookup.item.json.tool" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "lookup" },
+ { "from_node": "lookup", "to_node": "post" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["ok"], true, "{parsed}");
+ assert!(
+ parsed["null_resolutions"].as_array().unwrap().is_empty(),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_flags_tool_call_error_when_on_error_is_route() {
+ // `on_error: "route"` converts the preflight failure into a routed error
+ // ITEM so the SANDBOX RUN as a whole still completes (`Ok(outcome)`) —
+ // exactly the case the naive `null_resolutions`-only check would miss,
+ // because the failing node's diagnostics stay empty (the engine never
+ // got far enough to trace an `=`-expression before the preflight error).
+ // Seed the same schema as `dry_run_catches_unwired_required_composio_arg`
+ // (process-global cache; keep the arg list identical across tests).
+ //
+ // The graph must give `post`'s `error` port a real destination: vendored
+ // tinyflows' author-time `validate()` (added alongside per-node error
+ // handling — a graph with `on_error: "route"` but no outgoing `error`-port
+ // edge is now rejected up front, since a route with nowhere to go is
+ // always a dead-end) would otherwise reject this graph before the sandbox
+ // run ever starts, which is a different failure mode than the one this
+ // test targets. `recover` is a no-op sink, same convention as
+ // `dry_run_passes_when_tool_call_binds_to_upstream_tool_output` above.
+ seed_live_catalog_cache("gmail", vec![seeded_gmail_send_contract()]);
+
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Send email",
+ "config": { "slug": "GMAIL_SEND_EMAIL", "on_error": "route",
+ "args": { "to": "=item.email", "body": "hello" } } },
+ { "id": "recover", "kind": "tool_call", "name": "Recover",
+ "config": { "slug": "oh:noop", "args": {} } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "from_port": "error", "to_node": "recover" }
+ ]
+ });
+
+ // `to` misses (trigger input has no `email`) — a real run would fail the
+ // preflight; `on_error: "route"` must not let that slip through as `ok: true`.
+ let result = tool
+ .execute(json!({ "graph": graph, "input": {} }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], false,
+ "on_error: route must not mask a real tool_call failure: {parsed}"
+ );
+ let node_errors = parsed["node_errors"].as_array().expect("node_errors array");
+ assert_eq!(node_errors.len(), 1, "{parsed}");
+ assert_eq!(node_errors[0]["node_id"], "post");
+ assert!(
+ node_errors[0]["error"].as_str().unwrap().contains("to"),
+ "error must name the missing field: {parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_flags_tool_call_error_when_on_error_is_continue() {
+ // Same case as above, but `on_error: "continue"` — the other policy that
+ // converts a node failure into routed data instead of failing the run.
+ seed_live_catalog_cache("gmail", vec![seeded_gmail_send_contract()]);
+
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Send email",
+ "config": { "slug": "GMAIL_SEND_EMAIL", "on_error": "continue",
+ "args": { "to": "=item.email", "body": "hello" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ });
+
+ let result = tool
+ .execute(json!({ "graph": graph, "input": {} }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], false,
+ "on_error: continue must not mask a real tool_call failure: {parsed}"
+ );
+ assert_eq!(
+ parsed["node_errors"].as_array().unwrap().len(),
+ 1,
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_passes_when_agent_enum_schema_binds_to_tool_call() {
+ // The agent declares an `enum`-constrained field; the schema-aware mock
+ // must synthesize an ALLOWED value (not a generic `""` placeholder, which
+ // would fail the vendored validator's `enum` check) so a correctly-built
+ // graph using an enum schema dry-runs green instead of false-positiving.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "triage", "kind": "agent", "name": "Triage",
+ "config": { "agent_ref": "planner", "prompt": "triage this",
+ "output_parser": { "schema": { "type": "object",
+ "required": ["priority"],
+ "properties": {
+ "priority": { "type": "string", "enum": ["urgent", "normal"] }
+ } } } } },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "oh:noop",
+ "args": { "priority": "=nodes.triage.item.json.priority" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "triage" },
+ { "from_node": "triage", "to_node": "post" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], true,
+ "enum-schema agent must dry-run green: {parsed}"
+ );
+ assert!(parsed["null_resolutions"].as_array().unwrap().is_empty());
+ assert!(parsed["node_errors"].as_array().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn dry_run_flags_null_resolved_agent_prompt() {
+ // The exact root-cause bug PR A/B/C exist to catch: `prompt` itself is a
+ // `=`-expression that reads as prose, not a valid jq program — the
+ // vendored engine's own `resolve_traced` records it as a null resolution
+ // at `location: "prompt"`, meaning the agent would run with an EMPTY
+ // prompt. Unlike other agent-config nulls, this one must fail the dry run.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "classify", "kind": "agent", "name": "Classify",
+ "config": { "prompt": "=You are given an email: .item. Classify the following \
+ email as urgent/normal/low priority." } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "classify" } ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], false,
+ "a null-resolved agent prompt must fail the dry run: {parsed}"
+ );
+ let agent_prompt_nulls = parsed["agent_prompt_nulls"]
+ .as_array()
+ .expect("agent_prompt_nulls array");
+ assert_eq!(agent_prompt_nulls.len(), 1, "{parsed}");
+ assert_eq!(agent_prompt_nulls[0]["node_id"], "classify");
+ assert_eq!(agent_prompt_nulls[0]["location"], "prompt");
+ assert!(
+ agent_prompt_nulls[0]["suggestion"]
+ .as_str()
+ .unwrap()
+ .contains("input_context"),
+ "{parsed}"
+ );
+ assert!(
+ parsed["message"]
+ .as_str()
+ .unwrap()
+ .to_lowercase()
+ .contains("input_context"),
+ "{parsed}"
+ );
+}
diff --git a/crates/openhuman-core/src/flows/builder_tools_save_and_edit_tests.rs b/crates/openhuman-core/src/flows/builder_tools_save_and_edit_tests.rs
index e69de29bb2..4450748b44 100644
--- a/crates/openhuman-core/src/flows/builder_tools_save_and_edit_tests.rs
+++ b/crates/openhuman-core/src/flows/builder_tools_save_and_edit_tests.rs
@@ -0,0 +1,636 @@
+use super::*;
+
+#[tokio::test]
+async fn dry_run_flags_null_resolved_agent_input_context() {
+ // The B7 counterpart to `dry_run_flags_null_resolved_agent_prompt`:
+ // `input_context` has been the agent's primary upstream-data channel
+ // since #4590, so a null-resolved `input_context` is just as
+ // execution-breaking as a null `prompt` — the agent runs with no
+ // upstream data at all. Must fail the dry run the same way.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "classify", "kind": "agent", "name": "Classify",
+ "config": { "prompt": "Classify the email as urgent, normal, or low priority.",
+ "input_context": "=nodes.missing.item.json.body" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "classify" } ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], false,
+ "a null-resolved agent input_context must fail the dry run: {parsed}"
+ );
+ let agent_input_context_nulls = parsed["agent_input_context_nulls"]
+ .as_array()
+ .expect("agent_input_context_nulls array");
+ assert_eq!(agent_input_context_nulls.len(), 1, "{parsed}");
+ assert_eq!(agent_input_context_nulls[0]["node_id"], "classify");
+ assert_eq!(agent_input_context_nulls[0]["location"], "input_context");
+ assert!(
+ agent_input_context_nulls[0]["suggestion"]
+ .as_str()
+ .unwrap()
+ .contains("upstream"),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_passes_when_agent_uses_input_context_instead_of_prompt_expression() {
+ // The FALSE-POSITIVE-PREVENTION case: the same data need, wired the
+ // correct way — `input_context` carries the upstream item, `prompt`
+ // stays a plain instruction with no leading `=`. This must dry-run green.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "classify", "kind": "agent", "name": "Classify",
+ "config": { "prompt": "Classify the email as urgent, normal, or low priority.",
+ "input_context": "=item" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "classify" } ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["ok"], true, "{parsed}");
+ assert!(
+ parsed["agent_prompt_nulls"].as_array().unwrap().is_empty(),
+ "{parsed}"
+ );
+ assert!(
+ parsed["agent_input_context_nulls"]
+ .as_array()
+ .unwrap()
+ .is_empty(),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_warns_on_unexercised_agent_after_condition() {
+ // B15's dry-run blind spot: `gate` is a `condition` wired with only a
+ // `true` edge to `classify`. The dry run's default trigger input is `{}`
+ // (no `input` param passed), so `gate`'s configured field ("active") is
+ // absent — falsey — and the condition emits `false`. Since `false` has no
+ // outgoing edge, `classify` never executes at all: not a null resolution,
+ // not a node error, just silently unexercised. A real trigger's payload
+ // could easily carry `active: true` and take the other branch, so the
+ // dry run must still surface this as a warning even though `ok` stays
+ // `true` — there's nothing here that flips it to a hard reject.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "gate", "kind": "condition", "name": "Gate",
+ "config": { "field": "active" } },
+ { "id": "classify", "kind": "agent", "name": "Classify",
+ "config": { "prompt": "Classify the item.", "input_context": "=item" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "from_port": "true", "to_node": "classify" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["ok"], true,
+ "an unexercised branch is a warning, not a hard reject: {parsed}"
+ );
+ let warnings = parsed["routing_divergence_warnings"]
+ .as_array()
+ .expect("routing_divergence_warnings array");
+ assert_eq!(warnings.len(), 1, "{parsed}");
+ assert_eq!(warnings[0]["node_id"], "classify");
+ assert_eq!(warnings[0]["condition_node_id"], "gate");
+ assert!(
+ warnings[0]["message"]
+ .as_str()
+ .unwrap()
+ .contains("classify"),
+ "{parsed}"
+ );
+}
+
+#[tokio::test]
+async fn dry_run_no_routing_divergence_warning_when_every_node_executes() {
+ // FALSE-POSITIVE-PREVENTION: a condition whose taken branch under the
+ // default mock input DOES reach the downstream agent must not warn.
+ let tool = dry_run_workflow_tool(test_config(&TempDir::new().unwrap()));
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "gate", "kind": "condition", "name": "Gate",
+ "config": { "field": "active" } },
+ { "id": "classify", "kind": "agent", "name": "Classify",
+ "config": { "prompt": "Classify the item.", "input_context": "=item" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "from_port": "false", "to_node": "classify" }
+ ]
+ });
+
+ let result = tool.execute(json!({ "graph": graph })).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["ok"], true, "{parsed}");
+ assert!(
+ parsed["routing_divergence_warnings"]
+ .as_array()
+ .unwrap()
+ .is_empty(),
+ "{parsed}"
+ );
+}
+
+/// (systemic tool-contract fix, Part 2b) A missing required Composio arg is
+/// now a HARD REJECT at `revise_workflow` — `validate_tool_contracts` runs
+/// ahead of the older advisory `graph_wiring_warnings` check and catches the
+/// exact same condition first, so the graph never gets far enough to merely
+/// warn about it. `graph_wiring_warnings`'s own required-arg warning (still
+/// exercised directly in `ops_tests.rs`) stays as a defense-in-depth
+/// fallback for any caller that doesn't also run `validate_tool_contracts`.
+#[tokio::test]
+async fn revise_workflow_rejects_a_missing_required_composio_arg() {
+ seed_live_catalog_cache("gmail", vec![seeded_gmail_send_contract()]);
+
+ let tmp = TempDir::new().unwrap();
+ let tool = revise_workflow_tool(test_config(&tmp));
+ let result = tool
+ .execute(json!({
+ "name": "Send mail",
+ "graph": {
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "send", "kind": "tool_call", "name": "Send",
+ // `body` wired via expression (counts as wired); `to` absent.
+ "config": { "slug": "GMAIL_SEND_EMAIL",
+ "args": { "body": "=item.text" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "send" } ]
+ }
+ }))
+ .await
+ .unwrap();
+
+ assert!(
+ result.is_error,
+ "a missing required arg must now hard-reject"
+ );
+ let output = result.output();
+ assert!(output.contains("send"), "{output}");
+ assert!(output.contains("`to`"), "{output}");
+ // `body` is wired (expression) — never named as missing.
+ assert!(!output.contains("`body`"), "{output}");
+}
+
+#[tokio::test]
+async fn save_workflow_missing_flow_id_is_error() {
+ let tmp = TempDir::new().unwrap();
+ let tool = save_workflow_tool(test_config(&tmp));
+ // Persisting a definition is a Write-class action (no external effect at
+ // save time — the flow's own runs govern that).
+ assert_eq!(tool.permission_level(), PermissionLevel::Write);
+ assert!(!tool.external_effect());
+
+ let result = tool
+ .execute(json!({ "graph": valid_graph() }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ assert!(result.output().contains("Missing 'flow_id'"));
+}
+
+#[tokio::test]
+async fn save_workflow_unknown_flow_is_error() {
+ let tmp = TempDir::new().unwrap();
+ let tool = save_workflow_tool(test_config(&tmp));
+
+ let result = tool
+ .execute(json!({ "flow_id": "nope", "graph": valid_graph() }))
+ .await
+ .unwrap();
+ assert!(result.is_error, "save onto a nonexistent flow must fail");
+ assert!(result.output().contains("nope"));
+}
+
+#[tokio::test]
+async fn save_workflow_persists_graph_and_name_onto_existing_flow() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = seed_flow(&config, "Blank flow").await;
+ let tool = save_workflow_tool(config.clone());
+
+ let result = tool
+ .execute(json!({
+ "flow_id": flow_id,
+ "graph": valid_graph(),
+ "name": "AI News Digest"
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["type"], "workflow_saved");
+ assert_eq!(parsed["flow_id"], flow_id.as_str());
+ assert_eq!(parsed["name"], "AI News Digest");
+ assert_eq!(parsed["node_count"], 2);
+ // Enablement / approval gate are NOT touched by the tool.
+ assert_eq!(parsed["require_approval"], true);
+
+ // The graph + name really persisted.
+ let saved = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert_eq!(saved.name, "AI News Digest");
+ assert_eq!(saved.graph.nodes.len(), 2);
+}
+
+#[tokio::test]
+async fn save_workflow_rejects_invalid_graph_and_leaves_flow_intact() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = seed_flow(&config, "Blank flow").await;
+ let tool = save_workflow_tool(config.clone());
+
+ let result = tool
+ .execute(json!({
+ "flow_id": flow_id,
+ // No trigger node — fails tinyflows validation.
+ "graph": { "nodes": [ { "id": "a", "kind": "agent", "name": "A" } ], "edges": [] }
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+
+ let saved = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert_eq!(saved.name, "Blank flow");
+ assert_eq!(
+ saved.graph.nodes.len(),
+ 1,
+ "original graph must be untouched"
+ );
+}
+
+#[tokio::test]
+async fn save_workflow_surfaces_auto_disarm_warning_on_manual_to_automatic_transition() {
+ // Regression for #4889 + the stale-docs issue that motivated this test:
+ // `flows_update` auto-disables a flow whenever its trigger transitions
+ // from manual to automatic on an already-enabled flow, but `save_workflow`
+ // used to drop `flows_update`'s explanatory `Outcome.logs` entirely —
+ // the agent had no way to relay the disarm to the user. Assert both the
+ // disarm itself and that its log now surfaces in `save_workflow`'s
+ // `warnings`.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = seed_flow(&config, "Manual flow").await;
+ let seeded = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert!(
+ seeded.enabled,
+ "precondition: a manual-trigger flow persists enabled from create"
+ );
+
+ let tool = save_workflow_tool(config.clone());
+ let result = tool
+ .execute(json!({
+ "flow_id": flow_id,
+ "graph": schedule_trigger_graph(),
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(
+ parsed["enabled"], false,
+ "manual→automatic transition on an enabled flow must auto-disable it: {parsed}"
+ );
+ let warnings = parsed["warnings"]
+ .as_array()
+ .expect("warnings must be an array");
+ assert!(
+ warnings
+ .iter()
+ .any(|w| w.as_str().unwrap_or("").contains("auto-disabled")),
+ "save_workflow must surface flows_update's disarm log as a warning, got: {parsed}"
+ );
+ let flow_updated_boilerplate = format!("flow updated: {flow_id}");
+ assert!(
+ warnings
+ .iter()
+ .all(|w| w.as_str().unwrap_or("") != flow_updated_boilerplate),
+ "save_workflow must exclude the redundant \"flow updated: <id>\" boilerplate \
+ from warnings, got: {parsed}"
+ );
+
+ // Persisted, not just returned in-memory.
+ let reloaded = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert!(!reloaded.enabled);
+}
+
+#[tokio::test]
+async fn save_workflow_rejects_agent_binding_missing_declared_field() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = seed_flow(&config, "Blank flow").await;
+ let tool = save_workflow_tool(config.clone());
+
+ let result = tool
+ .execute(json!({ "flow_id": flow_id, "graph": unresolvable_binding_graph() }))
+ .await
+ .unwrap();
+
+ assert!(result.is_error, "must be rejected: {}", result.output());
+ let output = result.output();
+ assert!(output.contains("notify"), "{output}");
+ assert!(output.contains("channel"), "{output}");
+ assert!(output.contains("summarize"), "{output}");
+ assert!(output.contains("output_parser.schema"), "{output}");
+
+ // The flow it tried to save onto must be untouched.
+ let saved = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert_eq!(saved.name, "Blank flow");
+ assert_eq!(
+ saved.graph.nodes.len(),
+ 1,
+ "original graph must be untouched"
+ );
+}
+
+#[tokio::test]
+async fn save_workflow_accepts_correctly_schemad_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = seed_flow(&config, "Blank flow").await;
+ let tool = save_workflow_tool(config.clone());
+
+ let graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "summarize", "kind": "agent", "name": "Summarize",
+ "config": { "agent_ref": "planner", "prompt": "summarize",
+ "output_parser": { "schema": { "type": "object",
+ "required": ["channel"],
+ "properties": { "channel": { "type": "string" } } } } } },
+ { "id": "notify", "kind": "tool_call", "name": "Notify",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "=nodes.summarize.item.json.channel" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "summarize" },
+ { "from_node": "summarize", "to_node": "notify" }
+ ]
+ });
+
+ let result = tool
+ .execute(json!({ "flow_id": flow_id, "graph": graph, "name": "Summarize and notify" }))
+ .await
+ .unwrap();
+
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["type"], "workflow_saved");
+ assert_eq!(parsed["node_count"], 3);
+
+ let saved = ops::flows_get(&config, &flow_id).await.unwrap().value;
+ assert_eq!(saved.name, "Summarize and notify");
+ assert_eq!(saved.graph.nodes.len(), 3);
+}
+
+#[tokio::test]
+async fn list_node_kinds_tool_returns_every_kind() {
+ let tool = list_node_kinds_tool(Arc::new(Config::default()));
+ let result = tool.execute(json!({})).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ let kinds = parsed["node_kinds"].as_array().unwrap();
+ assert_eq!(kinds.len(), tinyflows::catalog::NODE_KINDS.len());
+ // The tool must advertise the whole catalog, not a subset that happens to
+ // include the kinds someone remembered to name here — a kind the engine
+ // knows but this tool omits is a kind the builder agent cannot reach.
+ for kind in tinyflows::catalog::NODE_KINDS {
+ assert!(
+ kinds.iter().any(|k| k["kind"] == kind),
+ "list_node_kinds omits `{kind}`"
+ );
+ }
+ // Each entry carries a kind + summary + the config-field name lists.
+ assert!(kinds.iter().all(|k| k.get("summary").is_some()));
+}
+
+#[tokio::test]
+async fn get_node_kind_contract_tool_returns_contract_and_rejects_unknown() {
+ let tool = get_node_kind_contract_tool(Arc::new(Config::default()));
+
+ let ok = tool.execute(json!({ "kind": "tool_call" })).await.unwrap();
+ assert!(!ok.is_error, "{}", ok.output());
+ let parsed: Value = serde_json::from_str(&ok.output()).unwrap();
+ assert_eq!(parsed["kind"], "tool_call");
+ assert!(
+ parsed["config_fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|f| f["name"] == "slug")
+ );
+ // Host overlay is present on the tool's output.
+ assert!(
+ parsed["notes"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|n| n.as_str().unwrap_or("").contains("Composio"))
+ );
+
+ let bad = tool.execute(json!({ "kind": "nope" })).await.unwrap();
+ assert!(bad.is_error);
+ assert!(bad.output().contains("list_node_kinds"));
+ assert!(bad.output().contains(&format!(
+ "{} valid kinds",
+ tinyflows::catalog::NODE_KINDS.len()
+ )));
+
+ let missing = tool.execute(json!({})).await.unwrap();
+ assert!(missing.is_error);
+}
+
+// ── edit_workflow (F1: structured incremental edits) ─────────────────────────
+
+#[tokio::test]
+async fn edit_workflow_applies_ops_to_inline_graph_and_returns_proposal() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+
+ // Add a merge node `b` and wire the agent into it.
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "name": "Edited flow",
+ "instruction": "add a merge step",
+ "ops": [
+ { "op": "add_node", "node": { "id": "b", "kind": "merge", "name": "Join" } },
+ { "op": "add_edge", "edge": { "from_node": "a", "to_node": "b" } }
+ ]
+ }))
+ .await
+ .unwrap();
+
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["type"], "workflow_proposal");
+ assert_eq!(parsed["name"], "Edited flow");
+ assert_eq!(parsed["graph"]["nodes"].as_array().unwrap().len(), 3);
+ assert_eq!(parsed["graph"]["edges"].as_array().unwrap().len(), 2);
+}
+
+#[tokio::test]
+async fn edit_workflow_update_node_config_merge_patches() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "ops": [
+ { "op": "update_node_config", "id": "a", "config": { "prompt": "new instruction" } }
+ ]
+ }))
+ .await
+ .unwrap();
+
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ let nodes = parsed["graph"]["nodes"].as_array().unwrap();
+ let agent = nodes.iter().find(|n| n["id"] == "a").unwrap();
+ assert_eq!(agent["config"]["prompt"], "new instruction");
+}
+
+#[tokio::test]
+async fn edit_workflow_requires_a_base() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ let result = tool
+ .execute(json!({ "ops": [ { "op": "remove_node", "id": "a" } ] }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ assert!(result.output().contains("flow_id"));
+}
+
+#[tokio::test]
+async fn edit_workflow_reports_failing_op_with_guidance() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "ops": [ { "op": "remove_node", "id": "ghost" } ]
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ let out = result.output();
+ assert!(out.contains("remove_node"), "{out}");
+ assert!(out.contains("edit_workflow again"), "{out}");
+}
+
+#[tokio::test]
+async fn edit_workflow_bad_op_reports_index_type_and_shape() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ // ops 0 and 1 are well-formed; op 2 is an add_node missing its `node`.
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "ops": [
+ { "op": "set_node_name", "id": "a", "name": "One" },
+ { "op": "set_node_name", "id": "a", "name": "Two" },
+ { "op": "add_node", "id": "b" }
+ ]
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error, "{}", result.output());
+ let out = result.output();
+ // Names the failing op index, its op type, and the expected shape for it.
+ assert!(out.contains("op 2"), "{out}");
+ assert!(out.contains("add_node"), "{out}");
+ assert!(out.contains("node:"), "expected add_node shape in: {out}");
+ assert!(out.contains("edit_workflow again"), "{out}");
+}
+
+#[tokio::test]
+async fn edit_workflow_missing_op_field_lists_valid_types() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "ops": [ { "id": "a", "name": "No op tag" } ]
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error, "{}", result.output());
+ let out = result.output();
+ assert!(out.contains("op 0"), "{out}");
+ assert!(out.contains("missing `op` field"), "{out}");
+ assert!(out.contains("update_node_config"), "{out}");
+}
+
+#[tokio::test]
+async fn edit_workflow_add_node_exists_carries_ordering_hint() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ // Re-adding an existing node id fails in-order; the hint should point at the
+ // remove-first / patch-in-place fix.
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "ops": [
+ { "op": "add_node", "node": { "id": "a", "kind": "merge", "name": "Dup" } }
+ ]
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error, "{}", result.output());
+ let out = result.output();
+ assert!(out.contains("already exists"), "{out}");
+ assert!(out.contains("array order"), "{out}");
+ assert!(out.contains("remove_node"), "{out}");
+ assert!(out.contains("update_node_config"), "{out}");
+}
+
+#[tokio::test]
+async fn edit_workflow_accepts_node_id_aliases_end_to_end() {
+ let tmp = TempDir::new().unwrap();
+ let tool = edit_workflow_tool(test_config(&tmp));
+ // A valid ops array using the `node_id` alias (the natural agent guess)
+ // applies cleanly through edit_workflow.
+ let result = tool
+ .execute(json!({
+ "graph": valid_graph(),
+ "name": "Aliased edit",
+ "ops": [
+ { "op": "update_node_config", "node_id": "a", "config": { "prompt": "aliased" } },
+ { "op": "set_node_name", "node_id": "a", "name": "Aliased step" }
+ ]
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ let parsed: Value = serde_json::from_str(&result.output()).unwrap();
+ assert_eq!(parsed["type"], "workflow_proposal");
+ let nodes = parsed["graph"]["nodes"].as_array().unwrap();
+ let agent = nodes.iter().find(|n| n["id"] == "a").unwrap();
+ assert_eq!(agent["config"]["prompt"], "aliased");
+ assert_eq!(agent["name"], "Aliased step");
+}
diff --git a/crates/openhuman-core/src/flows/builder_tools_tests.rs b/crates/openhuman-core/src/flows/builder_tools_tests.rs
index e69de29bb2..260592c1af 100644
--- a/crates/openhuman-core/src/flows/builder_tools_tests.rs
+++ b/crates/openhuman-core/src/flows/builder_tools_tests.rs
@@ -0,0 +1,187 @@
+use std::sync::Arc;
+
+use super::tests_support::*;
+use super::*;
+use crate::config::Config;
+use crate::flows::ops;
+use serde_json::{Value, json};
+use tempfile::TempDir;
+use tinytools::{PermissionLevel, Tool};
+
+fn test_config(tmp: &TempDir) -> Arc<Config> {
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ Arc::new(config)
+}
+
+fn valid_graph() -> Value {
+ json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Summarize", "config": { "prompt": "hi" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ })
+}
+
+// ── search_tool_catalog / get_tool_contract ─────────────────────────────────
+// The live-catalog cache is process-global (`LIVE_CATALOG_CACHE`) — every
+// test below seeds the exact toolkit(s)/contract(s) it needs via
+// `seed_live_catalog_cache` so none of this touches a live Composio backend,
+// and keeps each toolkit's seeded contents self-consistent across tests that
+// share a toolkit key (same discipline the pre-fix required-args/response-
+// fields caches already required).
+
+use crate::integrations::composio::catalog::{ToolContract, seed_live_catalog_cache};
+
+fn seeded_gmail_send_contract() -> ToolContract {
+ ToolContract {
+ slug: "GMAIL_SEND_EMAIL".to_string(),
+ toolkit: "gmail".to_string(),
+ description: Some("Send an email".to_string()),
+ required_args: vec!["to".to_string(), "body".to_string()],
+ input_schema: Some(json!({ "type": "object", "required": ["to", "body"] })),
+ output_fields: vec!["id".to_string(), "threadId".to_string()],
+ output_schema: Some(json!({
+ "type": "object",
+ "properties": { "id": {"type": "string"}, "threadId": {"type": "string"} }
+ })),
+ primary_array_path: None,
+ is_curated: true,
+ }
+}
+
+/// A minimal seeded contract with NO required args, for WS6 dry-run tests: seeds
+/// a bespoke toolkit so the required-arg preflight always passes and the sandbox
+/// run settles into the `null_resolutions` path (rather than aborting), letting
+/// the test assert the honest Composio-upstream diagnostic deterministically —
+/// independent of whatever gmail/slack contracts other tests seed into the
+/// process-global cache.
+fn seeded_ws6_contract(slug: &str, toolkit: &str) -> ToolContract {
+ ToolContract {
+ slug: slug.to_string(),
+ toolkit: toolkit.to_string(),
+ description: Some("ws6 test action".to_string()),
+ required_args: vec![],
+ input_schema: Some(json!({ "type": "object", "additionalProperties": true })),
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: true,
+ }
+}
+
+// ── WS3: early runtime-gate warnings on uncurated actions ────────────────────
+//
+// Transcript failure #2: `get_tool_contract { slug: "TWITTER_USER_LOOKUP_ME" }`
+// returned `is_curated: false` with no other signal; the agent built and wired
+// the node and only ~15 tool calls later did `validate_workflow` reject it. A
+// real-but-uncurated action of a toolkit that ships a curated catalog is a hard
+// curated-only allowlist at RUNTIME, so surface the blocker at contract-fetch /
+// search time. Uses `spotify` / `telegram` (real curated toolkits unused by
+// other tests) so these seeds can't race with the shared `gmail`/`slack` keys.
+
+// ── WS5: per-token fallback ranking for zero-result multi-word queries ───────
+//
+// Transcript failure: `search_tool_catalog` behaved like near-exact matching —
+// multi-word natural-language queries ("twitter tweet replies lookup") returned
+// `count: 0` even though the toolkit HAS matching actions, so the agent falsely
+// concluded the action didn't exist. The primary pass is a strict case-
+// insensitive AND (every token must match); when that misses for a multi-word
+// query, a per-keyword OR fallback now returns the nearest matches + a note.
+
+// ── save_workflow ────────────────────────────────────────────────────────────
+
+/// Seed a saved flow to write into (the instant-create path does this via
+/// `flows_create` before delegating to the builder).
+async fn seed_flow(config: &Arc<Config>, name: &str) -> String {
+ let outcome = ops::flows_create(
+ config,
+ name.to_string(),
+ json!({
+ "nodes": [ { "id": "t", "kind": "trigger", "name": "Manual" } ],
+ "edges": []
+ }),
+ true,
+ )
+ .await
+ .unwrap();
+ outcome.value.id
+}
+
+/// A single-node graph with an automatic (schedule) trigger — enough to
+/// exercise the manual→automatic transition without tripping any of
+/// `run_builder_gates`' binding/connection/contract checks (no other nodes,
+/// nothing to bind).
+fn schedule_trigger_graph() -> Value {
+ json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger",
+ "config": { "trigger_kind": "schedule", "schedule": "0 8 * * *" } }
+ ],
+ "edges": []
+ })
+}
+
+// ── save_workflow: enforcing binding-resolvability gate ─────────────────────
+
+/// The proven live-failure shape (same as
+/// `tools_tests::propose_workflow_rejects_agent_binding_missing_declared_field`):
+/// a `summarize` agent whose declared output schema omits `channel`, and a
+/// `notify` tool_call binding `args.channel` to that unaddressable output.
+/// A schema-less agent is deliberately accepted by TinyFlows: its host-defined
+/// output may contain structured JSON, so the field is unverifiable rather
+/// than certainly absent.
+fn unresolvable_binding_graph() -> Value {
+ json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "summarize", "kind": "agent", "name": "Summarize",
+ "config": { "agent_ref": "planner", "prompt": "summarize",
+ "output_parser": { "schema": { "type": "object",
+ "properties": { "summary": { "type": "string" } } } } } },
+ { "id": "notify", "kind": "tool_call", "name": "Notify",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "=nodes.summarize.item.json.channel", "text": "A notification" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "summarize" },
+ { "from_node": "summarize", "to_node": "notify" }
+ ]
+ })
+}
+
+// ── cancel_flow_run ownership check (T-M3) ────────────────────────────────
+
+/// A graph that pauses at a `pending_approval` gate, so the run it produces
+/// stays non-terminal (cancellable) — mirrors `ops_tests::approval_gated_graph`.
+fn cancel_test_approval_gated_graph() -> Value {
+ json!({
+ "name": "approval-gated",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "gate", "kind": "output_parser", "name": "Gate", "config": { "requires_approval": true } },
+ { "id": "downstream", "kind": "output_parser", "name": "Downstream" }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "to_node": "downstream" }
+ ]
+ })
+}
+
+#[path = "builder_tools_draft_id_tests.rs"]
+mod draft_id_tests;
+#[path = "builder_tools_dry_run_tests.rs"]
+mod dry_run_tests;
+#[path = "builder_tools_reads_and_catalog_tests.rs"]
+mod reads_and_catalog_tests;
+#[path = "builder_tools_save_and_edit_tests.rs"]
+mod save_and_edit_tests;
+#[path = "builder_tools_validate_and_create_tests.rs"]
+mod validate_and_create_tests;
diff --git a/crates/openhuman-core/src/flows/bus.rs b/crates/openhuman-core/src/flows/bus.rs
index e69de29bb2..ce86a87287 100644
--- a/crates/openhuman-core/src/flows/bus.rs
+++ b/crates/openhuman-core/src/flows/bus.rs
@@ -0,0 +1,48 @@
+//! Event bus handlers for the `flows::` domain (issue B2 — see
+//! `my_docs/ohxtf/b2-triggers-trust/01-triggers-and-trust.md` §1).
+//!
+//! [`FlowTriggerSubscriber`] is the trigger → run bridge: it listens for the
+//! normalized events a saved flow's trigger node can bind to
+//! (`FlowTriggerSubscriber::dispatch_schedule_tick`, `ComposioTriggerReceived`,
+//! `WebhookIncomingRequest`), matches them against enabled flows, and spawns
+//! `flows::ops::flows_run` for each match. Matching helpers
+//! ([`extract_trigger_kind`], [`extract_trigger_config`]) are also reused by
+//! `flows::ops::flows_set_enabled` to bind/unbind a flow's automatic
+//! dispatch on enable/disable.
+
+#[cfg(test)]
+#[path = "bus_tests.rs"]
+mod tests;
+
+mod dedup_commit;
+mod owner;
+mod run_digest;
+mod trigger;
+
+pub use dedup_commit::DedupCommitSubscriber;
+pub use run_digest::FlowRunDigestSubscriber;
+pub use trigger::FlowTriggerSubscriber;
+pub(crate) use trigger::{extract_trigger_config, extract_trigger_kind};
+
+// Private helpers and shared imports the colocated tests reach through
+// `use super::*`.
+#[cfg(test)]
+use crate::config::Config;
+#[cfg(test)]
+use crate::core::events::DomainEvent;
+#[cfg(test)]
+use crate::flows::store;
+#[cfg(test)]
+use dedup_commit::{CommitTestHooks, flow_commit_lock};
+#[cfg(test)]
+use run_digest::{
+ DIGEST_MAX_CHARS, digest_filter, enforce_retention_cap, render_run_digest, truncate_chars,
+};
+#[cfg(test)]
+use serde_json::Value;
+#[cfg(test)]
+use std::sync::Arc;
+#[cfg(test)]
+use tinybus::EventHandler;
+#[cfg(test)]
+use trigger::{matches_app_event, pinned_trigger_inputs};
diff --git a/crates/openhuman-core/src/flows/bus/owner.rs b/crates/openhuman-core/src/flows/bus/owner.rs
index e69de29bb2..91346389c4 100644
--- a/crates/openhuman-core/src/flows/bus/owner.rs
+++ b/crates/openhuman-core/src/flows/bus/owner.rs
@@ -0,0 +1,134 @@
+//! Which agent a flow belongs to, for the subscribers that act on a flow
+//! named only by id (a schedule trigger, `FlowRunFinished`).
+//!
+//! A flow saved from inside an agent's context lives in that agent's storage
+//! scope (`crate::storage`). The subscribers run outside any agent, so they
+//! look the flow up here and handle the event as its owner
+//! (`crate::storage::agents::within_agent`); without a storage backend every
+//! flow is `local` and this is a no-op.
+
+use std::collections::HashMap;
+use std::sync::{LazyLock, Mutex};
+
+use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
+use crate::storage::agents::{LookupFailed, find_owner, within_agent, within_agent_ctx};
+
+/// Flows whose owner this process has resolved (`None` = `local`).
+static OWNERS: LazyLock<Mutex<HashMap<String, Option<String>>>> = LazyLock::new(Default::default);
+
+/// The agent `flow_id` belongs to: `None` for `local`, or when no scope has
+/// the flow (the handler then reports the flow as unknown, as before).
+///
+/// # Errors
+///
+/// When no scope reported the flow and a scope's lookup failed: the event
+/// is then not handled, rather than handled in the wrong scope.
+pub(super) async fn flow_owner(
+ ctx: &DispatchCtx,
+ config: &Config,
+ flow_id: &str,
+) -> Result<Option<String>, LookupFailed> {
+ // No backend: every record is `local`.
+ if crate::storage::installed().is_none() {
+ return Ok(None);
+ }
+ resolve(ctx, config, flow_id).await
+}
+
+/// Whether the current scope has `flow_id`.
+async fn has_flow(config: &Config, flow_id: &str) -> Result<bool, String> {
+ crate::flows::store::get_flow(config, flow_id)
+ .map(|flow| flow.is_some())
+ .map_err(|error| error.to_string())
+}
+
+/// [`flow_owner`]'s cache and lookup, across whatever scopes exist.
+async fn resolve(
+ ctx: &DispatchCtx,
+ config: &Config,
+ flow_id: &str,
+) -> Result<Option<String>, LookupFailed> {
+ let cached = OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(flow_id)
+ .cloned();
+ if let Some(owner) = cached {
+ // Still there? A removed flow's id may be reused, or the flow moved:
+ // re-check the cached scope and resolve again when it lost the flow.
+ match within_agent(ctx, owner.as_deref(), has_flow(config, flow_id)).await {
+ Some(Ok(true)) => return Ok(owner),
+ Some(Err(error)) => {
+ return Err(LookupFailed {
+ agent: owner,
+ error,
+ });
+ }
+ Some(Ok(false)) | None => forget(flow_id),
+ }
+ }
+ let Some(owner) = find_owner(ctx, "flow owner", |_| has_flow(config, flow_id)).await? else {
+ return Ok(None);
+ };
+ tracing::debug!(
+ target: "flows",
+ %flow_id,
+ agent = owner.as_deref().unwrap_or("local"),
+ "[flows] resolved the flow's owner"
+ );
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(flow_id.to_string(), owner.clone());
+ Ok(owner)
+}
+
+/// Runs `step`, handed the owner's context, as `flow_id`'s owner; logs and skips it when the owner is
+/// unknown (a failed lookup) or no context can act for it.
+pub(super) async fn as_owner<F, Fut>(ctx: &DispatchCtx, config: &Config, flow_id: &str, step: F)
+where
+ F: FnOnce(DispatchCtx) -> Fut,
+ Fut: std::future::Future<Output = ()>,
+{
+ match flow_owner(ctx, config, flow_id).await {
+ Ok(owner) => {
+ within_agent_ctx(ctx, owner.as_deref(), step).await;
+ }
+ Err(failed) => tracing::warn!(
+ target: "flows",
+ %flow_id,
+ "[flows] flow owner unknown ({failed}); event not handled"
+ ),
+ }
+}
+
+/// The configuration to handle a flow event under: the acting agent's (or SaaS profile's) own
+/// when the handler runs as one ([`as_owner`]) — its provider, access
+/// policy, memory and action directory — else `registered`, the one the
+/// subscriber was registered with.
+pub(super) fn config_for_scope(
+ ctx: &crate::core::runtime::DispatchCtx,
+ registered: &std::sync::Arc<Config>,
+) -> std::sync::Arc<Config> {
+ // A SaaS profile acts as its own tenant even with no agent inside it.
+ let acting = ctx
+ .tenant()
+ .is_ok_and(|tenant| tenant.agent.is_some() || tenant.profile.is_some());
+ match acting.then(|| ctx.embedder_config()) {
+ Some(Some(config)) => std::sync::Arc::new(config),
+ _ => std::sync::Arc::clone(registered),
+ }
+}
+
+/// Forgets a cached owner (a removed flow's id may be reused).
+pub(super) fn forget(flow_id: &str) {
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(flow_id);
+}
+
+#[cfg(test)]
+#[path = "owner_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index e69de29bb2..03dd7f4abd 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -0,0 +1,694 @@
+//! Trigger → run bridge: [`FlowTriggerSubscriber`] listens for the
+//! normalized events a saved flow's trigger node can bind to and spawns
+//! `flows::ops::flows_run` for each match, plus the trigger-config readers
+//! `flows::ops` reuses to bind/unbind automatic dispatch.
+
+use crate::config::Config;
+use crate::core::events::DomainEvent;
+use crate::flows::store;
+use async_trait::async_trait;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, RwLock};
+use tinybus::EventHandler;
+use tinyflows::model::TriggerKind;
+use tinyflows_catalog::Flow;
+use tokio::sync::{Mutex as AsyncMutex, mpsc};
+
+/// Reads `trigger_kind` from a flow's trigger node config, deserializing into
+/// `tinyflows::model::TriggerKind`. Returns `None` when the flow doesn't have
+/// exactly one trigger node ([`tinyflows::model::WorkflowGraph::trigger`]) or
+/// the `trigger_kind` discriminator is missing/invalid — callers treat that
+/// as "no automatic binding", not an error (a `manual`-only or legacy graph
+/// authored before B2 simply never fires itself).
+pub(crate) fn extract_trigger_kind(flow: &Flow) -> Option<TriggerKind> {
+ let trigger = flow.graph.trigger()?;
+ serde_json::from_value(trigger.config.get("trigger_kind")?.clone()).ok()
+}
+
+/// Returns the trigger node's full config value, for callers that need
+/// kind-specific fields (`schedule` for `schedule`, `toolkit`/`trigger_slug`
+/// for `app_event`, …).
+pub(crate) fn extract_trigger_config(flow: &Flow) -> Option<&Value> {
+ Some(&flow.graph.trigger()?.config)
+}
+
+/// Values an author pinned on the trigger node for *unattended* runs, read from
+/// the trigger's `config.inputs` object.
+///
+/// A schedule tick or an inbound app event has no operator to prompt, so a flow
+/// with declared inputs would otherwise be undispatchable. Pinning values in the
+/// trigger config is how such a flow states, at author time, what an automatic
+/// run should use. Values are passed through literally — this is configuration,
+/// not an expression scope, and there is no run in flight to resolve one
+/// against.
+///
+/// Returns an empty map when the trigger declares none, in which case a required
+/// input with no default fails in `prepare_flow_run` before any run row exists,
+/// and the reason is logged and visible in the run digest.
+pub(super) fn pinned_trigger_inputs(flow: &Flow) -> serde_json::Map<String, Value> {
+ extract_trigger_config(flow)
+ .and_then(|cfg| cfg.get("inputs"))
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default()
+}
+
+/// True when `flow` is an enabled `app_event` flow bound to the given
+/// Composio `toolkit`/`trigger_slug` (case-insensitive — Composio slugs are
+/// conventionally upper-case but authoring surfaces may not normalize them).
+pub(super) fn matches_app_event(flow: &Flow, toolkit: &str, trigger_slug: &str) -> bool {
+ if !matches!(extract_trigger_kind(flow), Some(TriggerKind::AppEvent)) {
+ return false;
+ }
+ let Some(cfg) = extract_trigger_config(flow) else {
+ return false;
+ };
+ let cfg_toolkit = cfg.get("toolkit").and_then(Value::as_str).unwrap_or("");
+ let cfg_slug = cfg
+ .get("trigger_slug")
+ .and_then(Value::as_str)
+ .unwrap_or("");
+ cfg_toolkit.eq_ignore_ascii_case(toolkit) && cfg_slug.eq_ignore_ascii_case(trigger_slug)
+}
+
+/// Listens for normalized trigger events and starts runs for matching
+/// enabled flows. See the module doc for the full contract.
+pub struct FlowTriggerSubscriber {
+ config: Arc<RwLock<Config>>,
+ queues: Arc<Mutex<HashMap<DispatchKey, Arc<FlowRunQueue>>>>,
+ runner: Arc<RunExecutor>,
+ queue_capacity: usize,
+ #[cfg(test)]
+ retiring: Arc<tokio::sync::Notify>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct DispatchKey {
+ tenant: crate::core::runtime::Tenant,
+ flow_id: String,
+}
+
+struct FlowRunQueue {
+ sender: mpsc::Sender<QueuedRun>,
+ receiver: Mutex<Option<mpsc::Receiver<QueuedRun>>>,
+ worker_started: std::sync::atomic::AtomicBool,
+ admission: Arc<AsyncMutex<()>>,
+ outstanding: AtomicUsize,
+}
+
+struct QueuedRun {
+ ctx: crate::core::runtime::DispatchCtx,
+ config: Arc<Config>,
+ request: TriggerRunRequest,
+}
+
+struct QueueOutstanding {
+ queue: Arc<FlowRunQueue>,
+ armed: bool,
+}
+
+impl QueueOutstanding {
+ fn new(queue: Arc<FlowRunQueue>) -> Self {
+ queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ Self { queue, armed: true }
+ }
+
+ fn transfer_to_worker(mut self) {
+ self.armed = false;
+ }
+}
+
+impl Drop for QueueOutstanding {
+ fn drop(&mut self) {
+ if self.armed {
+ self.queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ }
+ }
+}
+
+pub(crate) struct TriggerRunRequest {
+ pub(crate) flow_id: String,
+ pub(crate) input: Value,
+ pub(crate) inputs: serde_json::Map<String, Value>,
+ pub(crate) trigger: tinyflows_catalog::FlowRunTrigger,
+}
+
+type RunFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
+type RunExecutor = dyn Fn(crate::core::runtime::DispatchCtx, Arc<Config>, TriggerRunRequest) -> RunFuture
+ + Send
+ + Sync;
+
+const APP_EVENT_QUEUE_CAPACITY: usize = 32;
+
+impl FlowTriggerSubscriber {
+ pub fn new(config: Arc<Config>) -> Self {
+ Self::with_config_source(Arc::new(RwLock::new((*config).clone())))
+ }
+
+ pub(crate) fn with_config_source(config: Arc<RwLock<Config>>) -> Self {
+ Self::with_executor(
+ config,
+ APP_EVENT_QUEUE_CAPACITY,
+ |ctx, config, request| async move {
+ let flow_id = request.flow_id.clone();
+ tracing::info!(target: "flows", %flow_id, "[flows] trigger fired — starting run");
+ match crate::flows::ops::flows_run(
+ &ctx,
+ &config,
+ &flow_id,
+ request.input,
+ request.inputs,
+ request.trigger,
+ )
+ .await
+ {
+ Ok(_) => {
+ tracing::info!(target: "flows", %flow_id, "[flows] trigger-driven run finished")
+ }
+ Err(e) => {
+ tracing::warn!(target: "flows", %flow_id, error = %e, "[flows] trigger-driven run failed")
+ }
+ }
+ },
+ )
+ }
+
+ fn with_executor<F, Fut>(config: Arc<RwLock<Config>>, queue_capacity: usize, runner: F) -> Self
+ where
+ F: Fn(crate::core::runtime::DispatchCtx, Arc<Config>, TriggerRunRequest) -> Fut
+ + Send
+ + Sync
+ + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ let runner: Arc<RunExecutor> =
+ Arc::new(move |ctx, config, request| Box::pin(runner(ctx, config, request)));
+ Self {
+ config,
+ queues: Arc::new(Mutex::new(HashMap::new())),
+ runner,
+ queue_capacity: queue_capacity.max(1),
+ #[cfg(test)]
+ retiring: Arc::new(tokio::sync::Notify::new()),
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_runner<F, Fut>(config: Arc<Config>, queue_capacity: usize, runner: F) -> Self
+ where
+ F: Fn(crate::core::runtime::DispatchCtx, Arc<Config>, TriggerRunRequest) -> Fut
+ + Send
+ + Sync
+ + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ Self::with_executor(
+ Arc::new(RwLock::new((*config).clone())),
+ queue_capacity,
+ runner,
+ )
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_runner_and_config_source<F, Fut>(
+ config: Arc<RwLock<Config>>,
+ queue_capacity: usize,
+ runner: F,
+ ) -> Self
+ where
+ F: Fn(crate::core::runtime::DispatchCtx, Arc<Config>, TriggerRunRequest) -> Fut
+ + Send
+ + Sync
+ + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ Self::with_executor(config, queue_capacity, runner)
+ }
+
+ async fn dispatch_app_event(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: String,
+ payload: Value,
+ inputs: serde_json::Map<String, Value>,
+ ) {
+ // Admission intentionally waits for bounded per-key queue capacity.
+ // EventHandler runs inline in TinyBus, so a saturated key can delay
+ // later scopes in this callback. This is in-memory backpressure, not
+ // durable delivery; the upstream event broadcast is itself bounded.
+ let Some(key) = self.dispatch_key(ctx, &flow_id) else {
+ return;
+ };
+ let queued = QueuedRun {
+ ctx: ctx.clone(),
+ config: self.config_for_scope(ctx),
+ request: TriggerRunRequest {
+ flow_id,
+ input: payload,
+ inputs,
+ trigger: tinyflows_catalog::FlowRunTrigger::AppEvent,
+ },
+ };
+ self.enqueue_app_event(key, ctx, queued).await;
+ }
+
+ #[cfg(test)]
+ pub(crate) async fn dispatch_test_app_event(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ payload: Value,
+ ) {
+ self.dispatch_app_event(ctx, flow_id.to_string(), payload, serde_json::Map::new())
+ .await;
+ }
+
+ fn dispatch_key(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) -> Option<DispatchKey> {
+ match ctx.tenant() {
+ Ok(tenant) => Some(DispatchKey {
+ tenant,
+ flow_id: flow_id.to_string(),
+ }),
+ Err(error) => {
+ tracing::warn!(target: "flows", %flow_id, error = %error, "[flows] trigger dispatch has no tenant scope; refusing to use the host config");
+ None
+ }
+ }
+ }
+
+ fn queue_for(&self, key: &DispatchKey) -> Arc<FlowRunQueue> {
+ let mut queues = self
+ .queues
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ if let Some(queue) = queues.get(key).filter(|queue| !queue.sender.is_closed()) {
+ return Arc::clone(queue);
+ }
+
+ let (sender, receiver) = mpsc::channel(self.queue_capacity);
+ let queue = Arc::new(FlowRunQueue {
+ sender,
+ receiver: Mutex::new(Some(receiver)),
+ worker_started: std::sync::atomic::AtomicBool::new(false),
+ admission: Arc::new(AsyncMutex::new(())),
+ outstanding: AtomicUsize::new(0),
+ });
+ queues.insert(key.clone(), Arc::clone(&queue));
+ queue
+ }
+
+ fn start_worker_if_needed(
+ &self,
+ key: &DispatchKey,
+ queue: &Arc<FlowRunQueue>,
+ ctx: &crate::core::runtime::DispatchCtx,
+ ) {
+ if queue
+ .worker_started
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return;
+ }
+ let Some(receiver) = queue
+ .receiver
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .take()
+ else {
+ return;
+ };
+ let worker_key = key.clone();
+ let worker_queue = Arc::clone(queue);
+ let worker_queues = Arc::clone(&self.queues);
+ let runner = Arc::clone(&self.runner);
+ #[cfg(test)]
+ let retiring = Arc::clone(&self.retiring);
+ ctx.spawn(async move {
+ run_queue_worker(
+ worker_key,
+ worker_queue,
+ receiver,
+ worker_queues,
+ runner,
+ #[cfg(test)]
+ retiring,
+ )
+ .await;
+ });
+ }
+
+ async fn enqueue_app_event(
+ &self,
+ key: DispatchKey,
+ ctx: &crate::core::runtime::DispatchCtx,
+ mut queued: QueuedRun,
+ ) {
+ loop {
+ let queue = self.queue_for(&key);
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ if queue.sender.is_closed() {
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ continue;
+ }
+
+ let outstanding = QueueOutstanding::new(Arc::clone(&queue));
+ match queue.sender.send(queued).await {
+ Ok(()) => {
+ outstanding.transfer_to_worker();
+ drop(admission);
+ self.start_worker_if_needed(&key, &queue, ctx);
+ return;
+ }
+ Err(error) => {
+ queued = error.0;
+ drop(outstanding);
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ }
+ }
+ }
+ }
+
+ async fn enqueue_schedule(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: String,
+ inputs: serde_json::Map<String, Value>,
+ ) {
+ let Some(key) = self.dispatch_key(ctx, &flow_id) else {
+ return;
+ };
+ let queued = QueuedRun {
+ ctx: ctx.clone(),
+ config: self.config_for_scope(ctx),
+ request: TriggerRunRequest {
+ flow_id: flow_id.clone(),
+ input: Value::Null,
+ inputs,
+ trigger: tinyflows_catalog::FlowRunTrigger::Schedule,
+ },
+ };
+ self.enqueue_schedule_request(key, ctx, queued).await;
+ }
+
+ async fn enqueue_schedule_request(
+ &self,
+ key: DispatchKey,
+ ctx: &crate::core::runtime::DispatchCtx,
+ mut queued: QueuedRun,
+ ) {
+ loop {
+ let queue = self.queue_for(&key);
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ if queue.sender.is_closed() {
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ continue;
+ }
+ if queue.outstanding.load(Ordering::Acquire) != 0 {
+ tracing::debug!(target: "flows", flow_id = %key.flow_id, "[flows] schedule tick coalesced while a trigger run is queued or active");
+ return;
+ }
+
+ queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ match queue.sender.try_send(queued) {
+ Ok(()) => {
+ drop(admission);
+ self.start_worker_if_needed(&key, &queue, ctx);
+ return;
+ }
+ Err(mpsc::error::TrySendError::Full(_)) => {
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ tracing::debug!(target: "flows", flow_id = %key.flow_id, "[flows] schedule tick coalesced while a trigger run is queued");
+ return;
+ }
+ Err(mpsc::error::TrySendError::Closed(returned)) => {
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ // Keep the value available if the retiring worker won
+ // the race with this schedule tick.
+ queued = returned;
+ }
+ }
+ }
+ }
+
+ fn remove_queue_if_current(&self, key: &DispatchKey, queue: &Arc<FlowRunQueue>) {
+ let mut queues = self
+ .queues
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ if queues
+ .get(key)
+ .is_some_and(|current| Arc::ptr_eq(current, queue))
+ {
+ queues.remove(key);
+ }
+ }
+
+ /// The configuration to handle an event under (`super::owner::config_for_scope`).
+ pub(super) fn config_for_scope(&self, ctx: &crate::core::runtime::DispatchCtx) -> Arc<Config> {
+ let config = Arc::new(
+ self.config
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone(),
+ );
+ super::owner::config_for_scope(ctx, &config)
+ }
+
+ /// A `flow`-type cron job fired (`cron::scheduler`'s trigger sink calls
+ /// this directly). Runs as the agent the flow belongs to
+ /// (`super::owner`), then loads the one named flow, checks it is still
+ /// enabled with a `schedule` trigger (it may have been disabled/edited
+ /// since the job was registered), and dispatches it with an empty trigger
+ /// payload.
+ pub(crate) async fn dispatch_schedule_tick(
+ &self,
+ host: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) {
+ let config = self.config_for_scope(host);
+ super::owner::as_owner(host, &config, flow_id, |ctx| {
+ self.handle_schedule_tick(ctx, flow_id)
+ })
+ .await
+ }
+
+ async fn handle_schedule_tick(&self, ctx: crate::core::runtime::DispatchCtx, flow_id: &str) {
+ let config = self.config_for_scope(&ctx);
+ let flow = match store::get_flow(&config, flow_id) {
+ Ok(Some(flow)) => flow,
+ Ok(None) => {
+ tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick for unknown/removed flow — ignoring");
+ return;
+ }
+ Err(e) => {
+ tracing::warn!(target: "flows", %flow_id, error = %e, "[flows] failed to load flow for schedule tick");
+ return;
+ }
+ };
+ if !flow.enabled {
+ tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick for disabled flow — ignoring");
+ return;
+ }
+ if !matches!(extract_trigger_kind(&flow), Some(TriggerKind::Schedule)) {
+ tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick for flow whose trigger is no longer `schedule` — ignoring");
+ return;
+ }
+ let inputs = pinned_trigger_inputs(&flow);
+ self.enqueue_schedule(&ctx, flow_id.to_string(), inputs)
+ .await;
+ }
+
+ /// `DomainEvent::ComposioTriggerReceived` — scans every enabled flow for
+ /// an `app_event` trigger bound to this `toolkit`/`trigger_slug` and
+ /// dispatches each match with the event payload as the run input
+ /// (seeded into `run.trigger`, per the node-catalog contract).
+ async fn handle_app_event(
+ &self,
+ ctx: crate::core::runtime::DispatchCtx,
+ toolkit: &str,
+ trigger_slug: &str,
+ payload: &Value,
+ ) {
+ let config = self.config_for_scope(&ctx);
+ let (flows, skipped) = match store::list_enabled_flows(&config) {
+ Ok(result) => result,
+ Err(e) => {
+ tracing::warn!(target: "flows", %toolkit, %trigger_slug, error = %e, "[flows] failed to list enabled flows for app_event dispatch");
+ return;
+ }
+ };
+ if skipped > 0 {
+ // R-M4: one corrupt/unmigratable flow row must not blackhole
+ // app_event dispatch for every other enabled flow.
+ tracing::warn!(target: "flows", %toolkit, %trigger_slug, skipped, "[flows] handle_app_event: skipped corrupt/unmigratable flow rows while matching trigger");
+ }
+
+ let mut matched = 0usize;
+ for flow in flows {
+ if matches_app_event(&flow, toolkit, trigger_slug) {
+ matched += 1;
+ let inputs = pinned_trigger_inputs(&flow);
+ self.dispatch_app_event(&ctx, flow.id.clone(), payload.clone(), inputs)
+ .await;
+ }
+ }
+ tracing::debug!(target: "flows", %toolkit, %trigger_slug, matched, "[flows] app_event trigger matching complete");
+ }
+
+ #[cfg(test)]
+ pub(crate) async fn dispatch_test_schedule(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) {
+ self.enqueue_schedule(ctx, flow_id.to_string(), serde_json::Map::new())
+ .await;
+ }
+
+ #[cfg(test)]
+ pub(crate) async fn hold_queue_admission_test(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) -> tokio::sync::OwnedMutexGuard<()> {
+ let key = self.dispatch_key(ctx, flow_id).unwrap();
+ let queue = self.queue_for(&key);
+ Arc::clone(&queue.admission).lock_owned().await
+ }
+
+ #[cfg(test)]
+ pub(crate) fn retirement_notifier_test(&self) -> Arc<tokio::sync::Notify> {
+ Arc::clone(&self.retiring)
+ }
+}
+
+async fn run_queue_worker(
+ key: DispatchKey,
+ queue: Arc<FlowRunQueue>,
+ mut receiver: mpsc::Receiver<QueuedRun>,
+ queues: Arc<Mutex<HashMap<DispatchKey, Arc<FlowRunQueue>>>>,
+ runner: Arc<RunExecutor>,
+ #[cfg(test)] retiring: Arc<tokio::sync::Notify>,
+) {
+ let mut next = receiver.recv().await;
+ loop {
+ let Some(queued) = next.take() else {
+ break;
+ };
+ let run_ctx = queued.ctx.clone();
+ let flow_id = queued.request.flow_id.clone();
+ let run = run_ctx.spawn((runner)(queued.ctx, queued.config, queued.request));
+ if let Err(error) = run.await {
+ tracing::warn!(target: "flows", %flow_id, error = %error, "[flows] trigger run task exited unexpectedly");
+ }
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+
+ if let Ok(queued) = receiver.try_recv() {
+ next = Some(queued);
+ continue;
+ }
+
+ // A producer takes the same gate before sending. Once this worker
+ // holds it and observes an empty receiver, no successful send can be
+ // stranded behind a closed receiver. A sender that cloned this slot
+ // before retirement gets SendError and retries with the new slot.
+ #[cfg(test)]
+ retiring.notify_one();
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ match receiver.try_recv() {
+ Ok(queued) => {
+ drop(admission);
+ next = Some(queued);
+ }
+ Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected) => {
+ receiver.close();
+ let mut current = queues.lock().unwrap_or_else(|error| error.into_inner());
+ if current
+ .get(&key)
+ .is_some_and(|entry| Arc::ptr_eq(entry, &queue))
+ {
+ current.remove(&key);
+ }
+ return;
+ }
+ }
+ }
+
+ let mut current = queues.lock().unwrap_or_else(|error| error.into_inner());
+ if current
+ .get(&key)
+ .is_some_and(|entry| Arc::ptr_eq(entry, &queue))
+ {
+ current.remove(&key);
+ }
+}
+
+#[async_trait]
+impl EventHandler<DomainEvent> for FlowTriggerSubscriber {
+ fn name(&self) -> &str {
+ "flows::trigger"
+ }
+
+ fn domains(&self) -> Option<&[&str]> {
+ Some(&["cron", "composio", "webhook", "system"])
+ }
+
+ async fn handle(&self, event: &DomainEvent) {
+ // Trigger events arrive over the host's socket or its own scheduler:
+ // the host's own tenant, and in SaaS none.
+ let host = crate::core::runtime::DispatchCtx::host_default();
+ match event {
+ // Every scope's flows may listen for this trigger: match them in
+ // each, so each run starts as its flow's owner.
+ DomainEvent::ComposioTriggerReceived {
+ toolkit,
+ trigger,
+ payload,
+ ..
+ } => {
+ crate::storage::agents::for_each_live_scope(&host, "flows app_event", |ctx| {
+ self.handle_app_event(ctx, toolkit, trigger, payload)
+ })
+ .await;
+ }
+ DomainEvent::WebhookIncomingRequest { .. } => {
+ // Best-effort deviation (documented, not silently skipped —
+ // see `flows::ops::log_webhook_trigger_deferred` for the
+ // enable/disable-side note): a `webhook`-trigger flow needs a
+ // backend-provisioned tunnel + a UI surface for the resulting
+ // URL, neither of which exists yet. Never log the request's
+ // `raw_data` here — it is untrusted, possibly-sensitive
+ // inbound payload.
+ tracing::debug!(
+ target: "flows",
+ "[flows] observed WebhookIncomingRequest — webhook-trigger dispatch is not \
+ implemented in B2 (pending backend tunnel provisioning + B3 UI); no flow \
+ dispatched"
+ );
+ }
+ other => {
+ // Anything else on our filtered domains (plain shell/agent
+ // `CronJobTriggered`, other Composio lifecycle events,
+ // system lifecycle, …) is not a flow trigger — ignore. Log
+ // only the variant name, never the event's Debug form: some
+ // sibling variants on these domains carry payloads we must
+ // not put in logs (e.g. `ComposioTriggerReceived::payload`).
+ tracing::trace!(target: "flows", variant = other.variant_name(), "[flows] ignoring unrelated event");
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
index e69de29bb2..98706c70da 100644
--- a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
@@ -0,0 +1,663 @@
+use super::*;
+use tinyflows::model::TriggerKind;
+use tinyflows_catalog::types::FlowRun;
+
+#[test]
+fn pinned_trigger_inputs_reads_values_an_author_fixed_for_unattended_runs() {
+ let flow = flow_with_trigger_config(
+ "f1",
+ true,
+ json!({
+ "trigger_kind": "schedule",
+ "schedule": "0 9 * * *",
+ "inputs": { "repo": "acme/api", "depth": 3 }
+ }),
+ );
+ let inputs = pinned_trigger_inputs(&flow);
+ assert_eq!(inputs["repo"], json!("acme/api"));
+ assert_eq!(inputs["depth"], json!(3));
+}
+
+#[test]
+fn pinned_trigger_inputs_is_empty_when_unset_or_malformed() {
+ // Empty, not an error: a flow declaring no inputs (the overwhelming
+ // majority) must keep dispatching on a tick exactly as before, and a
+ // malformed value is caught downstream by `prepare_flow_run`, which
+ // reports it against the flow's actual declarations.
+ for cfg in [
+ json!({ "trigger_kind": "schedule" }),
+ json!({ "trigger_kind": "schedule", "inputs": null }),
+ json!({ "trigger_kind": "schedule", "inputs": ["repo"] }),
+ ] {
+ let flow = flow_with_trigger_config("f1", true, cfg.clone());
+ assert!(
+ pinned_trigger_inputs(&flow).is_empty(),
+ "expected no pinned inputs for {cfg}"
+ );
+ }
+}
+
+#[test]
+fn pinned_trigger_inputs_is_empty_for_a_graph_with_no_trigger() {
+ let mut flow = flow_with_trigger_config("f1", true, json!({ "trigger_kind": "schedule" }));
+ flow.graph.nodes.clear();
+ assert!(pinned_trigger_inputs(&flow).is_empty());
+}
+
+#[test]
+fn name_and_domains_are_stable() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = FlowTriggerSubscriber::new(test_config(&tmp));
+ assert_eq!(sub.name(), "flows::trigger");
+ assert_eq!(
+ sub.domains(),
+ Some(&["cron", "composio", "webhook", "system"][..])
+ );
+}
+
+#[tokio::test]
+async fn handle_does_not_panic_on_arbitrary_events() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = FlowTriggerSubscriber::new(test_config(&tmp));
+ sub.handle(&DomainEvent::CronJobTriggered {
+ job_id: "j1".into(),
+ job_name: "test".into(),
+ job_type: "shell".into(),
+ })
+ .await;
+ sub.dispatch_schedule_tick(
+ &crate::core::runtime::DispatchCtx::host_default(),
+ "missing-flow",
+ )
+ .await;
+}
+
+#[test]
+fn extract_trigger_kind_reads_schedule() {
+ let flow = flow_with_trigger_config(
+ "f1",
+ true,
+ json!({ "trigger_kind": "schedule", "schedule": "0 9 * * *" }),
+ );
+ assert!(matches!(
+ extract_trigger_kind(&flow),
+ Some(TriggerKind::Schedule)
+ ));
+}
+
+#[test]
+fn extract_trigger_kind_none_for_missing_discriminator() {
+ let flow = flow_with_trigger_config("f1", true, json!({}));
+ assert!(extract_trigger_kind(&flow).is_none());
+}
+
+#[test]
+fn extract_trigger_kind_none_for_invalid_discriminator() {
+ let flow = flow_with_trigger_config("f1", true, json!({ "trigger_kind": "not_a_kind" }));
+ assert!(extract_trigger_kind(&flow).is_none());
+}
+
+#[test]
+fn matches_app_event_requires_toolkit_and_slug_match() {
+ let flow = flow_with_trigger_config(
+ "f1",
+ true,
+ json!({ "trigger_kind": "app_event", "toolkit": "gmail", "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE" }),
+ );
+ assert!(matches_app_event(&flow, "gmail", "GMAIL_NEW_GMAIL_MESSAGE"));
+ // Case-insensitive.
+ assert!(matches_app_event(&flow, "Gmail", "gmail_new_gmail_message"));
+ // Wrong toolkit or slug does not match.
+ assert!(!matches_app_event(
+ &flow,
+ "slack",
+ "GMAIL_NEW_GMAIL_MESSAGE"
+ ));
+ assert!(!matches_app_event(&flow, "gmail", "SLACK_NEW_MESSAGE"));
+}
+
+#[test]
+fn matches_app_event_false_for_non_app_event_trigger() {
+ let flow = flow_with_trigger_config(
+ "f1",
+ true,
+ json!({ "trigger_kind": "schedule", "schedule": "0 9 * * *" }),
+ );
+ assert!(!matches_app_event(
+ &flow,
+ "gmail",
+ "GMAIL_NEW_GMAIL_MESSAGE"
+ ));
+}
+
+#[tokio::test]
+async fn handle_app_event_ignores_disabled_flows() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_trigger_config(
+ "disabled-flow",
+ false,
+ json!({ "trigger_kind": "app_event", "toolkit": "gmail", "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE" }),
+ );
+ crate::flows::store::upsert_flow(&config, &flow).unwrap();
+
+ // `list_enabled_flows` must not surface the disabled flow at all —
+ // proves the subscriber's dispatch source already excludes it,
+ // rather than asserting on a spawned background task's side effect.
+ let (enabled, skipped) = crate::flows::store::list_enabled_flows(&config).unwrap();
+ assert!(enabled.is_empty());
+ assert_eq!(skipped, 0);
+}
+
+#[tokio::test]
+async fn handle_schedule_tick_ignores_disabled_flow() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_trigger_config(
+ "sched-flow",
+ false,
+ json!({ "trigger_kind": "schedule", "schedule": "0 9 * * *" }),
+ );
+ crate::flows::store::upsert_flow(&config, &flow).unwrap();
+
+ let sub = FlowTriggerSubscriber::new(config.clone());
+ // Must not panic and must not spawn a run for a disabled flow — we
+ // can't directly observe "no run happened" without a full flows_run
+ // fixture, but this exercises the early-return path without error.
+ sub.dispatch_schedule_tick(
+ &crate::core::runtime::DispatchCtx::host_default(),
+ "sched-flow",
+ )
+ .await;
+}
+
+// ── FlowRunDigestSubscriber ─────────────────────────────────────
+
+#[test]
+fn digest_name_and_domains_are_stable() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = FlowRunDigestSubscriber::new(test_config(&tmp));
+ assert_eq!(sub.name(), "flows::digest");
+ assert_eq!(sub.domains(), Some(&["cron"][..]));
+}
+
+#[tokio::test]
+async fn digest_handle_does_not_panic_on_unrelated_events() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = FlowRunDigestSubscriber::new(test_config(&tmp));
+ // Must not panic, and must not touch the memory layer at all, for
+ // any event other than `FlowRunFinished`.
+ sub.handle(&DomainEvent::CronJobTriggered {
+ job_id: "j1".into(),
+ job_name: "test".into(),
+ job_type: "shell".into(),
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn digest_ignores_failed_run() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _engine = digest_test_engine(&config);
+
+ let flow = flow_with_trigger_config("f-failed", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+ store::insert_flow_run(
+ &config,
+ "run-failed",
+ "f-failed",
+ "thread-failed",
+ "2026-01-01T00:00:00Z",
+ )
+ .unwrap();
+ store::finish_flow_run(
+ &config,
+ "run-failed",
+ "failed",
+ "2026-01-01T00:05:00Z",
+ &[],
+ &[],
+ Some("boom"),
+ None,
+ )
+ .unwrap();
+
+ let sub = FlowRunDigestSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-failed".into(),
+ run_id: "run-failed".into(),
+ status: "failed".into(),
+ })
+ .await;
+
+ assert!(
+ stored_digests(&config, "f-failed").await.is_empty(),
+ "a failed run must never produce a run digest"
+ );
+}
+
+#[tokio::test]
+async fn digest_ignores_cancelled_run() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _engine = digest_test_engine(&config);
+
+ let flow = flow_with_trigger_config("f-cancelled", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+ store::insert_flow_run(
+ &config,
+ "run-cancelled",
+ "f-cancelled",
+ "thread-cancelled",
+ "2026-01-01T00:00:00Z",
+ )
+ .unwrap();
+ store::finish_flow_run(
+ &config,
+ "run-cancelled",
+ "cancelled",
+ "2026-01-01T00:05:00Z",
+ &[],
+ &[],
+ None,
+ None,
+ )
+ .unwrap();
+
+ let sub = FlowRunDigestSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-cancelled".into(),
+ run_id: "run-cancelled".into(),
+ status: "cancelled".into(),
+ })
+ .await;
+
+ assert!(stored_digests(&config, "f-cancelled").await.is_empty());
+}
+
+#[tokio::test]
+async fn digest_sanitizes_persisted_outputs() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _engine = digest_test_engine(&config);
+
+ let flow = flow_with_trigger_config("f-ok", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+ store::insert_flow_run(
+ &config,
+ "run-ok",
+ "f-ok",
+ "thread-ok",
+ "2026-01-01T00:00:00Z",
+ )
+ .unwrap();
+ let step = tinyflows_catalog::FlowRunStep {
+ node_id: "n1".to_string(),
+ output: json!({
+ "sent": 3,
+ "access_token": format!("synthetic-credential-value{}", "x".repeat(140)),
+ }),
+ port: None,
+ status: Some("success".to_string()),
+ duration_ms: Some(12),
+ diagnostics: Vec::new(),
+ };
+ // Generated synthetic fixture data exercises text-token scrubbing; it is
+ // deterministic test input and never a real credential.
+ let token_output = format!("sk-ant-api03-{}", "0123456789abcdef".repeat(3));
+ let string_step = tinyflows_catalog::FlowRunStep {
+ node_id: "n2".to_string(),
+ output: json!(token_output.clone()),
+ port: None,
+ status: Some("success".to_string()),
+ duration_ms: Some(8),
+ diagnostics: Vec::new(),
+ };
+ store::finish_flow_run(
+ &config,
+ "run-ok",
+ "completed",
+ "2026-01-01T00:05:00Z",
+ &[step, string_step],
+ &[],
+ None,
+ None,
+ )
+ .unwrap();
+
+ let sub = FlowRunDigestSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-ok".into(),
+ run_id: "run-ok".into(),
+ status: "completed".into(),
+ })
+ .await;
+
+ let digests = stored_digests(&config, "f-ok").await;
+ assert_eq!(
+ digests.len(),
+ 1,
+ "completed run must produce one run digest"
+ );
+ let entry = &digests[0];
+ assert_eq!(entry.meta.source.kind, tinymemory_api::SourceKind::Agent);
+ assert!(entry.meta.tags.contains(&crate::flows::flow_tag("f-ok")));
+ assert_eq!(
+ entry.meta.derive,
+ Some(false),
+ "nothing derived from a digest"
+ );
+ assert!(entry.text.contains("f-ok"));
+ assert!(entry.text.contains("completed"));
+ assert!(entry.text.contains("n1"));
+ assert!(entry.text.contains("\"sent\":3"));
+ assert!(!entry.text.contains("synthetic-credential-value"));
+ assert!(entry.text.contains("[REDACTED_SECRET]"));
+ assert!(!entry.text.contains(&token_output));
+ assert!(entry.text.contains("n2"));
+ assert!(entry.text.chars().count() <= DIGEST_MAX_CHARS);
+}
+
+#[tokio::test]
+async fn digest_treats_completed_with_warnings_as_success() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _engine = digest_test_engine(&config);
+
+ let flow = flow_with_trigger_config("f-warn", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+ store::insert_flow_run(
+ &config,
+ "run-warn",
+ "f-warn",
+ "thread-warn",
+ "2026-01-01T00:00:00Z",
+ )
+ .unwrap();
+ store::finish_flow_run(
+ &config,
+ "run-warn",
+ "completed_with_warnings",
+ "2026-01-01T00:05:00Z",
+ &[],
+ &[],
+ None,
+ None,
+ )
+ .unwrap();
+
+ let sub = FlowRunDigestSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-warn".into(),
+ run_id: "run-warn".into(),
+ status: "completed_with_warnings".into(),
+ })
+ .await;
+
+ assert_eq!(stored_digests(&config, "f-warn").await.len(), 1);
+}
+
+#[tokio::test]
+async fn digest_is_skipped_quietly_when_memory_is_off() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let mut config = (*test_config(&tmp)).clone();
+ config.memory.engine = String::new();
+ let config = Arc::new(config);
+ let flow = flow_with_trigger_config("f-off", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+ // No run row exists: with memory off the subscriber must return before
+ // even loading it, so this completes without a warning path.
+ FlowRunDigestSubscriber::new(config)
+ .handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-off".into(),
+ run_id: "missing".into(),
+ status: "completed".into(),
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn retention_cap_forgets_the_oldest_digests() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _engine = digest_test_engine(&config);
+ let base = chrono::Utc::now();
+ for i in 0..4_i64 {
+ let mut meta = crate::flows::flow_meta("f-cap", &["flow_run_digest".to_string()]);
+ meta.observed_at = Some(base + chrono::Duration::seconds(i));
+ crate::memory::ops::store_item(
+ &config,
+ tinymemory_api::StoreItem::document(format!("digest {i}"), meta),
+ )
+ .await
+ .unwrap();
+ }
+ assert_eq!(enforce_retention_cap(&config, "f-cap", 2).await.unwrap(), 2);
+ let kept = stored_digests(&config, "f-cap").await;
+ assert_eq!(kept.len(), 2);
+ assert!(
+ kept.iter()
+ .all(|hit| hit.text.contains("digest 2") || hit.text.contains("digest 3"))
+ );
+}
+
+#[test]
+fn truncate_chars_bounds_output_and_marks_truncation() {
+ let long = "x".repeat(50);
+ let truncated = truncate_chars(&long, 10);
+ assert_eq!(truncated.chars().count(), 10);
+ assert!(truncated.ends_with('…'));
+
+ let short = "hello";
+ assert_eq!(truncate_chars(short, 10), "hello");
+}
+
+#[test]
+fn render_run_digest_is_bounded_and_includes_key_fields() {
+ let run = FlowRun {
+ id: "run-1".to_string(),
+ flow_id: "f1".to_string(),
+ thread_id: "thread-1".to_string(),
+ status: "completed".to_string(),
+ started_at: "2026-01-01T00:00:00Z".to_string(),
+ finished_at: Some("2026-01-01T00:05:00Z".to_string()),
+ steps: vec![tinyflows_catalog::FlowRunStep {
+ node_id: "n1".to_string(),
+ output: json!({ "ok": true }),
+ port: None,
+ status: Some("success".to_string()),
+ duration_ms: Some(5),
+ diagnostics: Vec::new(),
+ }],
+ pending_approvals: Vec::new(),
+ error: None,
+ graph_hash: None,
+ };
+ let digest = render_run_digest("My Flow", &run);
+ assert!(digest.contains("My Flow"));
+ assert!(digest.contains("completed"));
+ assert!(digest.contains("n1"));
+ assert!(digest.chars().count() <= DIGEST_MAX_CHARS);
+}
+
+#[test]
+fn dedup_commit_name_and_domains_are_stable() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = DedupCommitSubscriber::new(test_config(&tmp));
+ assert_eq!(sub.name(), "flows::dedup_commit");
+ assert_eq!(sub.domains(), Some(&["cron"][..]));
+}
+
+#[tokio::test]
+async fn dedup_commit_ignores_unrelated_events() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let sub = DedupCommitSubscriber::new(test_config(&tmp));
+ // Must not panic for any event other than `FlowRunFinished`.
+ sub.handle(&DomainEvent::CronJobTriggered {
+ job_id: "j1".into(),
+ job_name: "test".into(),
+ job_type: "shell".into(),
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn dedup_commit_flow_with_no_dedup_nodes_is_a_noop() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_trigger_config("f-no-dedup", true, json!({}));
+ store::upsert_flow(&config, &flow).unwrap();
+
+ let sub = DedupCommitSubscriber::new(config);
+ // Must not panic when the flow has no `dedup` node at all.
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-no-dedup".into(),
+ run_id: "run-1".into(),
+ status: "completed".into(),
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn dedup_commit_unions_tentative_into_committed_and_clears_tentative_on_success() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_dedup_node("f-ok", "dd");
+ store::upsert_flow(&config, &flow).unwrap();
+
+ let namespace = dedup_state_namespace("f-ok");
+ store::kv_set(&config, &namespace, "dedup:dd:committed", &json!(["a"])).unwrap();
+ store::kv_set(
+ &config,
+ &namespace,
+ "dedup:dd:tentative",
+ &json!(["b", "c"]),
+ )
+ .unwrap();
+
+ let sub = DedupCommitSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-ok".into(),
+ run_id: "run-ok".into(),
+ status: "completed".into(),
+ })
+ .await;
+
+ let committed = store::kv_get(&config, &namespace, "dedup:dd:committed")
+ .unwrap()
+ .expect("committed key must still exist");
+ let mut committed: Vec<&str> = committed
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_str().unwrap())
+ .collect();
+ committed.sort_unstable();
+ assert_eq!(committed, vec!["a", "b", "c"], "committed = union");
+
+ assert!(
+ store::kv_get(&config, &namespace, "dedup:dd:tentative")
+ .unwrap()
+ .is_none(),
+ "tentative must be cleared after a successful commit"
+ );
+}
+
+#[tokio::test]
+async fn dedup_commit_treats_completed_with_warnings_as_success() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_dedup_node("f-warn", "dd");
+ store::upsert_flow(&config, &flow).unwrap();
+
+ let namespace = dedup_state_namespace("f-warn");
+ store::kv_set(&config, &namespace, "dedup:dd:tentative", &json!(["x"])).unwrap();
+
+ let sub = DedupCommitSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-warn".into(),
+ run_id: "run-warn".into(),
+ status: "completed_with_warnings".into(),
+ })
+ .await;
+
+ let committed = store::kv_get(&config, &namespace, "dedup:dd:committed")
+ .unwrap()
+ .expect("completed_with_warnings must still commit");
+ assert_eq!(committed, json!(["x"]));
+ assert!(
+ store::kv_get(&config, &namespace, "dedup:dd:tentative")
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn dedup_commit_releases_tentative_without_touching_committed_on_failure() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flow_with_dedup_node("f-failed", "dd");
+ store::upsert_flow(&config, &flow).unwrap();
+
+ let namespace = dedup_state_namespace("f-failed");
+ store::kv_set(&config, &namespace, "dedup:dd:committed", &json!(["a"])).unwrap();
+ store::kv_set(&config, &namespace, "dedup:dd:tentative", &json!(["b"])).unwrap();
+
+ let sub = DedupCommitSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: "f-failed".into(),
+ run_id: "run-failed".into(),
+ status: "failed".into(),
+ })
+ .await;
+
+ assert_eq!(
+ store::kv_get(&config, &namespace, "dedup:dd:committed")
+ .unwrap()
+ .unwrap(),
+ json!(["a"]),
+ "committed must be untouched by a failed run"
+ );
+ assert!(
+ store::kv_get(&config, &namespace, "dedup:dd:tentative")
+ .unwrap()
+ .is_none(),
+ "tentative must be released (cleared) on failure so the item retries"
+ );
+}
+
+#[tokio::test]
+async fn dedup_commit_releases_tentative_on_cancelled_and_interrupted() {
+ for status in ["cancelled", "interrupted"] {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_id = format!("f-{status}");
+ let flow = flow_with_dedup_node(&flow_id, "dd");
+ store::upsert_flow(&config, &flow).unwrap();
+
+ let namespace = dedup_state_namespace(&flow_id);
+ store::kv_set(&config, &namespace, "dedup:dd:tentative", &json!(["z"])).unwrap();
+
+ let sub = DedupCommitSubscriber::new(config.clone());
+ sub.handle(&DomainEvent::FlowRunFinished {
+ flow_id: flow_id.clone(),
+ run_id: format!("run-{status}"),
+ status: status.to_string(),
+ })
+ .await;
+
+ assert!(
+ store::kv_get(&config, &namespace, "dedup:dd:committed")
+ .unwrap()
+ .is_none(),
+ "status {status} must never commit"
+ );
+ assert!(
+ store::kv_get(&config, &namespace, "dedup:dd:tentative")
+ .unwrap()
+ .is_none(),
+ "status {status} must release tentative"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/flows/bus_tests.rs b/crates/openhuman-core/src/flows/bus_tests.rs
index e69de29bb2..a0f7f2da97 100644
--- a/crates/openhuman-core/src/flows/bus_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_tests.rs
@@ -0,0 +1,194 @@
+use super::*;
+use serde_json::json;
+use tinyflows::model::{Node, NodeKind, WorkflowGraph};
+use tinyflows_catalog::Flow;
+
+/// Binds a fresh in-memory reference engine to `config`'s workspace and
+/// returns it, so the digest tests write and read back through one store.
+fn digest_test_engine(config: &Config) -> Arc<tinymemory_api::conformance::ReferenceEngine> {
+ let engine = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+ engine
+}
+
+/// The run digests stored for `flow_id`.
+async fn stored_digests(config: &Config, flow_id: &str) -> Vec<tinymemory_api::Hit> {
+ crate::memory::ops::items_list(
+ config,
+ crate::memory::types::ItemsListParams {
+ filter: Some(digest_filter(flow_id)),
+ limit: Some(100),
+ cursor: None,
+ path: Vec::new(),
+ preview: false,
+ },
+ )
+ .await
+ .unwrap()
+ .items
+}
+
+fn test_config(tmp: &tempfile::TempDir) -> Arc<Config> {
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ Arc::new(config)
+}
+
+fn trigger_node(config: Value) -> Node {
+ Node {
+ id: "t".to_string(),
+ kind: NodeKind::Trigger,
+ type_version: 1,
+ name: "Trigger".to_string(),
+ config,
+ ports: Vec::new(),
+ position: None,
+ }
+}
+
+fn flow_with_trigger_config(id: &str, enabled: bool, trigger_config: Value) -> Flow {
+ Flow {
+ id: id.to_string(),
+ name: id.to_string(),
+ enabled,
+ graph: WorkflowGraph {
+ nodes: vec![trigger_node(trigger_config)],
+ ..Default::default()
+ },
+ created_at: "2026-01-01T00:00:00Z".to_string(),
+ updated_at: "2026-01-01T00:00:00Z".to_string(),
+ last_run_at: None,
+ last_status: None,
+ require_approval: false,
+ }
+}
+
+fn dedup_node(id: &str) -> Node {
+ Node {
+ id: id.to_string(),
+ kind: NodeKind::Dedup,
+ type_version: 1,
+ name: id.to_string(),
+ config: json!({ "key": "=item.id" }),
+ ports: Vec::new(),
+ position: None,
+ }
+}
+
+/// A saved flow with a `trigger` node plus one `dedup` node with id
+/// `dedup_id` — the minimal graph [`DedupCommitSubscriber::dedup_node_ids`]
+/// needs to find something to settle.
+fn flow_with_dedup_node(id: &str, dedup_id: &str) -> Flow {
+ Flow {
+ id: id.to_string(),
+ name: id.to_string(),
+ enabled: true,
+ graph: WorkflowGraph {
+ nodes: vec![trigger_node(json!({})), dedup_node(dedup_id)],
+ ..Default::default()
+ },
+ created_at: "2026-01-01T00:00:00Z".to_string(),
+ updated_at: "2026-01-01T00:00:00Z".to_string(),
+ last_run_at: None,
+ last_status: None,
+ require_approval: false,
+ }
+}
+
+// ── DedupCommitSubscriber ────────────────────────────────────────
+
+fn dedup_state_namespace(flow_id: &str) -> String {
+ // MUST match `tinyflows::build_capabilities`'s `state_namespace`
+ // (`crates/openhuman-core/src/flows/tinyflows/caps.rs`) — this test asserts the
+ // subscriber collides with the SAME keys the engine's `dedup` node
+ // itself reads/writes, not just "some" namespace.
+ format!("flow:{flow_id}")
+}
+
+#[path = "bus_dedup_commit_lock_tests.rs"]
+mod dedup_commit_lock_tests;
+#[path = "bus_subscriber_tests.rs"]
+mod subscriber_tests;
+#[path = "bus_trigger_queue_tests.rs"]
+mod trigger_queue_tests;
+
+#[tokio::test]
+async fn a_trigger_handled_as_an_agent_uses_the_agent_config() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ let registered = crate::config::Config {
+ workspace_dir: std::path::PathBuf::from("/tmp/flows-trigger-registered"),
+ ..crate::config::Config::default()
+ };
+ let subscriber = FlowTriggerSubscriber::new(std::sync::Arc::new(registered));
+ assert_eq!(
+ subscriber
+ .config_for_scope(&crate::core::runtime::DispatchCtx::unbound())
+ .workspace_dir,
+ std::path::PathBuf::from("/tmp/flows-trigger-registered"),
+ "outside an agent the registered config is used"
+ );
+ let agent_config = crate::config::Config {
+ workspace_dir: std::path::PathBuf::from("/tmp/flows-trigger-agent"),
+ ..crate::config::Config::default()
+ };
+ let agent = CoreContext::for_test(DomainSet::full(), None).derive_with(
+ ContextOverlay::new(agent_config, DomainSet::full(), Default::default())
+ .session_agent("flows-trigger-agent"),
+ );
+ let seen = subscriber
+ .config_for_scope(&crate::core::runtime::DispatchCtx::new(agent))
+ .workspace_dir
+ .clone();
+ assert_eq!(seen, std::path::PathBuf::from("/tmp/flows-trigger-agent"));
+}
+
+/// The dedup settle path reads the flow from the config its explicit context
+/// carries, concurrently with another tenant's, across an await and in a
+/// spawned task, with no task scope anywhere.
+#[tokio::test]
+async fn dedup_nodes_are_read_from_the_explicit_contexts_config() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+ let registered_tmp = tempfile::tempdir().unwrap();
+ let registered = test_config(&registered_tmp);
+ let subscriber = Arc::new(DedupCommitSubscriber::new(Arc::clone(&registered)));
+
+ let mut contexts = Vec::new();
+ for (name, dedup_id) in [("tenant-a", "dedup-a"), ("tenant-b", "dedup-b")] {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ store::upsert_flow(&config, &flow_with_dedup_node("shared-flow", dedup_id)).unwrap();
+ let ctx = DispatchCtx::new(
+ CoreContext::for_test(DomainSet::full(), None).derive_with(
+ ContextOverlay::new((*config).clone(), DomainSet::full(), Default::default())
+ .session_agent(name),
+ ),
+ );
+ contexts.push((tmp, ctx, dedup_id));
+ }
+
+ let mut tasks = Vec::new();
+ for (tmp, ctx, dedup_id) in contexts {
+ let subscriber = Arc::clone(&subscriber);
+ tasks.push(tokio::spawn(async move {
+ tokio::task::yield_now().await;
+ let ids = subscriber.dedup_node_ids(&ctx, "shared-flow");
+ drop(tmp);
+ (ids, dedup_id)
+ }));
+ }
+ for task in tasks {
+ let (ids, expected) = task.await.unwrap();
+ assert_eq!(ids, vec![expected.to_string()]);
+ }
+ // The registered config has no such flow: it is never consulted.
+ assert!(
+ subscriber
+ .dedup_node_ids(&DispatchCtx::unbound(), "shared-flow")
+ .is_empty()
+ );
+}
diff --git a/crates/openhuman-core/src/flows/catalogue_tests.rs b/crates/openhuman-core/src/flows/catalogue_tests.rs
index e69de29bb2..6d7520d33e 100644
--- a/crates/openhuman-core/src/flows/catalogue_tests.rs
+++ b/crates/openhuman-core/src/flows/catalogue_tests.rs
@@ -0,0 +1,228 @@
+//! Tests for the flow → catalogue-entry mapping.
+
+use super::*;
+use tinyflows::model::{Node, NodeKind, WorkflowGraph};
+use tinyflows_catalog::types::Flow;
+
+fn node(id: &str, kind: NodeKind, config: serde_json::Value) -> Node {
+ Node {
+ id: id.into(),
+ kind,
+ name: id.to_string(),
+ config,
+ type_version: 1,
+ ports: Vec::new(),
+ position: None,
+ }
+}
+
+fn flow(name: &str, enabled: bool, nodes: Vec<Node>) -> Flow {
+ Flow {
+ id: "flow-abc-123".to_string(),
+ name: name.to_string(),
+ enabled,
+ graph: WorkflowGraph {
+ nodes,
+ ..Default::default()
+ },
+ created_at: String::new(),
+ updated_at: String::new(),
+ last_run_at: None,
+ last_status: None,
+ require_approval: false,
+ }
+}
+
+#[test]
+fn the_entry_is_keyed_by_the_flow_id_not_a_slug_of_its_name() {
+ // `run_workflow` and `get_flow` take the id. A slug of the display name
+ // would be a second identifier that resolves nowhere, and the model would
+ // have no way to tell which one it was holding.
+ let entry = entry_for(flow("Morning Digest", true, vec![]));
+ assert_eq!(entry.dir_name, "flow-abc-123");
+ assert_eq!(entry.name, "Morning Digest");
+}
+
+#[test]
+fn the_entry_is_scoped_flow_and_carries_no_on_disk_bundle() {
+ // The distinction that makes `WorkflowScope::Flow` worth having: consumers
+ // that read `location` or `resources` must get an honest absence rather
+ // than a path that does not exist.
+ let entry = entry_for(flow("Anything", true, vec![]));
+ assert_eq!(entry.scope, WorkflowScope::Flow);
+ assert!(entry.location.is_none());
+ assert!(entry.resources.is_empty());
+}
+
+#[test]
+fn the_description_names_the_trigger_and_step_count() {
+ let f = flow(
+ "Digest",
+ true,
+ vec![
+ node(
+ "t",
+ NodeKind::Trigger,
+ serde_json::json!({ "trigger_kind": "schedule" }),
+ ),
+ node("a", NodeKind::Agent, serde_json::json!({})),
+ node("b", NodeKind::Agent, serde_json::json!({})),
+ ],
+ );
+ let entry = entry_for(f);
+ assert!(
+ entry.description.contains("schedule"),
+ "{}",
+ entry.description
+ );
+ // Two steps: the trigger is not a step a user thinks about.
+ assert!(
+ entry.description.contains("2 steps"),
+ "{}",
+ entry.description
+ );
+}
+
+#[test]
+fn a_single_step_is_not_pluralised() {
+ let f = flow(
+ "One",
+ true,
+ vec![
+ node(
+ "t",
+ NodeKind::Trigger,
+ serde_json::json!({ "trigger_kind": "manual" }),
+ ),
+ node("a", NodeKind::Agent, serde_json::json!({})),
+ ],
+ );
+ assert!(entry_for(f).description.contains("1 step)"));
+}
+
+#[test]
+fn a_graph_with_no_trigger_reads_as_manual_rather_than_blank() {
+ // `graph.trigger()` also returns `None` when there are *several* triggers.
+ // Either way the catalogue must say something; validation reports the real
+ // problem separately, so this stays quiet rather than duplicating it.
+ let entry = entry_for(flow("Headless", true, vec![]));
+ assert!(
+ entry.description.contains("manual"),
+ "{}",
+ entry.description
+ );
+}
+
+#[test]
+fn a_disabled_flow_is_still_listed_and_says_it_is_paused() {
+ // Hiding it would make the model answer "you have no such automation" to
+ // someone looking straight at it in the UI.
+ let entry = entry_for(flow("Paused", false, vec![]));
+ assert!(entry.description.contains("Currently disabled"));
+}
+
+#[test]
+fn an_enabled_flow_does_not_claim_to_be_disabled() {
+ assert!(
+ !entry_for(flow("Live", true, vec![]))
+ .description
+ .contains("disabled")
+ );
+}
+
+#[test]
+fn a_flow_description_is_always_derived_from_its_graph_shape() {
+ // The shared catalog type deliberately carries no free-text description.
+ // Do not infer a purpose from a user-provided name: that would make the
+ // prompt sound authoritative while merely guessing.
+ let entry = entry_for(flow("Send invoices to accounting", true, vec![]));
+ assert!(
+ entry.description.starts_with("Saved Flows automation"),
+ "fallback must describe the shape: {}",
+ entry.description
+ );
+ // And it must not guess a purpose out of the name.
+ assert!(!entry.description.contains("invoice"));
+}
+
+// ── Against a real store ──────────────────────────────────────────────────
+//
+// The mapping tests above never touch `flows.db`. These do, because the
+// interesting failure is not the mapping — it is `flow_entries` reading the
+// wrong database, or silently swallowing a real one. A unit test over
+// `entry_for` would pass in both cases.
+
+use tempfile::TempDir;
+
+fn store_config(tmp: &TempDir) -> crate::config::Config {
+ let config = crate::config::Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Default::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config
+}
+
+#[test]
+fn an_empty_store_contributes_nothing_to_the_catalogue() {
+ // Also the common case: most workspaces have no flows, and the catalogue
+ // must not grow a `[flow]` header or an empty group for them.
+ let tmp = TempDir::new().unwrap();
+ assert!(flow_entries(&store_config(&tmp)).is_empty());
+}
+
+#[test]
+fn a_saved_flow_reaches_the_catalogue_with_its_real_id() {
+ let tmp = TempDir::new().unwrap();
+ let config = store_config(&tmp);
+
+ let graph = WorkflowGraph {
+ nodes: vec![
+ node(
+ "t",
+ NodeKind::Trigger,
+ serde_json::json!({ "trigger_kind": "manual" }),
+ ),
+ node("a", NodeKind::Agent, serde_json::json!({})),
+ ],
+ ..Default::default()
+ };
+ let saved =
+ super::super::store::create_flow(&config, "Weekly Report".to_string(), graph, false, true)
+ .expect("flow saves");
+
+ let entries = flow_entries(&config);
+ assert_eq!(entries.len(), 1, "the saved flow must appear: {entries:?}");
+ let entry = &entries[0];
+ assert_eq!(entry.name, "Weekly Report");
+ // The store's generated id, not one this test made up — that is what
+ // `run_workflow` will be handed.
+ assert_eq!(entry.dir_name, saved.id);
+ assert_eq!(entry.scope, WorkflowScope::Flow);
+ assert!(entry.description.contains("manual trigger"));
+ assert!(entry.description.contains("1 step)"));
+}
+
+#[test]
+fn entries_are_sorted_by_name_so_the_prompt_prefix_is_stable() {
+ // The catalogue is rendered into a system prompt that is frozen for a whole
+ // session and cached by prefix. Insertion-order listing would reshuffle the
+ // prefix whenever a flow was created, invalidating the cache for reasons
+ // unrelated to the conversation.
+ let tmp = TempDir::new().unwrap();
+ let config = store_config(&tmp);
+ for name in ["Zebra", "Alpha", "Mango"] {
+ super::super::store::create_flow(
+ &config,
+ name.to_string(),
+ WorkflowGraph::default(),
+ false,
+ true,
+ )
+ .expect("flow saves");
+ }
+ let names: Vec<String> = flow_entries(&config).into_iter().map(|e| e.name).collect();
+ assert_eq!(names, vec!["Alpha", "Mango", "Zebra"]);
+}
diff --git a/crates/openhuman-core/src/flows/copilot_bus.rs b/crates/openhuman-core/src/flows/copilot_bus.rs
index e69de29bb2..63b0a24ba4 100644
--- a/crates/openhuman-core/src/flows/copilot_bus.rs
+++ b/crates/openhuman-core/src/flows/copilot_bus.rs
@@ -0,0 +1,194 @@
+//! Host tools that invoke the TinyFlows Copilot implementation through its bus contract.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use serde::{Serialize, de::DeserializeOwned};
+use serde_json::Value;
+use tinyflows_bus::copilot::{ToolCatalogRequest, ToolDescriptor};
+use tinytools::{PermissionLevel, Tool, ToolResult};
+
+use crate::config::Config;
+
+pub(crate) async fn call<R, A>(config: &Config, member: &'static str, args: A) -> Result<R, String>
+where
+ R: DeserializeOwned,
+ A: Serialize,
+{
+ let proxy = crate::modules::tinyflows::copilot_proxy(config).await?;
+ proxy
+ .call(member, args)
+ .await
+ .map_err(|error| error.wire_message())
+}
+
+/// The module's tool metadata plus the host-only node-kind overlay for calls.
+pub(crate) struct CopilotToolCatalog {
+ config: Arc<Config>,
+ node_kinds: Vec<Value>,
+ descriptors: HashMap<String, ToolDescriptor>,
+}
+
+impl CopilotToolCatalog {
+ /// Load the tools the compiled module serves for this host configuration.
+ pub(crate) fn load(config: Arc<Config>) -> Result<Self, String> {
+ // Tool registration is synchronous, so fetch module-owned metadata
+ // through the storage blocking bridge. This call carries the supplied
+ // config and resolves no tenant data; tool calls take their authority
+ // from ToolRunContext.
+ let call_config = Arc::clone(&config);
+ let node_kinds = crate::storage::block_on_anyhow(async move {
+ crate::flows::all_node_kind_contracts(&call_config)
+ .await
+ .map_err(anyhow::Error::msg)
+ })
+ .map_err(|error| format!("could not load workflow node contracts: {error}"))
+ .and_then(|contracts| serde_json::to_value(contracts).map_err(|error| error.to_string()))?
+ .as_array()
+ .cloned()
+ .ok_or_else(|| "workflow node contracts were not an array".to_string())?;
+ let request = ToolCatalogRequest {
+ node_kinds: node_kinds.clone(),
+ };
+ let call_config = Arc::clone(&config);
+ let descriptors: Vec<ToolDescriptor> = crate::storage::block_on_anyhow(async move {
+ let proxy = crate::modules::tinyflows::copilot_proxy(&call_config)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ proxy
+ .call("ToolCatalog", (request,))
+ .await
+ .map_err(|error| anyhow::anyhow!(error.wire_message()))
+ })
+ .map_err(|error| format!("could not load TinyFlows Copilot tools: {error}"))?;
+
+ let mut by_name = HashMap::with_capacity(descriptors.len());
+ for descriptor in descriptors {
+ permission_level(&descriptor.permission).ok_or_else(|| {
+ format!(
+ "TinyFlows Copilot tool `{}` has unsupported permission `{}`",
+ descriptor.name, descriptor.permission
+ )
+ })?;
+ if by_name
+ .insert(descriptor.name.clone(), descriptor)
+ .is_some()
+ {
+ return Err("TinyFlows Copilot returned duplicate tool names".into());
+ }
+ }
+ Ok(Self {
+ config,
+ node_kinds,
+ descriptors: by_name,
+ })
+ }
+
+ pub(crate) fn tool(&self, name: &str) -> Result<BusCopilotTool, String> {
+ let descriptor = self
+ .descriptors
+ .get(name)
+ .cloned()
+ .ok_or_else(|| format!("TinyFlows Copilot does not provide `{name}`"))?;
+ Ok(BusCopilotTool {
+ config: Arc::clone(&self.config),
+ descriptor,
+ node_kinds: self.node_kinds.clone(),
+ })
+ }
+}
+
+/// A `tinytools::Tool` facade over one tool served by TinyFlows Copilot.
+pub(crate) struct BusCopilotTool {
+ config: Arc<Config>,
+ descriptor: ToolDescriptor,
+ node_kinds: Vec<Value>,
+}
+
+impl BusCopilotTool {
+ #[cfg(test)]
+ pub(crate) fn from_name(config: Arc<Config>, name: &str) -> Self {
+ CopilotToolCatalog::load(config)
+ .and_then(|catalog| catalog.tool(name))
+ .unwrap_or_else(|error| panic!("could not prepare Copilot tool `{name}`: {error}"))
+ }
+
+ async fn invoke(
+ &self,
+ args: Value,
+ context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let host = super::builder_host::register(
+ Arc::clone(&self.config),
+ crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context),
+ )
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let proxy = crate::modules::tinyflows::copilot_invoke_proxy(&self.config)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let request = tinyflows_bus::copilot::InvokeToolRequest {
+ name: self.descriptor.name.clone(),
+ arguments: args,
+ host: host.address(),
+ node_kinds: self.node_kinds.clone(),
+ };
+ let result: Value = proxy
+ .call("InvokeTool", (request,))
+ .await
+ .map_err(|error| anyhow::anyhow!(error.wire_message()))?;
+ serde_json::from_value(result)
+ .map_err(|error| anyhow::anyhow!("invalid TinyFlows Copilot tool result: {error}"))
+ }
+}
+
+#[async_trait::async_trait]
+impl Tool for BusCopilotTool {
+ fn name(&self) -> &str {
+ &self.descriptor.name
+ }
+
+ fn description(&self) -> &str {
+ &self.descriptor.description
+ }
+
+ fn parameters_schema(&self) -> Value {
+ self.descriptor.parameters_schema.clone()
+ }
+
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ self.invoke(args, None).await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: Value,
+ _options: tinytools::ToolCallOptions,
+ context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ self.invoke(args, context).await
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ permission_level(&self.descriptor.permission).unwrap_or(PermissionLevel::Dangerous)
+ }
+
+ fn external_effect(&self) -> bool {
+ self.descriptor.external_effect
+ }
+}
+
+fn permission_level(permission: &str) -> Option<PermissionLevel> {
+ match permission {
+ "None" => Some(PermissionLevel::None),
+ "ReadOnly" => Some(PermissionLevel::ReadOnly),
+ "Write" => Some(PermissionLevel::Write),
+ "Execute" => Some(PermissionLevel::Execute),
+ "Dangerous" => Some(PermissionLevel::Dangerous),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+#[path = "copilot_bus_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/copilot_bus_tests.rs b/crates/openhuman-core/src/flows/copilot_bus_tests.rs
index e69de29bb2..b685dd2a3a 100644
--- a/crates/openhuman-core/src/flows/copilot_bus_tests.rs
+++ b/crates/openhuman-core/src/flows/copilot_bus_tests.rs
@@ -0,0 +1,215 @@
+use super::*;
+use serde_json::json;
+
+#[tokio::test]
+async fn module_tool_descriptors_preserve_run_and_sandbox_safety_metadata() {
+ let config = Arc::new(Config::default());
+ let catalog = CopilotToolCatalog::load(config).expect("module tool catalog loads");
+
+ let run = catalog.tool("run_flow").expect("run_flow is catalogued");
+ assert_eq!(run.permission_level(), PermissionLevel::Write);
+ assert!(run.external_effect());
+ assert_eq!(run.parameters_schema()["required"], json!(["flow_id"]));
+
+ let dry_run = catalog
+ .tool("dry_run_workflow")
+ .expect("dry_run_workflow is catalogued");
+ assert_eq!(dry_run.permission_level(), PermissionLevel::None);
+ assert!(!dry_run.external_effect());
+}
+
+#[tokio::test]
+async fn model_arguments_cannot_replace_the_scoped_host_callback_address() {
+ let workspace = tempfile::tempdir().expect("temporary workspace");
+ let mut config = Config::default();
+ config.workspace_dir = workspace.path().to_path_buf();
+ config.config_path = workspace.path().join("config.toml");
+ let catalog = CopilotToolCatalog::load(Arc::new(config)).expect("module tool catalog loads");
+ let tool = catalog
+ .tool("list_flows")
+ .expect("list_flows is catalogued");
+ let result = tool
+ .execute(json!({
+ "host": {
+ "bus_name": "ai.tinyhumans.attacker",
+ "object_path": "/attacker/copilot-host"
+ }
+ }))
+ .await
+ .expect("the outer invocation supplies its own host callback");
+ assert!(
+ !result.is_error,
+ "model arguments must not redirect the scoped callback: {}",
+ result.output()
+ );
+ let output: Value = serde_json::from_str(&result.output()).expect("tool JSON result");
+ assert_eq!(output["flows"], json!([]), "{output}");
+}
+
+fn tool_context(
+ core: &Arc<crate::core::runtime::CoreContext>,
+ id: &str,
+) -> tinyagents_harness::tool::ToolExecutionContext {
+ let run = crate::agent::tinyagents::host::run_context::OpenHumanRunContext::new()
+ .with_core(Some(Arc::clone(core)))
+ .into_tinyagents(tinyagents_harness::context::RunConfig::new(id));
+ tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &run,
+ tinyagents_harness::ids::CallId::new(format!("{id}-call")),
+ )
+}
+
+#[tokio::test]
+async fn concurrent_tool_callbacks_keep_each_explicit_profile_scope() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ use crate::tools::toolpacks::ToolGroups;
+
+ let workspace = tempfile::tempdir().expect("temporary workspace");
+ let mut config = Config::default();
+ config.workspace_dir = workspace.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ config.config_path = workspace.path().join("config.toml");
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace directory");
+
+ let root = CoreContext::for_test_with_config(DomainSet::full(), config.clone());
+ let alice = root.derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::default())
+ .profile("copilot-alice"),
+ );
+ let bob = root.derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::default())
+ .profile("copilot-bob"),
+ );
+ let graph = json!({
+ "nodes": [{"id":"trigger","kind":"trigger","name":"Trigger","config":{}}],
+ "edges": []
+ });
+ for (context, name) in [(&alice, "Alice only"), (&bob, "Bob only")] {
+ let context = Arc::clone(context);
+ let config = config.clone();
+ let graph = graph.clone();
+ let name = name.to_string();
+ CoreContext::scope(context.clone(), async move {
+ crate::flows::ops::flows_create(&config, name, graph, false)
+ .await
+ .expect("profile flow creation");
+ })
+ .await;
+ }
+
+ let catalog = CopilotToolCatalog::load(Arc::new(config)).expect("module tool catalog loads");
+ let tool = catalog
+ .tool("list_flows")
+ .expect("list_flows is catalogued");
+ let alice_call = tool_context(&alice, "copilot-alice");
+ let bob_call = tool_context(&bob, "copilot-bob");
+ let alice_future = tool.execute_with_context(
+ json!({}),
+ tinytools::ToolCallOptions::default(),
+ Some(&alice_call),
+ );
+ let bob_future = tool.execute_with_context(
+ json!({}),
+ tinytools::ToolCallOptions::default(),
+ Some(&bob_call),
+ );
+ let (alice_result, bob_result) = tokio::join!(alice_future, bob_future);
+ let alice_result = alice_result.expect("Alice callback result");
+ let bob_result = bob_result.expect("Bob callback result");
+ assert!(!alice_result.is_error, "{}", alice_result.output());
+ assert!(!bob_result.is_error, "{}", bob_result.output());
+ assert!(alice_result.output().contains("Alice only"));
+ assert!(!alice_result.output().contains("Bob only"));
+ assert!(bob_result.output().contains("Bob only"));
+ assert!(!bob_result.output().contains("Alice only"));
+}
+
+#[tokio::test]
+async fn module_run_flow_uses_the_host_detached_runner_and_requires_a_saved_flow() {
+ let workspace = tempfile::tempdir().expect("temporary workspace");
+ let mut config = Config::default();
+ config.workspace_dir = workspace.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ config.config_path = workspace.path().join("config.toml");
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace directory");
+ let catalog =
+ CopilotToolCatalog::load(Arc::new(config.clone())).expect("module tool catalog loads");
+ let tool = catalog.tool("run_flow").expect("run_flow is catalogued");
+
+ let missing = tool
+ .execute(json!({ "flow_id": "not-saved" }))
+ .await
+ .expect("missing flow is a reported tool failure");
+ assert!(missing.is_error, "{}", missing.output());
+ assert!(
+ missing.output().contains("not-saved"),
+ "{}",
+ missing.output()
+ );
+
+ let flow = crate::flows::ops::flows_create(
+ &config,
+ "Detached Copilot run".into(),
+ json!({
+ "nodes": [{"id":"trigger","kind":"trigger","name":"Trigger","config":{}}],
+ "edges": []
+ }),
+ false,
+ )
+ .await
+ .expect("saved flow creates")
+ .value;
+ let result = tool
+ .execute(json!({ "flow_id": flow.id, "input": { "source": "copilot" } }))
+ .await
+ .expect("saved flow starts through the host callback");
+ assert!(!result.is_error, "{}", result.output());
+ let started: Value = serde_json::from_str(&result.output()).expect("run result JSON");
+ assert_eq!(started["type"], "workflow_run_started");
+ assert_eq!(started["status"], "running");
+ assert!(started["run_id"].as_str().is_some_and(|id| !id.is_empty()));
+ assert_eq!(started["flow_id"], flow.id);
+}
+
+#[tokio::test]
+async fn module_proposal_tool_uses_host_gates_without_persisting() {
+ let workspace = tempfile::tempdir().expect("temporary workspace");
+ let mut config = Config::default();
+ config.workspace_dir = workspace.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ config.config_path = workspace.path().join("config.toml");
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace directory");
+ let catalog =
+ CopilotToolCatalog::load(Arc::new(config.clone())).expect("module tool catalog loads");
+ let tool = catalog
+ .tool("propose_workflow")
+ .expect("propose_workflow is catalogued");
+
+ let invalid = tool
+ .execute(json!({ "name": "Invalid", "graph": { "nodes": [], "edges": [] } }))
+ .await
+ .expect("invalid candidate is a reported tool error");
+ assert!(invalid.is_error, "{}", invalid.output());
+
+ let valid = tool
+ .execute(json!({
+ "name": "Proposed only",
+ "graph": {
+ "nodes": [{"id":"trigger","kind":"trigger","name":"Trigger","config":{}}],
+ "edges": []
+ }
+ }))
+ .await
+ .expect("valid candidate uses the scoped BuildProposal callback");
+ assert!(!valid.is_error, "{}", valid.output());
+ let proposal: Value = serde_json::from_str(&valid.output()).expect("proposal JSON");
+ assert_eq!(proposal["type"], "workflow_proposal");
+ assert_eq!(proposal["persisted"], false);
+ assert!(
+ crate::flows::ops::flows_list(&config)
+ .await
+ .expect("flow list")
+ .value
+ .is_empty()
+ );
+}
diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rs
index e69de29bb2..380a8f27a1 100644
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@ -0,0 +1,568 @@
+//! Agent tools giving a running flow a private, tag-scoped slice of memory,
+//! plus the flow-memory helpers every flow memory caller shares.
+//!
+//! Memory v2 has no namespaces: a flow's items are the items carrying its
+//! [`flow_tag`] (`flow:<flow_id>`). Every flow write also carries
+//! [`FLOWS_TAG`] (`flows`), which is what the read-only cross-flow
+//! `scope: "flows"` recall filters on. A keyed write additionally carries
+//! [`flow_key_tag`] (`flow:<flow_id>:key:<key>`) so it can be replaced and
+//! forgotten by key.
+//!
+//! Motivating use case: a newsletter-digest flow that runs on a schedule
+//! needs to remember which items it already sent so it doesn't re-send them
+//! on the next run.
+//!
+//! **Security invariant (non-negotiable):** there is no code path here by
+//! which a flow can write an item tagged for another flow. Every write
+//! derives its tags from the run's trusted `TrustedAutomation { Workflow }`
+//! origin ([`trusted_flow_id`]), never from a model-supplied `flow_id`
+//! argument; outside a trusted workflow run the write is refused outright.
+//! Flow writes are stored as `source.kind = agent` learnings with the flow
+//! tags, so they never pose as user-authored conversation or documents.
+//! [`FlowMemoryRecallTool`] only ever reads with a flow tag filter
+//! (`flow:<id>` or `flows`), so it never reaches the user's own memory.
+
+use crate::tools::schema_cache::static_schema;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::json;
+use tinymemory_api::{
+ Citation, ForgetTarget, LearningKind, MemoryMeta, MetaFilter, SourceKind, SourceRef,
+};
+use tinytools::{PermissionLevel, Tool, ToolResult};
+
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
+use crate::config::Config;
+use crate::memory::types::{ForgetParams, ItemsListParams, LearnParams, RecallParams};
+use crate::memory::{MemoryError, MemoryResult};
+use crate::security::SecurityPolicy;
+use crate::security::policy::ToolOperation;
+
+/// Prefix of a flow's own tag (see [`flow_tag`]).
+pub const FLOW_TAG_PREFIX: &str = "flow:";
+
+/// Tag carried by every flow-written item; the cross-flow (`scope: "flows"`)
+/// read filter.
+pub const FLOWS_TAG: &str = "flows";
+
+/// Infix between a flow's tag and a key in [`flow_key_tag`].
+const FLOW_KEY_INFIX: &str = ":key:";
+
+/// Returns the flow id the *run itself* is scoped under, when the current
+/// agent turn is executing inside a saved-flow run
+/// (`AgentTurnOrigin::TrustedAutomation { job_id, source: Workflow { .. } }` —
+/// see `flows::ops::workflow_origin`). `job_id` on that variant IS the
+/// running flow's id.
+///
+/// **Security invariant:** this is the ONLY trustworthy source of "which flow
+/// is calling". A `flow_id` tool argument is model-supplied and can be forged
+/// by a prompt-injected caller. Writes refuse when this is `None`; the
+/// read-only recall falls back to the argument (cross-flow reads are already
+/// open by design, so an argument grants no new read privilege).
+fn trusted_flow_id(origin: Option<&AgentTurnOrigin>) -> Option<String> {
+ match origin {
+ Some(AgentTurnOrigin::TrustedAutomation {
+ job_id,
+ source: TrustedAutomationSource::Workflow { .. },
+ }) => Some(job_id.clone()),
+ _ => None,
+ }
+}
+
+/// The tag marking an item as `flow_id`'s own.
+///
+/// **Security invariant:** the only constructor of flow tags. Every caller —
+/// the agent tools below, the tinyflows `memory` node adapter, the post-run
+/// digest subscriber and `flows_delete` — passes a trusted flow id.
+#[must_use]
+pub fn flow_tag(flow_id: &str) -> String {
+ format!("{FLOW_TAG_PREFIX}{flow_id}")
+}
+
+/// The tag marking an item as `flow_id`'s value for `key`.
+#[must_use]
+pub fn flow_key_tag(flow_id: &str, key: &str) -> String {
+ format!("{FLOW_TAG_PREFIX}{flow_id}{FLOW_KEY_INFIX}{key}")
+}
+
+/// The key a flow item was written under, recovered from its tags.
+#[must_use]
+pub fn flow_key_of(meta: &MemoryMeta) -> Option<&str> {
+ meta.tags.iter().find_map(|tag| {
+ tag.strip_prefix(FLOW_TAG_PREFIX)
+ .and_then(|rest| rest.split_once(FLOW_KEY_INFIX))
+ .map(|(_, key)| key)
+ })
+}
+
+/// The filter matching every item `flow_id` wrote.
+#[must_use]
+pub fn flow_filter(flow_id: &str) -> MetaFilter {
+ MetaFilter {
+ tags_any: vec![flow_tag(flow_id)],
+ ..MetaFilter::default()
+ }
+}
+
+/// The filter matching every flow-written item, of any flow.
+#[must_use]
+pub fn cross_flow_filter() -> MetaFilter {
+ MetaFilter {
+ tags_any: vec![FLOWS_TAG.to_string()],
+ ..MetaFilter::default()
+ }
+}
+
+/// Host metadata for an item `flow_id` writes: `source.kind = agent` with the
+/// flow tag as its source id, tagged [`flow_tag`], [`FLOWS_TAG`] and `extra`.
+#[must_use]
+pub fn flow_meta(flow_id: &str, extra: &[String]) -> MemoryMeta {
+ let tag = flow_tag(flow_id);
+ let mut tags = vec![tag.clone(), FLOWS_TAG.to_string()];
+ tags.extend(extra.iter().cloned());
+ MemoryMeta {
+ source: SourceRef {
+ kind: SourceKind::Agent,
+ id: Some(tag),
+ },
+ tags,
+ ..MemoryMeta::default()
+ }
+}
+
+/// Forgets every item matching `filter` (which must be non-empty). Memory
+/// off forgets nothing.
+pub async fn forget_matching(config: &Config, filter: MetaFilter) -> MemoryResult<usize> {
+ if filter.is_empty() {
+ return Err(MemoryError::invalid(
+ "refusing to forget with an empty filter",
+ ));
+ }
+ let bound = match crate::memory::engine::resolve(config).engine() {
+ Ok(bound) => bound,
+ Err(MemoryError::Off(_)) => {
+ tracing::debug!("[flows:memory] forget skipped: memory is off");
+ return Ok(0);
+ }
+ Err(error) => return Err(error),
+ };
+ let report = bound.engine.forget(ForgetTarget::Filter(filter)).await?;
+ tracing::debug!(
+ engine = %bound.id,
+ forgotten = report.forgotten,
+ "[flows:memory] forgot items by tag filter"
+ );
+ Ok(report.forgotten)
+}
+
+/// Stores `content` as `flow_id`'s value for `key`, replacing an earlier
+/// value under the same key. Returns the stored item's id.
+pub async fn remember_keyed(
+ config: &Config,
+ flow_id: &str,
+ key: &str,
+ content: &str,
+ kind: LearningKind,
+) -> MemoryResult<String> {
+ // Fail with MEMORY_OFF before touching anything.
+ crate::memory::engine::resolve(config).engine()?;
+ let key_tag = flow_key_tag(flow_id, key);
+ // Take a scoped snapshot before writing. If learning fails, this leaves
+ // the prior value intact; deleting by these ids after learning also keeps
+ // a concurrent write that was absent from the snapshot.
+ let mut old_ids = Vec::new();
+ let mut cursor = None;
+ loop {
+ let page = crate::memory::ops::items_list(
+ config,
+ ItemsListParams {
+ filter: Some(MetaFilter {
+ tags_any: vec![key_tag.clone()],
+ ..MetaFilter::default()
+ }),
+ limit: Some(crate::memory::types::MAX_LIMIT),
+ cursor,
+ ..ItemsListParams::default()
+ },
+ )
+ .await?;
+ old_ids.extend(page.items.into_iter().map(|item| item.id.0));
+ cursor = page.next_cursor;
+ if cursor.is_none() {
+ break;
+ }
+ }
+ // A flow's own key/value state: searchable, but nothing is derived from
+ // it as memory about the user.
+ let mut meta = flow_meta(flow_id, &[key_tag]);
+ meta.derive = Some(false);
+ let view = crate::memory::ops::learn(
+ config,
+ LearnParams {
+ text: content.to_string(),
+ kind: Some(kind),
+ confidence: None,
+ meta: None,
+ },
+ Some(meta),
+ )
+ .await?;
+ let obsolete_ids: Vec<String> = old_ids.into_iter().filter(|id| id != &view.id).collect();
+ let replaced = if obsolete_ids.is_empty() {
+ 0
+ } else {
+ crate::memory::ops::forget(
+ config,
+ ForgetParams {
+ ids: obsolete_ids,
+ reach: None,
+ },
+ )
+ .await?
+ .forgotten
+ };
+ tracing::debug!(
+ flow_id = %flow_id,
+ key_chars = key.chars().count(),
+ content_chars = content.chars().count(),
+ replaced,
+ "[flows:memory] keyed flow memory stored"
+ );
+ Ok(view.id)
+}
+
+/// Maps the tool's `category` argument onto a learning kind.
+fn learning_kind_for(category: Option<&str>) -> LearningKind {
+ match category.map(|c| c.trim().to_ascii_lowercase()) {
+ None => LearningKind::Fact,
+ Some(c) => match c.as_str() {
+ "" | "fact" | "core" => LearningKind::Fact,
+ "preference" => LearningKind::Preference,
+ "procedure" => LearningKind::Procedure,
+ "correction" => LearningKind::Correction,
+ _ => LearningKind::Other,
+ },
+ }
+}
+
+/// Read-only recall over a flow's own items, or (with `scope: "flows"`)
+/// across every flow's items — never the user's own memory.
+pub struct FlowMemoryRecallTool;
+
+impl FlowMemoryRecallTool {
+ /// Holds no memory handle — config and engine are resolved per call.
+ #[must_use]
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for FlowMemoryRecallTool {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Renders a recall answer and its citations, each attributed to its flow
+/// key when it has one.
+fn render_recall(answer: &str, citations: &[Citation]) -> String {
+ if citations.is_empty() {
+ return "No flow memories found matching that query.".to_string();
+ }
+ use std::fmt::Write;
+ let mut output = format!("{answer}\n\nSources ({}):\n", citations.len());
+ for citation in citations {
+ let key = flow_key_of(&citation.meta).unwrap_or("-");
+ let _ = writeln!(output, "- [{}] [{key}] {}", citation.id.0, citation.snippet);
+ }
+ output
+}
+
+#[async_trait]
+impl Tool for FlowMemoryRecallTool {
+ fn name(&self) -> &str {
+ "flow_memory_recall"
+ }
+
+ fn description(&self) -> &str {
+ "Search a flow's own private memory for relevant facts — e.g. so a scheduled \
+ digest flow can check what it already sent before, to avoid duplicates. `scope: \"flow\"` \
+ (the default) searches only the calling flow's own memory. `scope: \"flows\"` searches \
+ read-only across every flow's memory (useful when related flows should dedupe \
+ against each other). This tool never reads the user's personal memory — only memory \
+ flows have written about their own runs."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Keywords or phrase to search for"
+ },
+ "flow_id": {
+ "type": "string",
+ "description": "The calling flow's id. Inside a running flow this is informational \
+ only: the active flow's own id (from the run's trusted origin) is authoritative and \
+ any value supplied here is ignored. Required only when this tool is invoked outside \
+ a flow run (e.g. from a chat agent)."
+ },
+ "scope": {
+ "type": "string",
+ "enum": ["flow", "flows"],
+ "description": "\"flow\" (default) searches only this flow's own memory; \"flows\" searches read-only across every flow's memory."
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Max results to return (default: 5)"
+ }
+ },
+ "required": ["query", "flow_id"]
+ })
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.execute_with_context(args, tinytools::ToolCallOptions::default(), None)
+ .await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: serde_json::Value,
+ _options: tinytools::ToolCallOptions,
+ tool_context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let origin =
+ crate::agent::tinyagents::host::run_context::turn_origin_for_tool(tool_context);
+ let query = match args.get("query").and_then(|v| v.as_str()) {
+ Some(q) => q.trim(),
+ None => return Ok(ToolResult::error("Missing 'query' parameter".to_string())),
+ };
+ if query.is_empty() {
+ return Ok(ToolResult::error("query cannot be empty".to_string()));
+ }
+ let flow_id_arg = args.get("flow_id").and_then(|v| v.as_str()).map(str::trim);
+
+ // SECURITY: inside a running flow the trusted origin wins over the
+ // model-supplied `flow_id` argument.
+ let flow_id = match trusted_flow_id(origin.as_ref()) {
+ Some(trusted_id) => {
+ tracing::debug!(
+ target: "flows",
+ flow_id = %trusted_id,
+ "[flows:memory] flow_memory_recall: flow id from the trusted Workflow origin"
+ );
+ trusted_id
+ }
+ None => match flow_id_arg {
+ None => return Ok(ToolResult::error("Missing 'flow_id' parameter".to_string())),
+ Some("") => return Ok(ToolResult::error("flow_id cannot be empty".to_string())),
+ Some(arg) => arg.to_string(),
+ },
+ };
+ let scope = args.get("scope").and_then(|v| v.as_str()).unwrap_or("flow");
+ let filter = match scope {
+ "flow" => flow_filter(&flow_id),
+ "flows" => cross_flow_filter(),
+ other => {
+ return Ok(ToolResult::error(format!(
+ "Unknown scope '{other}': expected 'flow' or 'flows'"
+ )));
+ }
+ };
+ #[allow(clippy::cast_possible_truncation)]
+ let limit = args
+ .get("limit")
+ .and_then(serde_json::Value::as_u64)
+ .map_or(5, |v| v as usize);
+
+ let config =
+ match crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)
+ .load_config()
+ .await
+ {
+ Ok(config) => config,
+ Err(error) => {
+ return Ok(ToolResult::error(format!(
+ "Flow memory recall failed: {error}"
+ )));
+ }
+ };
+ tracing::debug!(
+ target: "flows",
+ scope,
+ query_chars = query.chars().count(),
+ limit,
+ "[flows:memory] flow_memory_recall: querying"
+ );
+ match crate::memory::ops::recall(
+ &config,
+ RecallParams {
+ refers_to: None,
+ question: query.to_string(),
+ filter: Some(filter),
+ limit: Some(limit),
+ },
+ )
+ .await
+ {
+ Ok(view) => {
+ tracing::debug!(
+ target: "flows",
+ scope,
+ citations = view.citations.len(),
+ "[flows:memory] flow_memory_recall: answered"
+ );
+ Ok(ToolResult::success(render_recall(
+ &view.answer,
+ &view.citations,
+ )))
+ }
+ Err(error) => {
+ tracing::debug!(
+ target: "flows",
+ code = error.code(),
+ "[flows:memory] flow_memory_recall: failed"
+ );
+ Ok(ToolResult::error(format!(
+ "Flow memory recall failed: {error}"
+ )))
+ }
+ }
+ }
+
+ fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {
+ true
+ }
+}
+
+/// Write access to a flow's own memory — and *only* its own. See the module
+/// doc for the security invariant this tool exists to preserve.
+pub struct FlowMemoryRememberTool {
+ security: Arc<SecurityPolicy>,
+}
+
+impl FlowMemoryRememberTool {
+ /// Holds no memory handle — config and engine are resolved per call.
+ #[must_use]
+ pub fn new(security: Arc<SecurityPolicy>) -> Self {
+ Self { security }
+ }
+}
+
+#[async_trait]
+impl Tool for FlowMemoryRememberTool {
+ fn name(&self) -> &str {
+ "flow_memory_remember"
+ }
+
+ fn description(&self) -> &str {
+ "Store a fact in THIS flow's own private memory — e.g. so a scheduled digest \
+ flow can remember which items it already sent, to avoid re-sending them on the next run. \
+ Writing the same `key` again replaces the earlier value. The flow is taken from the run \
+ itself; there is no way to target the user's personal memory or another flow's memory \
+ from this tool."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ static_schema!(include_str!("parameters/flow_memory_remember.json"))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Write
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.execute_with_context(args, tinytools::ToolCallOptions::default(), None)
+ .await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: serde_json::Value,
+ _options: tinytools::ToolCallOptions,
+ tool_context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let origin =
+ crate::agent::tinyagents::host::run_context::turn_origin_for_tool(tool_context);
+ let flow_id_arg = args.get("flow_id").and_then(|v| v.as_str());
+ let Some(key) = args.get("key").and_then(|v| v.as_str()) else {
+ return Ok(ToolResult::error("Missing 'key' parameter".to_string()));
+ };
+ let Some(content) = args.get("content").and_then(|v| v.as_str()) else {
+ return Ok(ToolResult::error("Missing 'content' parameter".to_string()));
+ };
+ let kind = learning_kind_for(args.get("category").and_then(|v| v.as_str()));
+
+ if let Err(error) = self
+ .security
+ .enforce_tool_operation(ToolOperation::Act, "flow_memory_remember")
+ {
+ return Ok(ToolResult::error(error));
+ }
+
+ // SECURITY (T-M2): the flow comes from the trusted run origin only;
+ // outside a workflow run the write is refused.
+ let Some(flow_id) = trusted_flow_id(origin.as_ref()) else {
+ tracing::warn!(
+ target: "flows",
+ requested_flow_id_chars = flow_id_arg.map_or(0, str::len),
+ "[flows:memory:security] flow_memory_remember refused: no trusted Workflow run origin"
+ );
+ return Ok(ToolResult::error(
+ "flow memory writes are only available inside a workflow run".to_string(),
+ ));
+ };
+ let key = key.trim();
+ if key.is_empty() {
+ return Ok(ToolResult::error("key cannot be empty".to_string()));
+ }
+ if tinyredact::has_likely_secret(content) {
+ tracing::warn!(
+ target: "flows",
+ key_chars = key.chars().count(),
+ content_chars = content.chars().count(),
+ "[flows:memory:safety] flow_memory_remember rejected secret-like content"
+ );
+ return Ok(ToolResult::error(
+ "Refusing to store content that looks like a secret. Remove credentials or tokens and try again.".to_string(),
+ ));
+ }
+
+ let config =
+ match crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)
+ .load_config()
+ .await
+ {
+ Ok(config) => config,
+ Err(error) => {
+ return Ok(ToolResult::error(format!(
+ "Failed to store flow memory: {error}"
+ )));
+ }
+ };
+ match remember_keyed(&config, &flow_id, key, content, kind).await {
+ Ok(_) => Ok(ToolResult::success(format!("Stored flow memory: {key}"))),
+ Err(error) => {
+ tracing::debug!(
+ target: "flows",
+ code = error.code(),
+ "[flows:memory] flow_memory_remember: store failed"
+ );
+ Ok(ToolResult::error(format!(
+ "Failed to store flow memory: {error}"
+ )))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "memory_tools_tests.rs"]
+mod tests;
+
+#[cfg(test)]
+#[path = "memory_tools_schema_tests.rs"]
+mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/mod.rs b/crates/openhuman-core/src/flows/mod.rs
index e69de29bb2..07345fbe38 100644
--- a/crates/openhuman-core/src/flows/mod.rs
+++ b/crates/openhuman-core/src/flows/mod.rs
@@ -0,0 +1,68 @@
+//! The `flows::` domain: saved automation workflows (tinyflows graphs) —
+//! create/get/list/update/delete/enable/run, backed by SQLite. Mirrors
+//! `crates/openhuman-core/src/cron/`'s module shape.
+//!
+//! Business logic lives in [`ops`]; persistence in `store` (private, with a
+//! handful of functions re-exported below for the capability seam's
+//! `tinyflows_sqlite::flows::SqliteStateStore`); the RPC/CLI
+//! controller surface in `schemas` (private, re-exported below).
+//!
+//! # Gate shape — leaf, not facade
+//!
+//! The whole family (this module plus [`tinyflows`]) is gated at
+//! `pub mod flows;` in `crates/openhuman-core/src/lib.rs` on `#[cfg(feature = "flows")]`,
+//! and the submodules below inherit that gate. There is **no `stub.rs`**:
+//! every symbol reached from outside is a *registration site* (`core::all`,
+//! `core::runtime::subscribers`' `FlowTriggerSubscriber`, `core::runtime::services`' boot
+//! reconcile, the agent-tool `vec!` in `tools::ops`, the `workflow_builder` /
+//! `flow_discovery` entries in `agent::registry`'s `BUILTINS`), and a registration site wants
+//! *absence*, not a disabled-error stub — otherwise `flows.*` becomes a known
+//! method that fails at runtime.
+//!
+//! The leaf gate holds only because no always-compiled domain has a real code
+//! edge into this tree. If one ever gains a real `use` of `flows::`, this
+//! family must convert to the facade+stub shape (see `voice/`).
+
+mod agent_route;
+pub(crate) mod authoring_host;
+pub mod builder_host;
+pub(crate) mod builder_tools;
+mod builder_tools_connection_reads;
+pub mod bus;
+pub mod catalogue;
+mod copilot_bus;
+mod draft_store;
+pub mod memory_tools;
+pub mod node_contracts;
+pub mod ops;
+pub(crate) mod registration;
+mod schemas;
+mod store;
+/// The tinyflows engine seam (formerly `crate::tinyflows`).
+pub mod tinyflows;
+
+// Portable catalog vocabulary is imported directly from `tinyflows-catalog`.
+
+pub use schemas::{
+ all_controller_schemas as all_flows_controller_schemas,
+ all_registered_controllers as all_flows_registered_controllers,
+};
+// `kv_get`/`kv_set` are re-exported (not just `pub(crate)`-visible within this
+// domain's own module tree) because `tinyflows_sqlite::flows::SqliteStateStore`
+// (built in `crates/openhuman-core/src/flows/tinyflows/caps/ops.rs`) lives in a sibling module and needs
+// them to implement `tinyflows::caps::StateStore` without duplicating the
+// `flow_state` table's persistence logic.
+// `upsert_flow_run_step` is likewise re-exported for the tinyflows seam: the
+// live run observer (`tinyflows::observability::FlowRunObserver`, issue G2)
+// lives in the sibling `tinyflows` domain and persists each finished step onto
+// the `flow_runs` row through this function as the run executes.
+pub use store::{kv_get, kv_set, upsert_flow_run_step};
+pub use {node_contracts::all_node_kind_contracts, node_contracts::node_kind_contract};
+// Flow memory scoping (`flow:<id>` tags over memory v2) lives in
+// `memory_tools`, the sibling that owns the agent tools; the digest
+// subscriber, `flows_delete` and the tinyflows `memory` node adapter reach the
+// same helpers through these re-exports so every caller tags identically.
+pub use memory_tools::{
+ FLOWS_TAG, cross_flow_filter, flow_filter, flow_key_of, flow_key_tag, flow_meta, flow_tag,
+ forget_matching, remember_keyed,
+};
diff --git a/crates/openhuman-core/src/flows/node_contracts.rs b/crates/openhuman-core/src/flows/node_contracts.rs
index e69de29bb2..57178d4daf 100644
--- a/crates/openhuman-core/src/flows/node_contracts.rs
+++ b/crates/openhuman-core/src/flows/node_contracts.rs
@@ -0,0 +1,183 @@
+//! Host overlay on the tinyflows node-kind catalog (P1.2 / audit finding F2).
+//!
+//! The portable, model-level contracts live in the tinyflows crate
+//! ([`tinyflows::catalog`]) — config fields, ports, examples, and the
+//! structural gotchas that are true of the DSL everywhere. This module is the
+//! **thin host layer**: it takes those contracts and appends the facts only
+//! *this* host knows — what a `tool_call` slug resolves to (a Composio action
+//! slug or an `oh:` native tool), that a Composio result is wrapped in `data`,
+//! how an `agent` node receives its data (`input_context`), and which trigger
+//! kinds actually dispatch here. Keeping the vendor-specific knowledge here
+//! preserves tinyflows' host-agnostic invariant.
+//!
+//! The `list_node_kinds` / `get_node_kind_contract` agent tools and the
+//! `propose_workflow` description all read the *overlaid* view via
+//! [`all_node_kind_contracts`] / [`node_kind_contract`].
+
+use tinyflows_bus::node_kinds::NodeKindContract;
+
+/// Appends this host's vendor-specific caveats to a portable tinyflows
+/// contract. One arm per kind that has host-owned facts; the rest pass through
+/// unchanged.
+fn apply_host_overlay(contract: NodeKindContract) -> NodeKindContract {
+ match contract.kind.as_str() {
+ "trigger" => contract
+ .with_note(
+ "In THIS host only manual / schedule / app_event actually dispatch today; the \
+ other kinds save but never self-run (flows_validate warns).",
+ )
+ .with_note(
+ "trigger_kind=app_event also needs config.toolkit + config.trigger_slug (the \
+ Composio app + event to match).",
+ ),
+ "agent" => contract
+ .with_note(
+ "Data reaches the agent via config.input_context — an explicit =-binding: \
+ \"=item\" (direct predecessor), \"=items\" (all inputs, for a fan-in), or \
+ \"=nodes.<id>.item.json\" (a specific upstream node). The agent has NO automatic \
+ access to the upstream item.",
+ )
+ .with_note(
+ "config.prompt must be PLAIN natural-language text — no leading = and no .item \
+ woven into the prose. A prompt written as a =expression built from prose silently \
+ resolves to null and hands the agent an EMPTY prompt (rejected by the \
+ binding-resolvability gate).",
+ )
+ .with_note(
+ "execution=per_item runs a FULL harness agent (own model context, own tool loop) \
+ per input item, so it is far more expensive than a per_item tool_call — fan out \
+ over a list you have already narrowed, not a raw fetch. In THIS host \
+ simultaneous harness turns are additionally capped process-wide (8 by default, \
+ OPENHUMAN_FLOWS_MAX_PARALLEL_AGENTS): a higher config.concurrency is throttled \
+ to that ceiling, never rejected, so the run still completes.",
+ ),
+ "tool_call" => contract
+ .with_note(
+ "config.slug is a real Composio action slug (from search_tool_catalog, e.g. \
+ GMAIL_SEND_EMAIL) OR oh:<tool_name> for a native OpenHuman tool (e.g. \
+ oh:web_search). A hallucinated/typo'd slug is a hard reject.",
+ )
+ .with_note(
+ "Before wiring, call get_tool_contract { slug }: wire EVERY required_arg into \
+ config.args using the input_schema's REAL property names (a guessed key is \
+ rejected). Composio actions also need config.connection_ref for the account; oh: \
+ tools do not.",
+ )
+ .with_note(
+ "A Composio tool_call's output is wrapped in `data` (ComposioExecuteResponse) — \
+ bind downstream as =nodes.<id>.item.json.data.<field>, NOT .item.json.<field>. To \
+ split_out over its result list, use get_tool_contract's primary_array_path \
+ prefixed with `json.` (e.g. \"json.data.messages\").",
+ ),
+ "http_request" => contract.with_note(
+ "config.connection_ref is an http_cred:<name> credential for authentication.",
+ ),
+ "code" => contract.with_note(
+ "A code node's output is NOT `data`-wrapped (unlike a Composio tool_call) — bind \
+ downstream as =nodes.<id>.item.json.<field>.",
+ ),
+ "split_out" => contract.with_note(
+ "For a Composio source whose get_tool_contract primary_array_path is null, do NOT \
+ default the path to \"json.data\" (that targets the whole payload container and \
+ yields one item) — probe the real array path with get_tool_output_sample instead.",
+ ),
+ "memory" => contract.with_note(
+ "scope: \"flow\" reads/writes the SAME per-flow memory namespace the \
+ flow_memory_recall / flow_memory_remember agent tools use — a memory[remember] \
+ node and a flow_memory_remember tool call inside an agent node on the same flow \
+ see each other's writes. For exact \"process each item once\" dedup, use a dedup \
+ node instead — semantic recall is similarity-ranked, not an exact membership check, \
+ so a recall→condition graph cannot safely express it.",
+ ),
+ "dedup" => contract
+ .with_note(
+ "Commit is run-LEVEL, not node-level: the host settles every dedup node in the \
+ flow off the run's single terminal FlowRunFinished status. Only \
+ completed/completed_with_warnings unions this run's tentative keys into \
+ committed for EVERY dedup node that ran; EVERY other status — \
+ failed/cancelled/interrupted, unknown, or any status this host doesn't \
+ recognize yet — releases tentative for ALL of them (untouched committed), so \
+ the whole run's items retry next time — one node failing mid-run releases every \
+ dedup node's tentative in that run, not just the failing one's.",
+ )
+ .with_note(
+ "Canonical placement: split_out → dedup [key=\"=item.id\"] → …action…, i.e. one \
+ dedup node right after the items are produced, keyed on a stable id that exists \
+ at that point (issue number, message id, url), placed BEFORE the action. It \
+ already marks a key seen only after the run succeeds, so don't also wire a \
+ separate memory remember/condition dedupe graph alongside it.",
+ ),
+ "loop" => contract
+ .with_note(
+ "Every pass through the body costs what the body costs. A loop whose body \
+ contains an agent node runs a full agent turn per iteration, so max_iterations \
+ is a spend bound as much as a correctness one — prefer the smallest cap that \
+ can finish the job, and an `=`-expression `condition` so the loop stops as soon \
+ as the work is done rather than always running to the cap.",
+ )
+ .with_note(
+ "A sub_workflow node is the other way to repeat work, and the two bound \
+ differently: this node's max_iterations counts passes within one run (default \
+ 25), while nested sub_workflow runs are bounded by max_sub_workflow_depth on \
+ the ROOT graph's trigger (default 8). Reach for a loop to repeat a section, \
+ and for sub_workflow to reuse a whole flow.",
+ ),
+ "spawn" => contract
+ .with_note(
+ "config.slug for target=tool follows the SAME rule as a tool_call: a real \
+ Composio action slug (with config.connection_ref for the account) or \
+ oh:<tool_name> for a native OpenHuman tool. Call get_tool_contract first and \
+ wire every required_arg into config.args.",
+ )
+ .with_note(
+ "THIS host wires a TaskRunner, so spawned work genuinely overlaps. It is \
+ in-process only: tickets do not survive a core restart, so a spawn whose gate \
+ would only be reached after one is a spawn whose result is lost — keep the \
+ spawn and its gate inside the same run.",
+ ),
+ "gate" => contract.with_note(
+ "wait_mode=\"suspend\" interrupts the run, and in THIS host an interrupted flow run \
+ is resumed through flows_resume against the durable checkpointer — so a suspended \
+ gate survives a restart where a polling one does not. Prefer it for anything \
+ waiting longer than seconds.",
+ ),
+ "scatter" => contract.with_note(
+ "Lanes multiply everything inside the region, including COST: a lane body \
+ containing an agent node runs a full harness turn per lane. This host additionally \
+ caps simultaneous harness turns process-wide (8 by default, \
+ OPENHUMAN_FLOWS_MAX_PARALLEL_AGENTS), so a 200-lane scatter over an agent node \
+ queues rather than running 200 wide — correct, but not the throughput the lane \
+ count suggests. Use config.lanes to chunk deliberately.",
+ ),
+ _ => contract,
+ }
+}
+
+/// Every node-kind contract with this host's overlay applied, in
+/// [`tinyflows::catalog::NODE_KINDS`] order.
+pub async fn all_node_kind_contracts(
+ config: &crate::config::Config,
+) -> Result<Vec<NodeKindContract>, String> {
+ let proxy = crate::modules::tinyflows::catalog_proxy(config).await?;
+ let contracts: Vec<NodeKindContract> = proxy
+ .call(tinyflows_bus::catalog::members::NODE_KINDS, ())
+ .await
+ .map_err(|error| error.wire_message())?;
+ Ok(contracts.into_iter().map(apply_host_overlay).collect())
+}
+
+/// The overlaid contract for one node kind, or `None` when `kind` is not one
+/// of [`tinyflows::catalog::NODE_KINDS`].
+pub async fn node_kind_contract(
+ config: &crate::config::Config,
+ kind: &str,
+) -> Result<Option<NodeKindContract>, String> {
+ Ok(all_node_kind_contracts(config)
+ .await?
+ .into_iter()
+ .find(|contract| contract.kind == kind))
+}
+
+#[cfg(test)]
+#[path = "node_contracts_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/node_contracts_tests.rs b/crates/openhuman-core/src/flows/node_contracts_tests.rs
index e69de29bb2..693f6cad81 100644
--- a/crates/openhuman-core/src/flows/node_contracts_tests.rs
+++ b/crates/openhuman-core/src/flows/node_contracts_tests.rs
@@ -0,0 +1,85 @@
+use super::*;
+use tinyflows_bus::node_kinds::NODE_KINDS;
+
+async fn contract(kind: &str) -> tinyflows_bus::node_kinds::NodeKindContract {
+ node_kind_contract(&crate::config::Config::default(), kind)
+ .await
+ .unwrap()
+ .unwrap()
+}
+
+#[tokio::test]
+async fn overlay_preserves_every_kind_from_the_catalog_bus() {
+ let contracts = all_node_kind_contracts(&crate::config::Config::default())
+ .await
+ .unwrap();
+ assert_eq!(contracts.len(), NODE_KINDS.len());
+ for kind in NODE_KINDS {
+ assert!(
+ contracts.iter().any(|contract| contract.kind == kind),
+ "missing {kind}"
+ );
+ }
+ assert!(
+ node_kind_contract(&crate::config::Config::default(), "not_a_kind")
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn memory_overlay_adds_flow_memory_coherence_facts_and_redirects_dedup_to_its_own_node() {
+ let c = contract("memory").await;
+ let notes = c.notes.join("\n");
+ assert!(notes.contains("flow_memory_recall"), "{notes}");
+ assert!(notes.contains("flow_memory_remember"), "{notes}");
+ assert!(notes.contains("SAME per-flow memory namespace"), "{notes}");
+ assert!(!notes.contains("Canonical dedupe pattern"), "{notes}");
+ assert!(!notes.contains("item.json.found"), "{notes}");
+ assert!(
+ !notes.contains("deferred to a dedicated primitive"),
+ "{notes}"
+ );
+ assert!(notes.contains("use a dedup node instead"), "{notes}");
+}
+
+#[tokio::test]
+async fn dedup_overlay_teaches_run_level_commit_semantics_and_placement() {
+ let c = contract("dedup").await;
+ let notes = c.notes.join("\n");
+ assert!(notes.contains("FlowRunFinished"), "{notes}");
+ assert!(notes.contains("completed_with_warnings"), "{notes}");
+ assert!(notes.contains("failed/cancelled/interrupted"), "{notes}");
+ assert!(notes.contains("unknown"), "{notes}");
+ assert!(notes.contains("split_out → dedup"), "{notes}");
+}
+
+#[tokio::test]
+async fn tool_call_overlay_adds_host_composio_facts() {
+ let c = contract("tool_call").await;
+ let notes = c.notes.join("\n");
+ assert!(notes.contains("Composio"), "{notes}");
+ assert!(notes.contains("oh:"), "{notes}");
+ assert!(notes.contains("data"), "{notes}");
+ assert!(notes.contains("get_tool_contract"), "{notes}");
+}
+
+#[tokio::test]
+async fn agent_overlay_adds_input_context_guidance() {
+ let c = contract("agent").await;
+ assert!(c.notes.iter().any(|n| n.contains("input_context")));
+}
+
+#[tokio::test]
+async fn trigger_overlay_names_the_host_dispatch_set() {
+ let c = contract("trigger").await;
+ assert!(c.notes.iter().any(|n| n.contains("app_event")));
+}
+
+#[tokio::test]
+async fn merge_keeps_the_module_contract_without_a_host_overlay() {
+ let c = contract("merge").await;
+ assert!(!c.notes.iter().any(|note| note.contains("THIS host")));
+ assert!(!c.notes.iter().any(|note| note.contains("Composio")));
+}
diff --git a/crates/openhuman-core/src/flows/ops.rs b/crates/openhuman-core/src/flows/ops.rs
index e69de29bb2..cd7e4ee9c5 100644
--- a/crates/openhuman-core/src/flows/ops.rs
+++ b/crates/openhuman-core/src/flows/ops.rs
@@ -0,0 +1,180 @@
+//! Business logic for the `flows::` domain: validate-on-save CRUD plus the
+//! end-to-end `flows_run` / `flows_resume` path. Delegated to from
+//! `schemas.rs`'s `handle_*` RPC/CLI handlers, mirroring
+//! `crates/openhuman-core/src/cron/ops.rs`.
+//!
+//! The module is split by responsibility; every operation the rest of the
+//! crate reaches through `flows::ops::` is re-exported from here so the
+//! external paths are unchanged:
+//!
+//! | Submodule | Responsibility |
+//! | --- | --- |
+//! | `validation` | migrate/validate a raw graph, engine compatibility, `flows_validate` / `flows_import` |
+//! | `builder_gates` | the author-time hard-gate stack, `strict_gate`, `build_builder_proposal` |
+//! | `wiring_warnings` | advisory Composio wiring / output-field / `split_out.path` warnings |
+//! | `inference_readiness` | B45 provider-connectivity evaluation + probe cache |
+//! | `tool_contract_gate` | live-catalog slug / required-arg / arg-name gate |
+//! | `connection_ref_gate` | WS3 `connection_ref` toolkit + existence gate |
+//! | `definitions` | create / duplicate / get / list / delete + saved-graph lookups |
+//! | `updates` | update / history / rollback with optimistic concurrency |
+//! | `triggers` | enable/disable, trigger binding, boot reconciliation, trigger warnings |
+//! | `connections` | the `connection_ref` picker list and required-connection CTAs |
+//! | `run` | `flows_run` / `flows_run_detached` entry points and run prep |
+//! | `execution` | the shared run body, origin, Langfuse export, approval notification |
+//! | `resume` | `flows_resume` and the T-M1 graph pin |
+//! | `run_rows` | `flow_runs` row persistence, drop-guard finalizer, step settlement |
+//! | `run_management` | cancel, run listing/pruning, TTL and boot sweeps |
+//! | `discovery` | Flow Scout discovery and suggestion lifecycle |
+//! | `streaming` | copilot/scout progress bridge onto the web-channel socket |
+//! | `builder_toolset` | tools hidden from the `workflow_builder` belt per path |
+//! | `builder` | `flows_build` / `flows_build_cancel` and proposal extraction |
+//! | `trail_off` | the builder-convergence question backstop |
+//! | `approval_manifest` | save-time approval manifest |
+//! | `catalog` | tool-catalog search / contract RPCs |
+//! | `drafts` | core-managed local drafts |
+
+use std::collections::HashSet;
+use std::sync::{Arc, LazyLock};
+
+use chrono::Utc;
+use serde_json::{Value, json};
+use tinyflows::model::{NodeKind, TriggerKind, WorkflowGraph};
+use tinyflows::triggers::graph_trigger_warnings;
+// The save/run safety predicates are `tinyflows-catalog`'s: whether a graph
+// fires unattended, whether it can act on the world, whether it has anything to
+// do at all are properties of the graph, not of this host. Re-exported at
+// `ops::` scope because the agent tools and this module's tests already name
+// them there.
+pub(crate) use tinyflows_catalog::graph_policy::{
+ enforce_side_effect_approval, graph_has_actionable_nodes, trigger_is_automatic,
+};
+use tokio_util::sync::CancellationToken;
+
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource, with_origin};
+use crate::config::Config;
+use crate::core::Outcome;
+use crate::flows::bus;
+use crate::flows::draft_store;
+use crate::flows::store;
+use crate::security::approval::{ApprovalChatContext, ApprovalTurnContext, FlowRunContext};
+use tinyflows_catalog::build_registry;
+use tinyflows_catalog::run_registry;
+use tinyflows_catalog::types::{
+ FlowConnection, FlowRunStep, FlowRunTrigger, FlowSuggestion, SuggestionStatus,
+};
+use {tinyflows_catalog::Flow, tinyflows_catalog::FlowRun};
+
+/// Overall safety bound on a single `flows_run` / `flows_resume`. Individual
+/// capabilities have their own timeouts (HTTP, sandbox), but a hung LLM/tool
+/// call must never let the RPC block indefinitely — this caps the whole run.
+const FLOW_RUN_TIMEOUT_SECS: u64 = 600;
+
+/// How long a run may sit parked at a human-in-the-loop approval gate
+/// (`pending_approval`) before the TTL sweep expires it to a terminal
+/// `"cancelled"` (issue G4). Aligned with the agent tool-call `ApprovalGate`'s
+/// 10-minute fail-closed TTL (`crates/openhuman-core/src/security/approval/`), so a flow HITL gate a
+/// human never answers doesn't wedge a run — and its durable checkpoint —
+/// forever. The two are distinct mechanisms (flow runs execute as
+/// `TrustedAutomation { Workflow }`, which the tool-call gate lets through), so
+/// this is a dedicated flows-side TTL, not a reuse of the approval store's.
+const FLOW_PARKED_TTL_SECS: i64 = tinyflows_catalog::run_management::PARKED_RUN_TTL_SECS;
+
+/// T-M1 fail-closed refusal: the graph hash pinned when this run parked no
+/// longer matches the flow's current graph (`save_workflow` rewrote it while
+/// the approval sat pending). Distinct wording from every other
+/// `flows_resume` rejection so the UI/agent can tell a stale-approval refusal
+/// apart from an ordinary invalid-resume error and explain it plainly rather
+/// than surfacing a generic "resume failed".
+const GRAPH_CHANGED_SINCE_PARK_ERROR: &str = "the workflow changed after this run was paused — \
+ the pending approval no longer matches the current graph";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Phase 2 — autonomy-tier gating of acting flow nodes
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// A `flows_run` / `flows_resume` executes under a `TrustedAutomation { Workflow }`
+// origin (see `workflow_origin` below), but the *acting power* of a run is still
+// bounded by the user's `[autonomy]` tier — the same `SecurityPolicy`
+// (`crates/openhuman-core/src/security/`) the agent tool-loop honors, built via
+// `SecurityPolicy::from_config(&config.autonomy, …)` inside
+// `tinyflows::caps::build_capabilities`.
+//
+// Before an acting node dispatches, its capability adapter
+// (`crates/openhuman-core/src/flows/tinyflows/caps.rs::enforce_node_tier_gate`) maps the node to a
+// `CommandClass` and consults `SecurityPolicy::gate_decision`. `Block` refuses
+// outright (`[policy-blocked]` error, no dispatch); `Prompt`/`Allow` fall through
+// to the process-global `ApprovalGate`, which performs the human round-trip for
+// `Prompt` exactly as the agent tool-loop does. Node → class → per-tier decision:
+//
+// Flow node CommandClass read-only supervised full
+// ──────────── ──────────── ────────── ────────── ──────────
+// http_request Network BLOCK Prompt Prompt
+// code Write BLOCK Prompt Allow
+// tool_call (curation + (curated + Prompt Prompt/Allow¹
+// ApprovalGate) scope gate)
+// agent (llm) — (no acting side effect; not tier-gated, only the
+// inference/privacy chokepoint applies)
+// state (kv) — (host-internal flow KV; not an outbound act)
+//
+// ¹ tool_call routes through the deny-by-default curation/scope gate plus the
+// ApprovalGate rather than `gate_decision`; a Network-class Composio action
+// still prompts under supervised/full and the curation gate is the hard
+// allowlist. See `caps.rs::OpenHumanTools`.
+//
+// `Network` is never `Allow` in any tier (always `Prompt` when not blocked), so
+// even a full-tier http_request node prompts unless a pre-declared trust root /
+// `auto_approve` short-circuits the ApprovalGate — matching `curl`/`shell`.
+// `Write` (code) is `Allow` under full, so trusted automations run sandboxed
+// code unattended; read-only blocks both outright.
+
+mod approval_manifest;
+mod builder;
+mod builder_gates;
+mod builder_toolset;
+mod catalog;
+mod connection_ref_gate;
+mod connections;
+mod definitions;
+mod discovery;
+mod drafts;
+mod execution;
+mod inference_readiness;
+mod resume;
+mod run;
+mod run_management;
+mod run_rows;
+mod streaming;
+mod tool_contract_gate;
+mod trail_off;
+mod triggers;
+mod updates;
+mod validation;
+mod wiring_warnings;
+
+pub use approval_manifest::*;
+pub use builder::*;
+pub(crate) use builder_gates::*;
+use builder_toolset::*;
+pub use catalog::*;
+pub(crate) use connection_ref_gate::*;
+pub use connections::*;
+pub use definitions::*;
+pub use discovery::*;
+pub use drafts::*;
+use execution::*;
+pub(crate) use inference_readiness::*;
+pub use resume::*;
+pub use run::*;
+pub use run_management::*;
+use run_rows::*;
+pub use streaming::*;
+pub(crate) use tool_contract_gate::*;
+use trail_off::*;
+pub use triggers::*;
+pub use updates::*;
+pub use validation::*;
+pub(crate) use wiring_warnings::*;
+
+#[cfg(test)]
+#[path = "ops_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/ops/approval_manifest.rs b/crates/openhuman-core/src/flows/ops/approval_manifest.rs
index e69de29bb2..f6dc446bac 100644
--- a/crates/openhuman-core/src/flows/ops/approval_manifest.rs
+++ b/crates/openhuman-core/src/flows/ops/approval_manifest.rs
@@ -0,0 +1,158 @@
+use super::*;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Save-time approval manifest (consolidated pre-authorization card)
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Statically compute the "approval manifest" for a graph: every ApprovalGate
+/// permission a run of this flow will prompt for, so the save+enable card can
+/// ask for all of them in one shot instead of parking the run node-by-node.
+///
+/// Mirrors — never re-implements — the runtime gating in
+/// `crate::flows::tinyflows::caps` (`OpenHumanTools::invoke` /
+/// `OpenHumanHttp` / `OpenHumanCode`) and `approval::gate`'s Workflow-origin
+/// branch. Because Rule 2 (`enforce_side_effect_approval`) forces
+/// `require_approval: true` onto every graph with outbound side-effect nodes,
+/// a run parks on EVERY gated node that lacks `(flow_id, tool_name)` trust —
+/// so the manifest is precisely "the trust keys a fully pre-authorized run
+/// needs".
+///
+/// Entry `kind`s:
+/// - `"approvable"` — will park; pre-approving `tool_name` clears it.
+/// - `"blocked"` — the autonomy tier `Block`s the node's class outright
+/// (`enforce_node_tier_gate` refuses before dispatch); NOT approvable from
+/// the card — shown informationally so the user learns at save time, not
+/// at run time.
+/// - `"dynamic"` — the node's slug is an inline `=` expression resolved from
+/// runtime data; its trust key is unknowable at save time and it stays
+/// gated (best-effort disclosure).
+/// - `"agent"` — an `agent` node with an `agent_ref` runs a full harness turn
+/// whose inner tool calls cannot be enumerated statically; disclosed so the
+/// card never over-promises "zero prompts".
+///
+/// Curated Composio Read actions are excluded entirely: `CommandClass::Read`
+/// is `Allow` under every tier and the runtime skips the gate for them, so
+/// listing them would request grants that are never checked.
+pub async fn compute_approval_manifest(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ graph: &WorkflowGraph,
+) -> Result<Vec<Value>, String> {
+ compute_approval_manifest_json(
+ ctx,
+ config,
+ serde_json::to_value(graph).map_err(|e| e.to_string())?,
+ )
+ .await
+}
+
+async fn compute_approval_manifest_json(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<Vec<Value>, String> {
+ let registration =
+ crate::flows::authoring_host::register(std::sync::Arc::new(config.clone()), ctx.clone())
+ .await?;
+ let proxy = crate::modules::tinyflows::catalog_proxy(config).await?;
+ let entries: Vec<Value> = proxy
+ .call(
+ tinyflows_bus::catalog::members::APPROVAL_MANIFEST,
+ &(tinyflows_bus::catalog::ApprovalManifestRequest {
+ graph,
+ native_prefix: crate::flows::tinyflows::caps::NATIVE_TOOL_PREFIX.into(),
+ host: registration.catalog.clone(),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ tracing::debug!(target: "flows", entries = entries.len(), "[flows] approval manifest computed");
+ Ok(entries)
+}
+
+/// Approval manifest for a portable graph payload from the Copilot bus.
+pub(crate) async fn approval_manifest_json(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<Vec<Value>, String> {
+ compute_approval_manifest_json(ctx, config, graph).await
+}
+
+/// RPC: the approval manifest for a saved flow (by `id`) or a candidate
+/// `graph`, joined against the flow's existing `flow_tool_trust` grants so
+/// the save+enable card can ask only for what's missing.
+///
+/// With the approval gate uninstalled (`OPENHUMAN_APPROVAL_GATE=0`) nothing
+/// ever parks and nothing was ever granted, so `missing` and `already_trusted`
+/// are both empty by definition and the card never shows — `gate_installed:
+/// false` is the only signal in that case.
+pub async fn flows_approval_manifest(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ id: Option<&str>,
+ graph_json: Option<Value>,
+) -> Result<Outcome<Value>, String> {
+ tracing::debug!(target: "flows", id = ?id, has_graph = graph_json.is_some(), "[flows] flows_approval_manifest: entry");
+ let (graph, flow_id) = match (id, graph_json) {
+ (Some(id), _) => {
+ let flow = store::get_flow(config, id)
+ .map_err(|e| e.to_string())?
+ .ok_or_else(|| format!("flow not found: {id}"))?;
+ // `store::get_flow` already returns a migrated, deserialized graph.
+ (
+ serde_json::to_value(flow.graph).map_err(|e| e.to_string())?,
+ Some(id.to_string()),
+ )
+ }
+ (None, Some(graph_json)) => (graph_json, None),
+ (None, None) => return Err("provide 'id' or 'graph'".to_string()),
+ };
+
+ let entries = compute_approval_manifest_json(ctx, config, graph).await?;
+
+ let gate = crate::security::approval::ApprovalGate::try_global();
+ let gate_installed = gate.is_some();
+ let trusted: HashSet<String> = match (&gate, &flow_id) {
+ (Some(gate), Some(flow_id)) => gate
+ .list_flow_trust(flow_id)
+ .map_err(|e| e.to_string())?
+ .into_iter()
+ .collect(),
+ _ => HashSet::new(),
+ };
+
+ let (mut missing, mut already_trusted) = (Vec::new(), Vec::new());
+ if gate_installed {
+ for entry in &entries {
+ if entry.get("kind").and_then(Value::as_str) != Some("approvable") {
+ continue;
+ }
+ let Some(tool_name) = entry.get("tool_name").and_then(Value::as_str) else {
+ continue;
+ };
+ if trusted.contains(tool_name) {
+ already_trusted.push(tool_name.to_string());
+ } else {
+ missing.push(tool_name.to_string());
+ }
+ }
+ }
+
+ let log = format!(
+ "[flows] approval manifest: {} entr{}, {} missing grant(s)",
+ entries.len(),
+ if entries.len() == 1 { "y" } else { "ies" },
+ missing.len()
+ );
+ tracing::debug!(target: "flows", entries = entries.len(), missing = missing.len(), gate_installed, "[flows] flows_approval_manifest: exit");
+ Ok(Outcome::single_log(
+ json!({
+ "entries": entries,
+ "missing": missing,
+ "already_trusted": already_trusted,
+ "gate_installed": gate_installed,
+ }),
+ log,
+ ))
+}
diff --git a/crates/openhuman-core/src/flows/ops/builder_gates.rs b/crates/openhuman-core/src/flows/ops/builder_gates.rs
index e69de29bb2..31640a449d 100644
--- a/crates/openhuman-core/src/flows/ops/builder_gates.rs
+++ b/crates/openhuman-core/src/flows/ops/builder_gates.rs
@@ -0,0 +1,476 @@
+use super::*;
+use crate::core::runtime::DispatchCtx;
+
+/// The single canonical definition of the builder hard-gate stack: the
+/// author-time gates that reject (not warn) a graph an agent must not propose
+/// or persist — engine compatibility, binding-resolvability, agent-ref
+/// resolvability, connection-ref, tool-contract, and required-arg
+/// resolvability, in increasing cost order.
+///
+/// Returns an empty `Vec` when the graph passes; otherwise the first failing
+/// gate's node-level error messages (short-circuiting, so an expensive later
+/// gate never runs on a graph already known to be broken). Every plane that
+/// gates an agent-authored graph — `build_builder_proposal` (propose / revise /
+/// edit), `save_workflow`, and the `strict` create/update RPC path — routes
+/// through here, so they cannot drift (audit F3: agent saves and UI saves used
+/// to validate differently).
+///
+/// Assumes `graph` is already structurally valid (run
+/// `validate_and_migrate_graph` / `validate_all` first) — these gates check
+/// resolvability/contracts on a compilable graph.
+///
+/// Author-gate for `oh:storage_upload_file`: its literal `path` arg must be
+/// workspace-relative. Uploads are confined to the agent workspace by the
+/// runtime `resolve_upload_path` (a canonicalized path that escapes `action_dir`
+/// is rejected), so an absolute path like `/tmp/report.html` or one climbing out
+/// with `..` cannot work — it fails mid-run at the upload step. The prompt tells
+/// the builder to use a relative path, but the model reliably ignores that and
+/// copies an absolute path from a prior flow's example, so this enforces it in
+/// code (a hard, actionable author-gate) rather than trusting the prose.
+///
+/// Only LITERAL paths are checked: a `=`-expression resolves from upstream data
+/// at runtime and is out of scope here (the runtime check still applies). An
+/// absent `path` is left to the required-arg gate.
+pub(crate) fn validate_upload_paths(graph: &WorkflowGraph) -> Vec<String> {
+ const UPLOAD_SLUG: &str = "oh:storage_upload_file";
+ let mut errors = Vec::new();
+ for node in &graph.nodes {
+ if node.kind != NodeKind::ToolCall {
+ continue;
+ }
+ if node.config.get("slug").and_then(Value::as_str) != Some(UPLOAD_SLUG) {
+ continue;
+ }
+ let Some(raw) = node
+ .config
+ .get("args")
+ .and_then(|a| a.get("path"))
+ .and_then(Value::as_str)
+ else {
+ continue;
+ };
+ let path = raw.trim();
+ // Dynamic (resolved at runtime) or absent — not a literal we can check here.
+ if path.is_empty() || path.starts_with('=') {
+ continue;
+ }
+ let escapes_via_parent = path.split(['/', '\\']).any(|seg| seg == "..");
+ if std::path::Path::new(path).is_absolute() || escapes_via_parent {
+ errors.push(format!(
+ "Node '{}': `oh:storage_upload_file` path `{path}` must be workspace-relative \
+ (e.g. `report.html`). Uploads are confined to the agent workspace, so an \
+ absolute path (`/tmp/...`, `/Users/...`) or one escaping with `..` is rejected \
+ at run time. Use a relative path, and have the producing node write the file to \
+ that same relative path.",
+ node.id
+ ));
+ }
+ }
+ errors
+}
+
+pub(crate) async fn run_builder_gates(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: &WorkflowGraph,
+) -> Vec<String> {
+ // The stack order, short-circuiting and mock-run preflight are
+ // `tinyflows::gates::builder_failures`'; the host supplies the stages that
+ // depend on its vocabulary (agent registry, connections, tool catalog).
+ //
+ // Provider connectivity (B45) is deliberately NOT a stage: it is an advisory
+ // `inference_status` on the proposal payload and a run-time rejection, so a
+ // graph that is only "not runnable yet" can still be shown to the user.
+ let host = match crate::flows::authoring_host::register(
+ std::sync::Arc::new(config.clone()),
+ ctx.clone(),
+ )
+ .await
+ {
+ Ok(host) => host,
+ Err(error) => return vec![format!("builder gate could not complete: {error}")],
+ };
+ let result = async {
+ let proxy = crate::modules::tinyflows::authoring_proxy(config).await?;
+ let graph = serde_json::to_value(graph).map_err(|error| error.to_string())?;
+ proxy
+ .call::<Vec<String>>(
+ tinyflows_bus::methods::BUILDER_FAILURES,
+ &(
+ graph,
+ host.authoring.clone(),
+ vec![crate::flows::tinyflows::caps::NATIVE_TOOL_PREFIX.to_string()],
+ ),
+ )
+ .await
+ .map_err(|error| error.wire_message())
+ }
+ .await;
+ match result {
+ Ok(failures) => failures,
+ Err(error) => {
+ tracing::warn!(
+ target: "flows",
+ %error,
+ "[flows] builder gates: host stage failed — reporting it as a gate failure"
+ );
+ vec![format!("builder gate could not complete: {error}")]
+ }
+ }
+}
+
+/// Strict-mode gate for the create/update RPC path (audit F3): validates
+/// `graph_json` structurally (surfacing every error at once) and then runs the
+/// same [`run_builder_gates`] the agent tools enforce, returning `Err` with a
+/// combined, model-consumable message if anything fails.
+///
+/// The UI/RPC create/update path stays permissive by default (a human editing
+/// on the canvas may save a work-in-progress graph); passing `strict: true`
+/// opts that call into the *same* gates an agent save must pass, so the two
+/// planes converge on one definition instead of diverging.
+pub(crate) async fn strict_gate(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph_json: &Value,
+) -> Result<(), String> {
+ let graph = validate_and_migrate_graph(ctx, config, graph_json.clone())
+ .await
+ .map_err(|error| {
+ format!("strict validation failed — the graph is structurally invalid:\n{error}")
+ })?;
+ let gate_errors = run_builder_gates(ctx, config, &graph).await;
+ if !gate_errors.is_empty() {
+ return Err(format!(
+ "strict validation failed:\n{}",
+ gate_errors.join("\n\n")
+ ));
+ }
+ Ok(())
+}
+
+/// Runs the full builder hard-gate stack on an already structurally-valid
+/// `graph` and, if it passes, builds the `workflow_proposal` payload the
+/// propose/revise/edit tools all return.
+///
+/// The single home for the gate sequence (`tinyflows::gates::builder_failures`) plus
+/// summary/warning assembly,
+/// so `revise_workflow` and `edit_workflow` cannot drift. `retry_tool` names
+/// the tool in the "fix … and call `<tool>` again" guidance so each caller's
+/// error text points the agent back at the right tool.
+///
+/// `draft_id` / `flow_id` are OPTIONAL persistence-state context echoed onto
+/// the payload (the draft this proposal's edit lives on, and the saved flow it
+/// derives from / targets). The payload ALWAYS carries `"persisted": false` so
+/// a proposal can never be mistaken for a save confirmation — the exact false
+/// belief the WS2 audit caught (an agent read a proposal as "written onto the
+/// saved flow"). Actual persistence only happens via `save_workflow` /
+/// `create_workflow` / `flows_draft_promote`.
+///
+/// Returns `Ok(payload)` on success, or `Err(message)` with a
+/// model-consumable, fix-and-retry error when a gate rejects the graph. The
+/// caller is responsible for structural validation (`validate_and_migrate_graph`
+/// / `validate_all`) *before* calling this — these gates assume a compilable
+/// graph.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn build_builder_proposal(
+ ctx: &DispatchCtx,
+ config: &Config,
+ retry_tool: &str,
+ name: &str,
+ graph: &WorkflowGraph,
+ require_approval: bool,
+ revision: bool,
+ instruction: Option<String>,
+ draft_id: Option<String>,
+ flow_id: Option<String>,
+) -> Result<Value, String> {
+ // The full builder hard-gate stack, run through the single canonical
+ // runner so every proposal/save/strict-RPC path gates identically (F3).
+ let gate_errors = run_builder_gates(ctx, config, graph).await;
+ if !gate_errors.is_empty() {
+ return Err(format!(
+ "{}\n\nFix these and call {retry_tool} again.",
+ gate_errors.join("\n\n")
+ ));
+ }
+
+ let summary = tinyflows::summary::summarize(graph);
+ let mut warnings = graph_trigger_warnings(graph);
+ warnings.extend(graph_wiring_warnings(config, graph).await);
+ // Connector onboarding (Phase 5, item 18): tell the proposal card which
+ // toolkits this graph needs and whether they're connected, so it can render
+ // "Connect <toolkit>" CTAs instead of a bare gate error later.
+ let required_connections = compute_required_connections(ctx, config, graph).await;
+ // B45 (design correction): the LLM-provider-connectivity evaluation is
+ // ADVISORY here, never a rejection — `run_builder_gates` above no longer
+ // includes it (that used to hard-block `propose_workflow`/`edit_workflow`
+ // on a graph the copilot couldn't then show the user at all — judge
+ // finding on live run 104aab90). So `evaluation.status` here can
+ // legitimately be `"ready"`, `"signed_out"`, `"provider_not_configured"`,
+ // or `"error"` — the UI renders a "Connect a provider" / "Sign in" CTA
+ // for the non-ready cases, alongside the toolkit-connection CTAs above.
+ // The graph is proposed regardless of this value. Computed via the same
+ // shared, cached evaluator the run-time preflight (`validate_inference_readiness`
+ // in `run_flow_body`) consumes, so a run right after this proposal reads
+ // the cached result instead of re-probing the network.
+ let inference_readiness = evaluate_inference_readiness(ctx, config, graph).await;
+ let graph_value = serde_json::to_value(graph).map_err(|e| e.to_string())?;
+
+ tracing::info!(
+ target: "flows",
+ %name,
+ node_count = graph.nodes.len(),
+ require_approval,
+ warning_count = warnings.len(),
+ revision,
+ "[flows] build_builder_proposal: proposal ready for user review"
+ );
+
+ let mut payload = json!({
+ "type": "workflow_proposal",
+ "revision": revision,
+ // A proposal is NEVER a persisted flow — it is a candidate the user
+ // still has to accept/save. Stamp this unconditionally so the payload
+ // can't be misread as a save confirmation (WS2 audit).
+ "persisted": false,
+ "name": name,
+ "graph": graph_value,
+ "require_approval": require_approval,
+ "summary": summary,
+ "warnings": warnings,
+ "required_connections": required_connections,
+ });
+ // Only present when the graph has at least one applicable `agent` node;
+ // a tool_call-only graph omits both fields entirely rather than claiming
+ // a meaningless "ready".
+ if let Some(evaluation) = inference_readiness {
+ payload["inference_status"] = json!(evaluation.status);
+ if let Some(message) = evaluation.message {
+ payload["inference_message"] = json!(message);
+ }
+ }
+ if let Some(instruction) = instruction {
+ payload["instruction"] = json!(instruction);
+ }
+ // Echo the persistence-state handles so the agent can iterate/persist
+ // against the right ids (the draft the edit lives on; the flow it targets).
+ if let Some(draft_id) = draft_id {
+ payload["draft_id"] = json!(draft_id);
+ }
+ if let Some(flow_id) = flow_id {
+ payload["flow_id"] = json!(flow_id);
+ }
+ Ok(payload)
+}
+
+/// Decode the Copilot bus's portable graph payload and run the host-owned
+/// proposal gates without exposing engine types through the callback adapter.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn build_builder_proposal_json(
+ ctx: &DispatchCtx,
+ config: &Config,
+ retry_tool: String,
+ name: String,
+ graph: Value,
+ require_approval: bool,
+ revision: bool,
+ instruction: Option<String>,
+ draft_id: Option<String>,
+ flow_id: Option<String>,
+) -> Result<Value, String> {
+ let graph = validate_and_migrate_graph(ctx, config, graph).await?;
+ build_builder_proposal(
+ ctx,
+ config,
+ &retry_tool,
+ &name,
+ &graph,
+ require_approval,
+ revision,
+ instruction,
+ draft_id,
+ flow_id,
+ )
+ .await
+}
+
+/// Run the configured builder gates on the Copilot bus's portable graph payload.
+pub(crate) async fn run_builder_gates_json(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<Vec<String>, String> {
+ let graph = validate_and_migrate_graph(ctx, config, graph).await?;
+ Ok(run_builder_gates(ctx, config, &graph).await)
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Agent-ref resolvability gate: an `agent` node's `agent_ref` must name a
+// real agent, not the runtime's `RegistryFallback` "unknown agent_ref" case
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// `run_via_registry_fallback` (`tinyflows/caps.rs`) hard-errors mid-run with
+// "unknown agent_ref '…'" the moment an `agent` node's `config.agent_ref`
+// doesn't resolve to either a harness `AgentDefinition` or a custom agent
+// registry entry. Today that is the FIRST time an author finds out — the
+// graph proposes, saves, and even passes every other builder gate, then
+// fails on the very node whose whole job was to run. This gate moves that
+// same check to propose/edit/save time so a broken `agent_ref` is rejected
+// before it's ever persisted, using the exact resolution the runtime uses
+// (`route_for_agent_ref` + `agent_registry::get_agent`) rather than
+// re-implementing it.
+//
+// A plain `agent` node with NO `agent_ref` is unaffected (and must stay
+// that way) — it runs on the default LLM completion (`caps.llm`), never
+// touches `OpenHumanAgentRunner`'s routing at all, so there is nothing to
+// resolve.
+
+/// Rejects an `agent` node whose `config.agent_ref` would hit the runtime's
+/// `RegistryFallback` "unknown agent_ref" hard error mid-run
+/// (`run_via_registry_fallback` in `tinyflows/caps.rs`) — a real ref is one
+/// that resolves via [`crate::flows::agent_route::route_for_agent_ref`]
+/// to a harness [`AgentDefinition`](crate::agent::harness::host_definition::AgentDefinition)
+/// (`AgentRoute::Harness`), OR — when it routes to `AgentRoute::RegistryFallback`
+/// — resolves to an *enabled*
+/// [`AgentRegistryEntry`](crate::agent::registry::AgentRegistryEntry)
+/// via [`crate::agent::registry::get_agent`]. Both are exactly the
+/// checks `OpenHumanAgentRunner::run_agent` performs at run time, reused here
+/// rather than duplicated so the two planes cannot drift.
+///
+/// A node with no `agent_ref` (or a blank one) is a plain agent node — it
+/// runs on the default LLM completion, never reaches this routing at all —
+/// and is skipped, not rejected. A registry lookup failure (e.g. config
+/// unavailable) fails OPEN (skipped, logged) like the sibling
+/// `validate_connection_refs` gate: this gate must never false-reject a
+/// graph because of a transient local read.
+///
+/// Takes `config` for two reasons. First (CodeRabbit/Codex review on #5114):
+/// one-shot contexts — the generic `openhuman <namespace> <function>` CLI
+/// dispatcher (`default_state()`, no bootstrap), cron, tests — may reach this
+/// gate before the full server bootstrap has called
+/// [`AgentDefinitionRegistry::init_global`]. Without it, `route_for_agent_ref`
+/// sees an empty global registry and routes EVERY ref — including a real
+/// workspace-TOML harness definition — to `RegistryFallback`, which then only
+/// checks the custom agent registry and would reject a valid harness agent
+/// as unknown. So this gate defensively (re-)initialises the harness registry
+/// itself, same idempotent (`OnceLock`) idiom as
+/// other lazy registry users, before resolving any ref — the two planes
+/// (author-time gate and `OpenHumanAgentRunner::run_agent` at actual run
+/// time) then always see the same registry state. Second, it threads through
+/// to `agent_registry::get_agent`'s underlying config load.
+///
+/// Also lazily caches the custom agent registry snapshot on the first
+/// `RegistryFallback` node (CodeRabbit nitpick): a graph with several
+/// non-harness `agent_ref`s previously triggered one `config_rpc::
+/// load_config_with_timeout` per node; an all-`Harness`/no-custom-ref graph
+/// still never reads it at all.
+pub(crate) async fn validate_agent_refs(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: &WorkflowGraph,
+) -> Vec<String> {
+ use crate::agent::harness::host_definition::AgentDefinitionRegistry;
+ use crate::agent::registry::AgentRegistryEntry;
+ use crate::flows::agent_route::{AgentRoute, route_for_agent_ref};
+
+ let mut errors = Vec::new();
+ let mut harness_registry_init_attempted = false;
+ let mut custom_registry: Option<Result<Vec<AgentRegistryEntry>, String>> = None;
+
+ for node in &graph.nodes {
+ if node.kind != NodeKind::Agent {
+ continue;
+ }
+ let Some(agent_ref) = node.config.get("agent_ref").and_then(Value::as_str) else {
+ continue;
+ };
+ let agent_ref = agent_ref.trim();
+ if agent_ref.is_empty() {
+ continue;
+ }
+
+ if !harness_registry_init_attempted && AgentDefinitionRegistry::global().is_none() {
+ harness_registry_init_attempted = true;
+ if let Err(e) = AgentDefinitionRegistry::init_global(&config.workspace_dir) {
+ tracing::debug!(
+ target: "flows",
+ error = %e,
+ "[flows] agent-ref check: harness registry init failed — falling through \
+ to route resolution with whatever state is available"
+ );
+ }
+ }
+
+ match route_for_agent_ref(agent_ref) {
+ AgentRoute::Harness | AgentRoute::HostAgent => {
+ tracing::debug!(
+ target: "flows",
+ node = %node.id,
+ %agent_ref,
+ "[flows] agent-ref check: resolves to a harness or host agent definition"
+ );
+ }
+ AgentRoute::RegistryFallback => {
+ if custom_registry.is_none() {
+ custom_registry = Some(crate::agent::registry::list_agents(ctx, true).await);
+ }
+ match custom_registry.as_ref().expect("just populated") {
+ Ok(entries) => match entries.iter().find(|entry| entry.id == agent_ref) {
+ Some(entry) if entry.enabled => {
+ tracing::debug!(
+ target: "flows",
+ node = %node.id,
+ %agent_ref,
+ "[flows] agent-ref check: resolves to an enabled custom agent \
+ registry entry"
+ );
+ }
+ Some(_disabled) => {
+ tracing::warn!(
+ target: "flows",
+ node = %node.id,
+ %agent_ref,
+ "[flows] agent-ref check: agent_ref is registered but disabled — \
+ rejecting"
+ );
+ errors.push(format!(
+ "Node '{}': `agent_ref` `{agent_ref}` is registered but currently \
+ disabled — enable it (or pick another agent_ref via \
+ list_agent_definitions) before this node can run.",
+ node.id
+ ));
+ }
+ None => {
+ tracing::warn!(
+ target: "flows",
+ node = %node.id,
+ %agent_ref,
+ "[flows] agent-ref check: unknown agent_ref — neither a harness \
+ definition nor a custom agent registry entry — rejecting"
+ );
+ errors.push(format!(
+ "Node '{}': `agent_ref` `{agent_ref}` is not a real agent — it \
+ names neither a built-in agent definition nor a custom agent \
+ registry entry, and would fail at run time with an \"unknown \
+ agent_ref\" error. Call list_agent_definitions to see the real, \
+ selectable agent_ref values.",
+ node.id
+ ));
+ }
+ },
+ Err(e) => {
+ tracing::debug!(
+ target: "flows",
+ node = %node.id,
+ %agent_ref,
+ error = %e,
+ "[flows] agent-ref check: custom agent registry lookup unavailable — \
+ skipping (fail-open)"
+ );
+ }
+ }
+ }
+ }
+ }
+ errors
+}
diff --git a/crates/openhuman-core/src/flows/ops/catalog.rs b/crates/openhuman-core/src/flows/ops/catalog.rs
index e69de29bb2..ae5d554c72 100644
--- a/crates/openhuman-core/src/flows/ops/catalog.rs
+++ b/crates/openhuman-core/src/flows/ops/catalog.rs
@@ -0,0 +1,61 @@
+use super::*;
+
+#[cfg(test)]
+pub(crate) use crate::integrations::composio::catalog::toolkit_for_contract_slug;
+pub(crate) use crate::integrations::composio::catalog::{ContractLookupError, lookup_contract};
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Catalog RPCs for the UI (Phase 5, item 16) — one implementation, two consumers
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Searches the live Composio tool catalog (secret-free) — the RPC the in-canvas
+/// tool browser calls, reusing the exact same core as the agent's
+/// `search_tool_catalog` tool so the two can't drift.
+pub async fn flows_search_tool_catalog(
+ config: &Config,
+ query: &str,
+ toolkit: Option<&str>,
+ limit: usize,
+) -> Result<Outcome<Value>, String> {
+ tracing::debug!(target: "flows", %query, toolkit = toolkit.unwrap_or("<all>"), "[flows] flows_search_tool_catalog: searching live catalog");
+ let tools = crate::integrations::composio::builder_tools::search_live_catalog(
+ config, query, toolkit, limit,
+ )
+ .await;
+ Ok(Outcome::single_log(
+ json!({ "tools": tools }),
+ "tool catalog searched",
+ ))
+}
+
+/// Fetches one Composio action's full contract (secret-free) — the RPC the
+/// canvas tool browser calls to fill in an action's arg schema, reusing the same
+/// core as the agent's `get_tool_contract` tool.
+pub async fn flows_get_tool_contract(
+ config: &Config,
+ slug: &str,
+) -> Result<Outcome<Value>, String> {
+ let trimmed = slug.trim();
+ let (contract, runtime_gate) =
+ lookup_contract(config, slug)
+ .await
+ .map_err(|error| match error {
+ ContractLookupError::InvalidSlug { slug } => format!(
+ "Could not extract a toolkit from slug '{slug}' — it must look like \
+ '<TOOLKIT>_<ACTION>' (e.g. 'GMAIL_SEND_EMAIL')."
+ ),
+ ContractLookupError::CatalogUnavailable { toolkit } => {
+ format!("Could not fetch the live Composio catalog for toolkit '{toolkit}'.")
+ }
+ ContractLookupError::ActionNotFound { slug, toolkit } => format!(
+ "'{slug}' is not a real action in the '{toolkit}' toolkit's live catalog."
+ ),
+ })?;
+ let value = serde_json::to_value(&contract).map_err(|e| e.to_string())?;
+ tracing::debug!(target: "flows", slug = %trimmed, toolkit = %contract.toolkit, "[flows] flows_get_tool_contract: fetching contract");
+ let mut response = json!({ "contract": value });
+ if let Some(warning) = runtime_gate {
+ response["runtime_gate"] = json!(warning);
+ }
+ Ok(Outcome::single_log(response, "tool contract fetched"))
+}
diff --git a/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs b/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs
index e69de29bb2..bc36ce5531 100644
--- a/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs
+++ b/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs
@@ -0,0 +1,93 @@
+use super::*;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Connection-ref gate (WS3): a Composio tool_call's `connection_ref` must name
+// a real connected account of the RIGHT toolkit
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// Transcript audit: the user's connections were `twitter →
+// composio:twitter:ca_JX6QU88UfSk4`, `gmail → composio:gmail:ca_vX_WA8FsqNmE`,
+// `tiktok → composio:tiktok:ca_LPCp3WQpaDma`. The agent wired
+// `composio:twitter:ca_LPCp3WQpaDma` and `composio:gmail:ca_LPCp3WQpaDma` (the
+// TIKTOK id) onto the Twitter and Gmail tool_call nodes. dry_run / validate /
+// propose all returned ok:true — nothing cross-checked the id against the user's
+// real connections, nor the ref's toolkit segment against the slug — and it
+// would fail on the first real run. This gate closes that gap: it parses the
+// ref, enforces the toolkit segment matches the slug (needs no I/O), and — when
+// the live connection list is reachable — that the id names a real connected
+// account of that toolkit, naming the correct ref when it can.
+
+/// Hard gate: for every Composio `tool_call` node carrying a `connection_ref`,
+/// prove the ref names a real connected account of the SAME toolkit as the
+/// slug. Fetches the live connection list once (same source
+/// [`flows_list_connections`] reads) and delegates the pure matching to
+/// [`validate_connection_refs_against`].
+///
+/// Fail-open on I/O: if the Composio connection list is unreachable (backend
+/// outage), the id-existence check is SKIPPED (a `tracing::debug!` records it)
+/// so a real connection is never false-rejected during an outage — but the
+/// toolkit-mismatch check, which needs no I/O, still runs.
+pub(crate) async fn validate_connection_refs(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ graph: &WorkflowGraph,
+) -> Vec<String> {
+ let connections: Option<Vec<FlowConnection>> =
+ match crate::integrations::composio::ops::composio_list_connections(ctx, config).await {
+ Ok(outcome) => Some(build_flow_connections(
+ outcome.value.connections,
+ Vec::new(),
+ // Identity isn't needed for this existence/toolkit-mismatch
+ // check — only `connection_ref` and `toolkit` are read.
+ &[],
+ &Default::default(),
+ )),
+ Err(e) => {
+ tracing::debug!(
+ target: "flows",
+ error = %e,
+ "[flows] connection-ref check: composio connection list unavailable — \
+ skipping id-existence check (fail-open); toolkit-mismatch check still runs"
+ );
+ None
+ }
+ };
+ validate_connection_refs_against(graph, connections.as_deref())
+}
+
+/// Pure connection-ref validator (no I/O) so the gate's decision logic is
+/// unit-testable without a live Composio backend. `connections` is `Some(list)`
+/// when the live connection list was fetched (possibly empty — a genuine "no
+/// connections" state), or `None` when it was unavailable (fail-open: the
+/// id-existence check is skipped, only the toolkit-mismatch check runs).
+pub(super) fn validate_connection_refs_against(
+ graph: &WorkflowGraph,
+ connections: Option<&[FlowConnection]>,
+) -> Vec<String> {
+ use crate::integrations::composio::contract::validation::{
+ ConnectedAccountRef, ConnectionRefNode, validate_connection_refs as validate,
+ };
+
+ let nodes: Vec<_> = graph
+ .nodes
+ .iter()
+ .filter(|node| node.kind == NodeKind::ToolCall)
+ .filter_map(|node| {
+ Some(ConnectionRefNode {
+ id: node.id.clone(),
+ slug: node.config.get("slug")?.as_str()?.to_string(),
+ connection_ref: node.config.get("connection_ref")?.as_str()?.to_string(),
+ })
+ })
+ .collect();
+ let accounts = connections.map(|items| {
+ items
+ .iter()
+ .map(|item| ConnectedAccountRef {
+ connection_ref: item.connection_ref.clone(),
+ toolkit: item.toolkit.clone(),
+ })
+ .collect::<Vec<_>>()
+ });
+ validate(&nodes, accounts.as_deref())
+}
diff --git a/crates/openhuman-core/src/flows/ops/definitions.rs b/crates/openhuman-core/src/flows/ops/definitions.rs
index e69de29bb2..897a3b9399 100644
--- a/crates/openhuman-core/src/flows/ops/definitions.rs
+++ b/crates/openhuman-core/src/flows/ops/definitions.rs
@@ -0,0 +1,295 @@
+use super::*;
+
+/// Publishes a [`DomainEvent::FlowChanged`](crate::core::events::DomainEvent::FlowChanged)
+/// so an open Workflows list/canvas refetches (bridged to a `flow:changed`
+/// socket event) — the observability half of audit F6. Best-effort broadcast;
+/// `actor` is a coarse hint (`"system"` for RPC-driven changes today).
+pub(super) fn publish_flow_changed(flow_id: &str, kind: &str, actor: &str) {
+ tracing::debug!(target: "flows", %flow_id, kind, actor, "[flows] publishing FlowChanged");
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::FlowChanged {
+ flow_id: flow_id.to_string(),
+ kind: kind.to_string(),
+ actor: actor.to_string(),
+ });
+}
+
+/// Creates a new flow from a name and a raw graph JSON value.
+///
+/// Issue B29 (save/enable safety) — two server-side rules apply here,
+/// authoritative regardless of what the caller passed, so no creation path
+/// (prompt bar, scratch/template modal, proposal "save & enable", copilot
+/// `save_workflow`, …) can silently hand the user an armed, unattended
+/// automation:
+///
+/// - **Rule 1** ([`trigger_is_automatic`]): a graph whose trigger fires
+/// without a human in the loop (`schedule` / `app_event` / `webhook`)
+/// persists **disabled**. The user arms it explicitly via
+/// `flows_set_enabled` — the same toggle already used everywhere else. A
+/// `manual` trigger (or no trigger-kind discriminator at all) still
+/// persists enabled: it only ever runs via an explicit `flows_run`, so
+/// there is no surprise, and gating it would just add friction.
+///
+/// This means a caller that represents an explicit user-arming action
+/// (e.g. `WorkflowProposalCard`'s "Save & enable" click,
+/// `app/src/components/chat/WorkflowProposalCard.tsx`) must check the
+/// returned [`Flow`]'s `enabled` field and follow up with
+/// `flows_set_enabled(id, true)` when it comes back `false` — otherwise
+/// the button's own label lies to the user. That follow-up call is a
+/// legitimate, explicit enable, not the silent copilot auto-arm this rule
+/// exists to prevent (the copilot's `save_workflow` path has no such
+/// follow-up and stays disabled).
+/// - **Rule 2** ([`graph_has_outbound_side_effect`]): a graph containing any
+/// `tool_call` / `http_request` / `code` node — the three kinds that can
+/// produce a real outbound effect — forces `require_approval: true`,
+/// overriding whatever the caller passed. A read-only graph (only
+/// `trigger` / `agent` / `transform` / `condition` / data-flow nodes) is
+/// unaffected.
+///
+/// An enabled flow still has its automatic-dispatch side effect bound
+/// immediately (e.g. the schedule-trigger cron job registered), reusing the
+/// same [`bind_trigger`] helper `flows_set_enabled` uses — but per Rule 1
+/// that now only happens for a `manual`-triggered (or trigger-kind-less)
+/// flow. Best-effort, same as `flows_set_enabled`: a binding failure is
+/// logged, not fatal to create.
+pub async fn flows_create(
+ config: &Config,
+ name: String,
+ graph_json: Value,
+ require_approval: bool,
+) -> Result<Outcome<Flow>, String> {
+ let graph = validate_and_migrate_graph(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ graph_json,
+ )
+ .await?;
+
+ // Rule 1: automatic triggers create DISABLED — the user must arm them
+ // explicitly.
+ let enabled = !trigger_is_automatic(&graph);
+
+ // Rule 2: any outbound side-effect node forces require_approval, no
+ // matter what the caller asked for.
+ let (effective_require_approval, side_effect_forced) =
+ enforce_side_effect_approval(&graph, require_approval);
+ if side_effect_forced {
+ tracing::info!(
+ target: "flows",
+ %name,
+ "[flows] flows_create: forcing require_approval=true — graph contains outbound \
+ side-effect node(s) (tool_call / http_request / code)"
+ );
+ }
+
+ tracing::debug!(
+ target: "flows",
+ %name,
+ node_count = graph.nodes.len(),
+ enabled,
+ require_approval = effective_require_approval,
+ "[flows] flows_create: persisting new flow"
+ );
+ let flow = store::create_flow(config, name, graph, effective_require_approval, enabled)
+ .map_err(|e| e.to_string())?;
+
+ if flow.enabled {
+ tracing::debug!(target: "flows", flow_id = %flow.id, "[flows] flows_create: flow is enabled — binding automatic-dispatch trigger");
+ bind_trigger(config, &flow);
+ }
+
+ let mut logs = vec!["flow created".to_string()];
+ if !enabled {
+ let trigger_label = flow
+ .graph
+ .trigger()
+ .and_then(|t| t.config.get("trigger_kind"))
+ .and_then(Value::as_str)
+ .unwrap_or("automatic");
+ logs.push(format!(
+ "Flow created DISABLED because it has an automatic trigger ({trigger_label}). \
+ Enable it explicitly (flows_set_enabled) when you are ready for it to fire."
+ ));
+ }
+ if side_effect_forced {
+ logs.push(
+ "require_approval forced to true because the graph contains outbound side-effect \
+ nodes (tool_call / http_request / code)."
+ .to_string(),
+ );
+ }
+
+ publish_flow_changed(&flow.id, "created", "system");
+ Ok(Outcome::new(flow, logs))
+}
+
+/// Duplicates a saved flow: creates an independent copy of its graph under a
+/// new id/timestamps, with the name suffixed `" (copy)"`. The copy is created
+/// **disabled** (`enabled = false`) and therefore **not** schedule/app_event
+/// trigger-bound — unlike [`flows_create`], which binds a trigger for an
+/// enabled flow, this deliberately calls no [`bind_trigger`], so a duplicate
+/// can never immediately fire. Run history does not carry over. The user
+/// enables it explicitly (via `flows_set_enabled`) once they've reviewed the
+/// copy, at which point its trigger binds like any other flow.
+pub async fn flows_duplicate(config: &Config, id: &str) -> Result<Outcome<Flow>, String> {
+ let source = store::get_flow(config, id)
+ .map_err(|e| e.to_string())?
+ .ok_or_else(|| format!("flow '{id}' not found"))?;
+ let new_name = format!("{} (copy)", source.name);
+ tracing::debug!(target: "flows", source_id = %id, %new_name, "[flows] flows_duplicate: creating disabled, unbound copy");
+ let flow =
+ store::insert_duplicate_flow(config, &source, new_name).map_err(|e| e.to_string())?;
+ // Intentionally NO bind_trigger: a duplicate is disabled and must stay
+ // inert (no schedule/trigger dispatch) until the user enables it.
+ publish_flow_changed(&flow.id, "created", "system");
+ Ok(Outcome::single_log(
+ flow,
+ format!("flow duplicated from {id}"),
+ ))
+}
+
+/// Loads one flow by id.
+pub async fn flows_get(config: &Config, id: &str) -> Result<Outcome<Flow>, String> {
+ let flow = store::get_flow(config, id)
+ .map_err(|e| e.to_string())?
+ .ok_or_else(|| format!("flow '{id}' not found"))?;
+ Ok(Outcome::single_log(flow, format!("flow loaded: {id}")))
+}
+
+/// Loads a saved flow's portable [`WorkflowGraph`] by id, for the
+/// `sub_workflow`-by-`workflow_id` resolver capability
+/// (`tinyflows::caps::WorkflowResolver`, implemented in
+/// `crates/openhuman-core/src/flows/tinyflows/caps.rs`).
+///
+/// Returns `Ok(None)` when no flow with that id exists (the resolver turns that
+/// into a capability error naming the missing id), and `Err` only on a store
+/// failure. Kept sync (the underlying [`store::get_flow`] is sync) so the
+/// resolver can call it directly from its async method without a runtime hop.
+pub fn load_flow_graph(config: &Config, id: &str) -> Result<Option<WorkflowGraph>, String> {
+ tracing::debug!(target: "flows", flow_id = %id, "[flows] load_flow_graph: loading saved flow graph for sub_workflow resolver");
+ let graph = store::get_flow(config, id)
+ .map_err(|e| e.to_string())?
+ .map(|flow| flow.graph);
+ tracing::debug!(
+ target: "flows",
+ flow_id = %id,
+ found = graph.is_some(),
+ "[flows] load_flow_graph: resolver lookup complete"
+ );
+ Ok(graph)
+}
+
+/// Resolver-only saved-graph lookup. Authoring tools use [`load_flow_graph`]
+/// so a legacy draft can still be opened and repaired; execution resolves only
+/// graphs the current engine can run safely.
+pub(crate) async fn load_engine_compatible_flow_graph(
+ config: &Config,
+ id: &str,
+) -> Result<Option<WorkflowGraph>, String> {
+ let graph = load_flow_graph(config, id)?;
+ if let Some(graph) = graph.as_ref() {
+ ensure_config_aware_engine_compatible(config, graph)
+ .await
+ .map_err(|error| format!("workflow_id '{id}' is engine-incompatible: {error}"))?;
+ }
+ Ok(graph)
+}
+
+/// Lists every saved flow.
+///
+/// A corrupt or newer-schema-than-this-build `graph_json` row is skipped
+/// rather than failing the whole list (R-M4 — see `store::list_flow_rows`);
+/// when that happens it must not be silent, so a skip is both logged
+/// (`[flows]`-prefixed, id + error only — never row content) and surfaced in
+/// the RPC's `logs` so the UI can tell the user "N workflows could not be
+/// loaded" instead of silently rendering a shorter list than actually exists.
+pub async fn flows_list(config: &Config) -> Result<Outcome<Vec<Flow>>, String> {
+ let (flows, skipped) = store::list_flows(config).map_err(|e| e.to_string())?;
+ if skipped > 0 {
+ tracing::warn!(
+ target: "flows",
+ skipped,
+ loaded = flows.len(),
+ "[flows] flows_list: skipped corrupt/unmigratable flow_definitions rows"
+ );
+ Ok(Outcome::new(
+ flows,
+ vec![format!(
+ "flows listed ({skipped} workflow{} could not be loaded and were skipped)",
+ if skipped == 1 { "" } else { "s" }
+ )],
+ ))
+ } else {
+ Ok(Outcome::single_log(flows, "flows listed"))
+ }
+}
+
+/// Deletes a flow by id.
+///
+/// Removes the flow definition before unbinding its separately persisted
+/// automatic-dispatch trigger (e.g. the schedule-trigger job). Removing the
+/// flow first means a failed delete leaves its still-existing schedule intact.
+/// Best-effort: a lookup failure is logged and does not block the delete.
+pub async fn flows_delete(config: &Config, id: &str) -> Result<Outcome<Value>, String> {
+ flows_delete_with_remove(config, id, |config, id| {
+ store::remove_flow(config, id).map_err(|e| e.to_string())
+ })
+ .await
+}
+
+/// Delete implementation split at the fallible store operation so failure
+/// ordering can be exercised without corrupting the configured storage.
+pub(super) async fn flows_delete_with_remove(
+ config: &Config,
+ id: &str,
+ remove: impl FnOnce(&Config, &str) -> Result<(), String>,
+) -> Result<Outcome<Value>, String> {
+ let flow = match store::get_flow(config, id) {
+ Ok(Some(flow)) => Some(flow),
+ Ok(None) => None,
+ Err(e) => {
+ tracing::warn!(target: "flows", flow_id = %id, error = %e, "[flows] flows_delete: failed to load flow before unbind — proceeding with delete anyway");
+ None
+ }
+ };
+
+ remove(config, id)?;
+ if let Some(flow) = flow {
+ unbind_trigger(config, &flow);
+ }
+ tracing::debug!(target: "flows", flow_id = %id, "[flows] flows_delete: removed");
+
+ // Best-effort: purge the flow's pre-authorized tool trust with its row —
+ // a deleted flow must not leave dangling `flow_tool_trust` grants that a
+ // future flow reusing the same id (or a stale run) could inherit. Never
+ // fails the delete: the flow row is already gone regardless.
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ match gate.delete_flow_trust(id, None) {
+ Ok(removed) if removed > 0 => {
+ tracing::info!(target: "flows", flow_id = %id, removed, "[flows] flows_delete: purged flow tool trust grants");
+ }
+ Ok(_) => {}
+ Err(e) => {
+ tracing::warn!(target: "flows", flow_id = %id, error = %e, "[flows] flows_delete: failed to purge flow tool trust");
+ }
+ }
+ }
+
+ // Best-effort: forget this flow's memory along with its row — a deleted
+ // flow must not leave stray `flow_memory_remember` items or run digests
+ // behind. Memory off forgets nothing. Never fails the delete itself: the
+ // flow row is already gone by this point.
+ match crate::flows::forget_matching(config, crate::flows::flow_filter(id)).await {
+ Ok(forgotten) => {
+ tracing::debug!(target: "flows", flow_id = %id, forgotten, "[flows] flows_delete: forgot flow memory");
+ }
+ Err(error) => {
+ tracing::warn!(target: "flows", flow_id = %id, code = error.code(), %error, "[flows] flows_delete: failed to forget flow memory");
+ }
+ }
+
+ publish_flow_changed(id, "deleted", "system");
+ Ok(Outcome::new(
+ json!({ "id": id, "removed": true }),
+ vec![format!("flow removed: {id}")],
+ ))
+}
diff --git a/crates/openhuman-core/src/flows/ops/discovery.rs b/crates/openhuman-core/src/flows/ops/discovery.rs
index e69de29bb2..45a7e08d88 100644
--- a/crates/openhuman-core/src/flows/ops/discovery.rs
+++ b/crates/openhuman-core/src/flows/ops/discovery.rs
@@ -0,0 +1,170 @@
+use super::*;
+use crate::core::runtime::DispatchCtx;
+
+/// Persist suggestions received through the Copilot bus's portable wire shape.
+pub(crate) fn flows_suggestions_upsert_from_copilot(
+ config: &Config,
+ suggestions: Value,
+) -> Result<usize, String> {
+ let suggestions: Vec<FlowSuggestion> = serde_json::from_value(suggestions)
+ .map_err(|error| format!("invalid Copilot suggestions: {error}"))?;
+ store::upsert_suggestions(config, &suggestions).map_err(|error| error.to_string())
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Flow Scout — workflow discovery + suggestion lifecycle
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Overall safety bound on one `flows_discover` run. The `flow_discovery` agent
+/// reasons read-only over the user's data and ends by emitting
+/// `suggest_workflows`; its own `max_iterations` caps the loop, but a hung
+/// LLM/tool call must never let the RPC block indefinitely.
+///
+/// Matches [`FLOW_BUILD_TIMEOUT_SECS`] (600s): the session builder applies the
+/// `flow_discovery` definition's `effective_max_iterations()` (50, not the
+/// global default of 10) to this path (issue #4868), so a worst-case run at
+/// ~10s/iteration can take up to ~500s — the old 300s bound could clip a
+/// legitimate long discovery run before the iteration cap ever got a chance
+/// to (post-merge Codex P2 finding).
+const FLOW_DISCOVER_TIMEOUT_SECS: u64 = 600;
+
+/// The canned brief handed to the `flow_discovery` agent. The agent's own
+/// archetype prompt teaches the read → correlate → ground → emit loop; this is
+/// just the kick-off instruction for the on-demand "Discover" action.
+const FLOW_DISCOVER_PROMPT: &str = "Discover the most useful automations you could set up for me. \
+ Read what you can about how I work — my goals, recurring conversations, the people and apps I \
+ deal with, and the flows I already have — then propose a few concrete, buildable workflows. \
+ Ground each in something you actually observed about me, and end by calling suggest_workflows.";
+
+/// Runs the read-only `flow_discovery` agent ("Flow Scout") on demand: it reads
+/// the user's memory/threads/people/connections/existing flows, grounds a few
+/// automation ideas, and records them via the `suggest_workflows` tool (which
+/// persists to the `flow_suggestions` table). Returns the current set of active
+/// (`New`) suggestions after the run.
+///
+/// The agent is strictly read-only — its only write is `suggest_workflows`
+/// (`PermissionLevel::None`) — so this never persists, enables, or runs a flow.
+/// Turning a suggestion into a real flow is the user's separate "Build this"
+/// action, which routes to `workflow_builder`.
+pub async fn flows_discover(
+ ctx: &DispatchCtx,
+ config: &Config,
+ stream: Option<FlowStreamTarget>,
+) -> Result<Outcome<Vec<FlowSuggestion>>, String> {
+ use crate::agent::OpenHumanSessionHost;
+ use crate::agent::turn_origin::{AgentTurnOrigin, with_origin};
+
+ tracing::info!(
+ target: "flows",
+ streaming = stream.is_some(),
+ "[flows] flows_discover: starting Flow Scout discovery run"
+ );
+
+ // The registry must be initialised before building a named builtin agent
+ // (mirrors `agent_registry::ops::available_tools`); it is idempotent, so a
+ // second call from an already-booted core is a cheap no-op.
+ crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global(
+ &config.workspace_dir,
+ )
+ .map_err(|e| format!("failed to initialise agent registry: {e}"))?;
+
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(ctx, config, "flow_discovery")
+ .map_err(|e| format!("failed to build flow_discovery agent: {e:#}"))?;
+ agent.set_agent_definition_name("flow_discovery".to_string());
+
+ // When a chat thread is attached, stream the scout turn into it exactly like
+ // an interactive turn (see `FlowStreamTarget`). Best-effort — with no target
+ // the run stays headless, exactly as before.
+ if let Some(target) = &stream {
+ attach_flow_progress_bridge(ctx, &mut agent, target, "flows_discover", config);
+ agent.set_thread_id(Some(target.thread_id.as_str()));
+ }
+
+ // Run to completion under a CLI origin (an internal, user-initiated action —
+ // the approval gate must not fail-closed on it), bounded by a wall-clock
+ // timeout so a hung provider call can't wedge the RPC. When streaming, the
+ // run is wrapped in the thread-id scope so descendant turns tag their trace
+ // and socket events with this thread.
+ let run = with_origin(AgentTurnOrigin::Cli, agent.run_single(FLOW_DISCOVER_PROMPT));
+ let run = tokio::time::timeout(
+ std::time::Duration::from_secs(FLOW_DISCOVER_TIMEOUT_SECS),
+ run,
+ );
+ let timed = run.await;
+ // Reduce the (timeout, run) result to a single `Result<summary, error>` so
+ // the terminal chat event can be emitted uniformly for the streamed case.
+ let outcome: Result<String, String> = match timed {
+ Ok(Ok(summary)) => {
+ tracing::debug!(target: "flows", "[flows] flows_discover: agent run completed");
+ Ok(summary)
+ }
+ Ok(Err(e)) => {
+ // The agent errored. Surface it, but still return whatever
+ // suggestions may already be persisted (a prior run's active set)
+ // rather than hard-failing the UI.
+ tracing::warn!(target: "flows", error = %e, "[flows] flows_discover: agent run failed");
+ Err(format!("flow_discovery run failed: {e:#}"))
+ }
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ timeout_secs = FLOW_DISCOVER_TIMEOUT_SECS,
+ "[flows] flows_discover: agent run timed out"
+ );
+ Err(format!(
+ "flow_discovery run timed out after {FLOW_DISCOVER_TIMEOUT_SECS}s"
+ ))
+ }
+ };
+
+ // Emit the terminal chat event so a client viewing the thread finalizes the
+ // assistant bubble instead of spinning (the bridge only streams deltas).
+ if let Some(target) = &stream {
+ finalize_flow_stream(ctx, target, &outcome, FLOW_DISCOVER_PROMPT, config).await;
+ }
+
+ let suggestions = store::list_suggestions(config, Some(SuggestionStatus::New), 50)
+ .map_err(|e| e.to_string())?;
+ tracing::info!(
+ target: "flows",
+ count = suggestions.len(),
+ "[flows] flows_discover: returning active suggestions"
+ );
+ Ok(Outcome::single_log(suggestions, "flow discovery complete"))
+}
+
+/// Lists persisted workflow suggestions. `status` filters to one lifecycle
+/// state (the UI passes `New` for the active "Suggested for you" cards); `None`
+/// returns every status.
+pub async fn flows_list_suggestions(
+ config: &Config,
+ status: Option<SuggestionStatus>,
+) -> Result<Outcome<Vec<FlowSuggestion>>, String> {
+ let suggestions = store::list_suggestions(config, status, 100).map_err(|e| e.to_string())?;
+ Ok(Outcome::single_log(suggestions, "suggestions listed"))
+}
+
+/// Marks a suggestion `dismissed` (the user rejected the card). The row is kept
+/// so a later discovery run dedupes against it and won't re-surface the idea.
+pub async fn flows_dismiss_suggestion(config: &Config, id: &str) -> Result<Outcome<Value>, String> {
+ let found = store::set_suggestion_status(config, id, SuggestionStatus::Dismissed)
+ .map_err(|e| e.to_string())?;
+ Ok(Outcome::single_log(
+ json!({ "id": id, "dismissed": found }),
+ "suggestion dismissed",
+ ))
+}
+
+/// Marks a suggestion `built` — called by the frontend after the user saves a
+/// flow authored from this suggestion, so it drops out of the active cards.
+pub async fn flows_mark_suggestion_built(
+ config: &Config,
+ id: &str,
+) -> Result<Outcome<Value>, String> {
+ let found = store::set_suggestion_status(config, id, SuggestionStatus::Built)
+ .map_err(|e| e.to_string())?;
+ Ok(Outcome::single_log(
+ json!({ "id": id, "built": found }),
+ "suggestion marked built",
+ ))
+}
diff --git a/crates/openhuman-core/src/flows/ops/execution_tests.rs b/crates/openhuman-core/src/flows/ops/execution_tests.rs
index e69de29bb2..3bf01a4040 100644
--- a/crates/openhuman-core/src/flows/ops/execution_tests.rs
+++ b/crates/openhuman-core/src/flows/ops/execution_tests.rs
@@ -0,0 +1,52 @@
+use super::*;
+use tinyflows::graph::GraphEvent;
+use tinyflows::graph::ids;
+
+#[test]
+fn graph_observations_are_adapted_without_changing_their_wire_shape() {
+ let thread_id = "flow:flow-1:uuid-1";
+ let engine = FlowObservation {
+ event_id: ids::EventId::new("evt-1"),
+ run_id: ids::RunId::new("run-9"),
+ root_run_id: ids::RunId::new("run-9"),
+ parent_run_id: None,
+ thread_id: Some(ids::ThreadId::new(thread_id)),
+ graph_id: ids::GraphId::new("workflow"),
+ checkpoint_id: None,
+ namespace: Vec::new(),
+ step: 1,
+ offset: 2,
+ ts_ms: 1_020,
+ event: GraphEvent::NodeStarted {
+ node: ids::NodeId::new("fetch"),
+ step: 1,
+ },
+ };
+
+ let converted = exporter_observations(std::slice::from_ref(&engine));
+ assert_eq!(converted.len(), 1);
+ assert_eq!(
+ serde_json::to_value(&engine).unwrap(),
+ serde_json::to_value(&converted[0]).unwrap()
+ );
+ assert_eq!(
+ converted[0].thread_id.as_ref().map(|id| id.as_str()),
+ Some(thread_id)
+ );
+ assert_eq!(converted[0].event_id.as_str(), "evt-1");
+ assert_eq!(converted[0].step, 1);
+ assert_eq!(converted[0].ts_ms, 1_020);
+}
+
+#[test]
+fn catalog_flow_triggers_map_to_the_serde_bus_contract() {
+ let cases = [
+ (FlowRunTrigger::Rpc, BusFlowRunTrigger::Rpc),
+ (FlowRunTrigger::Schedule, BusFlowRunTrigger::Schedule),
+ (FlowRunTrigger::AppEvent, BusFlowRunTrigger::AppEvent),
+ (FlowRunTrigger::Resume, BusFlowRunTrigger::Resume),
+ ];
+ for (catalog, bus) in cases {
+ assert_eq!(flow_trigger(catalog), bus);
+ }
+}
diff --git a/crates/openhuman-core/src/flows/ops/tool_contract_gate.rs b/crates/openhuman-core/src/flows/ops/tool_contract_gate.rs
index e69de29bb2..c7ed3a873b 100644
--- a/crates/openhuman-core/src/flows/ops/tool_contract_gate.rs
+++ b/crates/openhuman-core/src/flows/ops/tool_contract_gate.rs
@@ -0,0 +1,77 @@
+use super::*;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Tool-contract enforcement gate (systemic tool-contract fix, Part 2)
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// `validate_binding_resolvability` (above) statically proves a binding's
+// SHAPE is sound (envelope dereference, agent output schema). It has no
+// opinion on whether a `tool_call` node's `slug` is a REAL Composio action,
+// or whether the args it wires cover that action's REAL required set — a
+// builder could pass a hallucinated slug (`SLACK_POST_MESSAGE_TO_CHANNEL`,
+// which 404s at runtime) or omit a genuinely required arg, and
+// `validate_binding_resolvability` would have nothing to say about either.
+// [`validate_tool_contracts`] is that missing HARD gate, grounded in
+// [`crate::integrations::composio::catalog::fetch_live_toolkit_catalog`] — the
+// FULL LIVE Composio catalog, not the static curated subset.
+
+/// Statically proves every `tool_call` node's `config.slug` is a REAL action
+/// in the LIVE Composio catalog for its toolkit, and that every one of that
+/// action's REAL required args is present (non-null) in `config.args` —
+/// rejecting the graph (a non-empty `Vec` = reject; empty = pass) when
+/// either check fails. Wired into `propose_workflow` / `revise_workflow` /
+/// `save_workflow` alongside [`validate_binding_resolvability`].
+///
+/// Skipped for a `slug` that is `=`-derived (resolved from upstream/trigger
+/// data at runtime — nothing to check statically) or a native `oh:` tool (no
+/// Composio contract at all).
+///
+/// **Best-effort on catalog availability, not on catalog CONTENT**: when the
+/// live-catalog fetch itself fails (no backend session, network error) the
+/// node is SKIPPED with a debug log — never rejected — because a
+/// hallucinated slug can only be confirmed hallucinated once the real
+/// catalog was actually reachable; `graph_wiring_warnings`'s
+/// `composio_required_args` checks share this exact contract. Once the
+/// catalog IS reachable, though, both checks below are HARD: an unreal slug
+/// or a missing required arg rejects the graph outright, unlike the
+/// advisory output-field/`split_out.path` WARNs in `graph_wiring_warnings`
+/// (Part 2c/2d) — those degrade gracefully because a binding to an unknown
+/// field can't be proven wrong, whereas a nonexistent slug or a missing
+/// required arg are both provably broken.
+/// Whether OpenHuman ships a STATIC curated catalog for `toolkit`. This is the
+/// exact condition both [`validate_tool_contracts`]'s curation gate and
+/// `tinyflows::caps::flow_tool_allowed`'s runtime Path A use to decide a toolkit
+/// is a hard curated-only allowlist: for such a toolkit a real-but-uncurated
+/// action is rejected on EVERY real run, so the author-time gate and the early
+/// builder-tool warnings (`get_tool_contract` / `search_tool_catalog`) must all
+/// agree on it — one home for the check so they cannot drift.
+pub(crate) fn toolkit_has_curated_catalog(toolkit: &str) -> bool {
+ // The curated catalogs moved to `tinymemory-bus` (OpenHuman#5560) and are
+ // reachable directly via `catalog_for_toolkit`, so this no longer needs
+ // the engine-backed provider-registry hop the comment here used to
+ // explain: `get_provider(toolkit).curated_tools()` was verified identical
+ // to `catalog_for_toolkit(toolkit)` for every toolkit that had one, and
+ // tinymemory v1.13.4 deleted the registry outright, so the hop is gone
+ // rather than merely unnecessary.
+ crate::integrations::composio::catalog::has_curated_catalog(toolkit)
+}
+
+pub(crate) async fn validate_tool_contracts(config: &Config, graph: &WorkflowGraph) -> Vec<String> {
+ use crate::integrations::composio::contract::validation::{
+ ToolContractNode, validate_tool_contract_nodes,
+ };
+
+ let nodes: Vec<_> = graph
+ .nodes
+ .iter()
+ .filter(|node| node.kind == NodeKind::ToolCall)
+ .filter_map(|node| {
+ Some(ToolContractNode {
+ id: node.id.clone(),
+ slug: node.config.get("slug")?.as_str()?.to_string(),
+ args: node.config.get("args").cloned().unwrap_or(Value::Null),
+ })
+ })
+ .collect();
+ validate_tool_contract_nodes(config, &nodes).await
+}
diff --git a/crates/openhuman-core/src/flows/ops/updates.rs b/crates/openhuman-core/src/flows/ops/updates.rs
index e69de29bb2..68b9575267 100644
--- a/crates/openhuman-core/src/flows/ops/updates.rs
+++ b/crates/openhuman-core/src/flows/ops/updates.rs
@@ -0,0 +1,279 @@
+use super::*;
+
+/// Maps a store-level [`FlowUpdateError`](tinyflows_catalog::store::FlowUpdateError) to the RPC
+/// error string. A concurrency conflict is encoded as a JSON object the UI can
+/// parse (`{ code: "version_conflict", message, current }`) so it can offer a
+/// reload/diff instead of silently clobbering; other variants are plain text.
+fn map_flow_update_error(e: tinyflows_catalog::store::FlowUpdateError) -> String {
+ match e {
+ tinyflows_catalog::store::FlowUpdateError::NotFound => "flow not found".to_string(),
+ tinyflows_catalog::store::FlowUpdateError::Conflict(current) => {
+ serde_json::to_string(&json!({
+ "code": "version_conflict",
+ "message": "This flow changed since you loaded it. Reload to see the latest \
+ version, then reapply your change.",
+ "current": *current,
+ }))
+ .unwrap_or_else(|_| "version_conflict".to_string())
+ }
+ tinyflows_catalog::store::FlowUpdateError::Store(err) => err.to_string(),
+ }
+}
+
+/// Updates a flow's name, graph, and/or `require_approval` toggle.
+/// Re-validates the graph (whether newly supplied or the existing one)
+/// before persisting, same as `flows_create`.
+///
+/// When the caller supplies a new `graph_json` and the flow is (still)
+/// enabled, re-binds the automatic-dispatch trigger if the trigger
+/// kind/config actually changed (e.g. a new schedule cron expression) —
+/// otherwise the stale binding from the old graph would keep firing on the
+/// old cadence, or a newly-added schedule would never get bound at all.
+/// Skipped entirely for a name/`require_approval`-only update (no
+/// `graph_json` supplied), since the trigger definitely didn't change.
+///
+/// **B29 Rule 1 analogue for saves** (save/enable safety — same issue
+/// `flows_create` guards at creation time, see its doc): `flows_create`
+/// refuses to persist an automatic-trigger graph (`schedule` / `app_event` /
+/// `webhook`, see [`trigger_is_automatic`]) as `enabled`, but that guard only
+/// runs once, at creation. Without an equivalent here, a flow created
+/// `enabled: true` with a manual/no-op trigger could later have an
+/// automatic-trigger graph saved onto it — via the `save_workflow` agent
+/// tool, the canvas Save button, a proposal apply, or any other
+/// `flows_update` caller — and go LIVE immediately with no user review
+/// (confirmed live: a flow started firing on an unreviewed 8am schedule).
+/// So: when the *new* graph's trigger is automatic and the *previous*
+/// graph's trigger was NOT automatic (a manual/none → automatic
+/// transition), this forces the persisted `enabled` back to `false` in the
+/// same store write — the user must explicitly re-arm via
+/// `flows_set_enabled` after reviewing the new trigger. An automatic →
+/// automatic re-edit (e.g. tweaking a cron expression) is left alone — the
+/// user already opted in once, and re-disarming on every edit would just be
+/// friction.
+///
+/// The override is applied **unconditionally** on a manual/none → automatic
+/// transition — it does *not* gate on whether the flow *looked* enabled in
+/// the `existing` read above. That read is a snapshot taken before
+/// `store::update_flow_graph`'s own guarded UPDATE re-reads the row; a
+/// concurrent `flows_set_enabled(id, true)` landing in the gap would leave
+/// this snapshot stale while the row is actually enabled by the time the
+/// guarded UPDATE runs — and since `set_enabled` bumps `updated_at` too,
+/// such a race wouldn't even trip the optimistic-concurrency conflict, it
+/// would just silently persist the automatic graph as enabled (the exact
+/// bug this rule exists to close). Gating on the stale `existing.enabled`
+/// re-opens that race; forcing the override on every transition, enabled-or-
+/// not, is exactly as safe as Rule 1's at-create version — a transition on
+/// an already-disabled flow is just a no-op write of `enabled=false` over
+/// `enabled=false`.
+pub async fn flows_update(
+ config: &Config,
+ id: &str,
+ name: Option<String>,
+ graph_json: Option<Value>,
+ require_approval: Option<bool>,
+ expected_version: Option<String>,
+) -> Result<Outcome<Flow>, String> {
+ flows_update_inner(
+ config,
+ id,
+ name,
+ graph_json,
+ require_approval,
+ expected_version,
+ false,
+ )
+ .await
+}
+
+async fn flows_update_inner(
+ config: &Config,
+ id: &str,
+ name: Option<String>,
+ graph_json: Option<Value>,
+ require_approval: Option<bool>,
+ expected_version: Option<String>,
+ disarm_automatic: bool,
+) -> Result<Outcome<Flow>, String> {
+ let existing = store::get_flow(config, id)
+ .map_err(|e| e.to_string())?
+ .ok_or_else(|| format!("flow '{id}' not found"))?;
+
+ let new_name = name.unwrap_or_else(|| existing.name.clone());
+ let new_require_approval = require_approval.unwrap_or(existing.require_approval);
+ let graph_changed = graph_json.is_some();
+ let graph = match graph_json {
+ Some(raw) => {
+ let graph = validate_and_migrate_graph(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ raw,
+ )
+ .await?;
+ graph
+ }
+ None => {
+ validate_and_migrate_graph(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ serde_json::to_value(&existing.graph).map_err(|error| error.to_string())?,
+ )
+ .await?
+ }
+ };
+ // B29 Rule 1 analogue: disarm every manual/none → automatic trigger
+ // transition, unconditionally. `now_auto` is safe to compute here (it
+ // only depends on `graph`, THIS call's own incoming graph — never
+ // stale). The "was it automatic before" half of the transition,
+ // however, is NOT decided here: R-m2 found that gating on the
+ // ops-level `existing.graph` read let a concurrent write race this
+ // call and slip an automatic-trigger graph through with `enabled: true`
+ // — `existing` can be arbitrarily stale by the time
+ // `store::update_flow_graph` actually performs its guarded write. That
+ // decision now lives inside `update_flow_graph`, computed against the
+ // row it just re-read there (see its doc comment).
+ let now_auto = trigger_is_automatic(&graph);
+ let forced_automatic_disarm = disarm_automatic && now_auto;
+ tracing::debug!(
+ target: "flows",
+ flow_id = %id,
+ now_auto,
+ currently_enabled = existing.enabled,
+ forced_automatic_disarm,
+ "[flows] flows_update: auto-trigger disarm decision inputs (transition itself decided \
+ store-side against a fresh read, see update_flow_graph)"
+ );
+
+ // Rule 2 analogue (compound-bypass closure): re-apply the same outbound
+ // side-effect check `flows_create` applies on save — via the shared
+ // [`enforce_side_effect_approval`] helper — so an update that *adds* a
+ // tool_call/http_request/code node to a previously read-only graph can
+ // never persist `require_approval: false` just because the update path
+ // trusted the caller's toggle unconditionally.
+ let (effective_require_approval, side_effect_forced) =
+ enforce_side_effect_approval(&graph, new_require_approval);
+ if side_effect_forced {
+ tracing::info!(
+ target: "flows",
+ flow_id = %id,
+ "[flows] flows_update: forcing require_approval=true — graph contains outbound \
+ side-effect node(s) (tool_call / http_request / code)"
+ );
+ }
+
+ tracing::debug!(
+ target: "flows",
+ flow_id = %id,
+ has_expected = expected_version.is_some(),
+ require_approval = effective_require_approval,
+ side_effect_forced,
+ "[flows] flows_update: persisting changes"
+ );
+ // The auto-disarm decision (both the unconditional manual→automatic
+ // transition and `disarm_automatic`'s forced-remote-authoring variant)
+ // is made INSIDE `update_flow_graph`, against the row it re-reads right
+ // before its guarded UPDATE — see R-m2 above and that function's doc
+ // comment. `enabled_override: None` here means "no explicit force from
+ // this caller"; the disarm, if any, still applies on top of that.
+ let updated = store::update_flow_graph(
+ config,
+ id,
+ new_name,
+ graph,
+ effective_require_approval,
+ None,
+ disarm_automatic,
+ expected_version.as_deref(),
+ )
+ .map_err(map_flow_update_error)?;
+
+ // Best-effort, POST-write: did the flow actually transition from
+ // enabled to disabled as part of this update? Derived from the real
+ // before/after state (`existing.enabled` vs `updated.enabled`) rather
+ // than re-predicting the decision — the decision itself already
+ // happened store-side against a fresh read, so this is purely for the
+ // info log / result message wording below and can't desync from what
+ // was actually persisted.
+ let should_disarm = now_auto && existing.enabled && !updated.enabled;
+ if should_disarm {
+ tracing::info!(
+ target: "flows",
+ flow_id = %id,
+ "[flows] flows_update: auto-disabled automatic-trigger graph pending explicit re-arm"
+ );
+ }
+
+ if graph_changed && updated.enabled {
+ let trigger_unchanged = bus::extract_trigger_kind(&existing)
+ == bus::extract_trigger_kind(&updated)
+ && bus::extract_trigger_config(&existing) == bus::extract_trigger_config(&updated);
+ if !trigger_unchanged {
+ tracing::debug!(target: "flows", flow_id = %id, "[flows] flows_update: trigger changed on an enabled flow — rebinding automatic-dispatch trigger");
+ unbind_trigger(config, &existing);
+ bind_trigger(config, &updated);
+ }
+ }
+
+ publish_flow_changed(id, "updated", "system");
+ let mut logs = vec![format!("flow updated: {id}")];
+ if should_disarm {
+ let reason = if forced_automatic_disarm {
+ "Flow was auto-disabled because this authoring surface revised an automatic trigger \
+ (schedule / app_event / webhook). Enable it explicitly (flows_set_enabled) once \
+ you've reviewed the revision."
+ } else {
+ "Flow was auto-disabled because its trigger changed from manual to automatic \
+ (schedule / app_event / webhook). Enable it explicitly (flows_set_enabled) once \
+ you've reviewed the new trigger."
+ };
+ logs.push(reason.to_string());
+ }
+ if side_effect_forced {
+ logs.push(
+ "require_approval forced to true because the graph contains outbound side-effect \
+ nodes (tool_call / http_request / code)."
+ .to_string(),
+ );
+ }
+ Ok(Outcome::new(updated, logs))
+}
+
+/// Lists a flow's revision history (prior graph snapshots), newest first,
+/// capped at `limit` (audit F6). The safety rail that makes rollback possible.
+pub fn flows_get_history(
+ config: &Config,
+ id: &str,
+ limit: usize,
+) -> Result<Outcome<Vec<tinyflows_catalog::FlowRevision>>, String> {
+ let revisions = store::list_revisions(config, id, limit).map_err(|e| e.to_string())?;
+ let count = revisions.len();
+ Ok(Outcome::single_log(
+ revisions,
+ format!("flow history: {id} ({count} revisions)"),
+ ))
+}
+
+/// Rolls a flow back to a prior revision by restoring that revision's graph
+/// through the normal update path — which itself snapshots the current graph as
+/// a new revision, so a rollback is itself undoable. Honours optimistic
+/// concurrency via `expected_version`.
+pub async fn flows_rollback(
+ config: &Config,
+ id: &str,
+ revision_id: &str,
+ expected_version: Option<String>,
+) -> Result<Outcome<Flow>, String> {
+ let rev = store::revision_by_id(config, id, revision_id)
+ .map_err(|e| e.to_string())?
+ .ok_or_else(|| format!("revision '{revision_id}' not found for flow '{id}'"))?;
+
+ tracing::debug!(target: "flows", flow_id = %id, %revision_id, "[flows] flows_rollback: restoring prior revision");
+ flows_update(
+ config,
+ id,
+ Some(rev.name),
+ Some(rev.graph),
+ Some(rev.require_approval),
+ expected_version,
+ )
+ .await
+}
diff --git a/crates/openhuman-core/src/flows/ops/validation.rs b/crates/openhuman-core/src/flows/ops/validation.rs
index e69de29bb2..cce0fcf3bc 100644
--- a/crates/openhuman-core/src/flows/ops/validation.rs
+++ b/crates/openhuman-core/src/flows/ops/validation.rs
@@ -0,0 +1,218 @@
+use super::*;
+use crate::core::runtime::DispatchCtx;
+use tinyflows_bus::{GraphValidation, ImportGraphResult, ValidateGraphRequest};
+
+// The refusal code remains stable on OpenHuman's test surface.
+#[cfg(test)]
+pub(crate) use tinyflows::compat::UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN;
+
+async fn validate_over_bus(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<GraphValidation, String> {
+ let registration =
+ crate::flows::authoring_host::register(Arc::new(config.clone()), ctx.clone()).await?;
+ let proxy = crate::modules::tinyflows::authoring_proxy(config).await?;
+ proxy
+ .call(
+ tinyflows_bus::methods::VALIDATE_GRAPH,
+ &(ValidateGraphRequest {
+ graph,
+ host: Some(registration.authoring.clone()),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())
+}
+
+/// Validates and migrates a graph through TinyFlows, resolving saved children
+/// through the host callback bound to the current invocation scope.
+pub(crate) async fn validate_and_migrate_graph(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<WorkflowGraph, String> {
+ let report = validate_over_bus(ctx, config, graph).await?;
+ if let Some(error) = report.errors.first() {
+ return Err(error.message.clone());
+ }
+ report
+ .graph
+ .ok_or_else(|| "TinyFlows validation returned no graph".to_string())
+ .and_then(|graph| serde_json::from_value(graph).map_err(|error| error.to_string()))
+}
+
+/// Host-aware compatibility errors for graphs that can reference saved flows.
+pub(crate) async fn config_aware_engine_compatibility_errors(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<Vec<String>, String> {
+ let report = validate_over_bus(ctx, config, graph).await?;
+ Ok(report
+ .errors
+ .into_iter()
+ .filter(|error| {
+ error.code.starts_with("unsupported_")
+ || error.code.starts_with("incompatible_referenced_workflow")
+ })
+ .map(|error| format!("{}: {}", error.code, error.message))
+ .collect())
+}
+
+pub(super) async fn ensure_config_aware_engine_compatible(
+ config: &Config,
+ graph: &WorkflowGraph,
+) -> Result<(), String> {
+ let graph = serde_json::to_value(graph).map_err(|error| error.to_string())?;
+ match config_aware_engine_compatibility_errors(&DispatchCtx::ambient(), config, graph)
+ .await?
+ .into_iter()
+ .next()
+ {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
+}
+
+/// Validates a candidate graph without persisting it and reports all errors
+/// with host trigger warnings added after successful engine validation.
+pub async fn flows_validate(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph_json: Value,
+) -> Outcome<tinyflows_catalog::FlowValidation> {
+ use tinyflows_catalog::{FlowValidation, FlowValidationError};
+ let report = match validate_over_bus(ctx, config, graph_json).await {
+ Ok(report) => report,
+ Err(error) => {
+ return Outcome::single_log(
+ FlowValidation {
+ valid: false,
+ errors: vec![error.clone()],
+ error_details: vec![FlowValidationError {
+ code: "authoring_unavailable".into(),
+ message: error,
+ node_id: None,
+ field: None,
+ }],
+ warnings: Vec::new(),
+ },
+ "flow validation failed",
+ );
+ }
+ };
+ let errors = report
+ .errors
+ .into_iter()
+ .map(|error| FlowValidationError {
+ code: error.code,
+ message: error.message,
+ node_id: error.node_id,
+ field: error.field,
+ })
+ .collect::<Vec<_>>();
+ if !errors.is_empty() {
+ let messages = errors.iter().map(|error| error.message.clone()).collect();
+ return Outcome::single_log(
+ FlowValidation {
+ valid: false,
+ errors: messages,
+ error_details: errors,
+ warnings: Vec::new(),
+ },
+ "flow validation failed",
+ );
+ }
+ let graph: WorkflowGraph = match report
+ .graph
+ .ok_or_else(|| "TinyFlows validation returned no graph".to_string())
+ .and_then(|graph| serde_json::from_value(graph).map_err(|error| error.to_string()))
+ {
+ Ok(graph) => graph,
+ Err(error) => {
+ return Outcome::single_log(
+ FlowValidation {
+ valid: false,
+ errors: vec![error.clone()],
+ error_details: vec![FlowValidationError {
+ code: "unparseable_graph".into(),
+ message: error,
+ node_id: None,
+ field: None,
+ }],
+ warnings: Vec::new(),
+ },
+ "flow validation failed",
+ );
+ }
+ };
+ let warnings = graph_trigger_warnings(&graph);
+ Outcome::single_log(
+ FlowValidation {
+ valid: true,
+ errors: Vec::new(),
+ error_details: Vec::new(),
+ warnings,
+ },
+ "flow validated",
+ )
+}
+
+/// Imports and validates native or n8n graph JSON through TinyFlows without
+/// persisting it.
+pub async fn flows_import(
+ _ctx: &DispatchCtx,
+ config: &Config,
+ graph_json: Value,
+ format: Option<String>,
+) -> Result<Outcome<tinyflows_catalog::FlowImport>, String> {
+ use tinyflows_catalog::FlowImport;
+ let requested = format
+ .as_deref()
+ .unwrap_or("auto")
+ .trim()
+ .to_ascii_lowercase();
+ if !matches!(
+ requested.as_str(),
+ "auto" | "" | "native" | "tinyflows" | "n8n"
+ ) {
+ return Err(format!(
+ "unknown import format '{requested}' (expected 'native' or 'n8n')"
+ ));
+ }
+ let proxy = crate::modules::tinyflows::authoring_proxy(config).await?;
+ let imported: ImportGraphResult = proxy
+ .call(
+ tinyflows_bus::methods::IMPORT_GRAPH,
+ &(tinyflows_bus::ImportGraphRequest {
+ graph: graph_json,
+ format: Some(requested),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ if let Some(error) = imported.errors.first() {
+ return Err(error.message.clone());
+ }
+ let graph: WorkflowGraph = imported
+ .graph
+ .ok_or_else(|| "TinyFlows import returned no graph".to_string())
+ .and_then(|graph| serde_json::from_value(graph).map_err(|error| error.to_string()))?;
+ let mut warnings = imported.warnings;
+ warnings.extend(graph_trigger_warnings(&graph));
+ Ok(Outcome::single_log(
+ FlowImport { graph, warnings },
+ "flow imported",
+ ))
+}
+
+/// Compatibility diagnostics for a portable Copilot graph payload.
+pub(crate) async fn engine_compatibility_errors_json(
+ ctx: &DispatchCtx,
+ config: &Config,
+ graph: Value,
+) -> Result<Vec<String>, String> {
+ config_aware_engine_compatibility_errors(ctx, config, graph).await
+}
diff --git a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
index e69de29bb2..d7cf7406c7 100644
--- a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
@@ -0,0 +1,558 @@
+use super::*;
+
+// ── validate_agent_refs (agent-ref resolvability gate, PR #5114) ───────────
+
+#[tokio::test]
+async fn agent_ref_plain_node_without_ref_is_accepted() {
+ // A plain `agent` node carries NO `agent_ref` — it runs on the default LLM
+ // completion and never touches `OpenHumanAgentRunner`'s routing at all, so
+ // this gate must never reject it. This is the exact invariant #5114 must
+ // preserve: only an UNKNOWN `agent_ref` is rejected, never a plain node.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan", "config": { "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+ let errors =
+ validate_agent_refs(&crate::core::runtime::DispatchCtx::ambient(), &config, &g).await;
+ assert!(errors.is_empty(), "{errors:?}");
+}
+
+#[tokio::test]
+async fn agent_ref_blank_string_is_treated_as_absent() {
+ // A whitespace-only `agent_ref` must be treated the same as no ref at all
+ // rather than being resolved (and potentially rejected as "unknown").
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": " ", "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+ let errors =
+ validate_agent_refs(&crate::core::runtime::DispatchCtx::ambient(), &config, &g).await;
+ assert!(errors.is_empty(), "{errors:?}");
+}
+
+#[tokio::test]
+async fn agent_ref_resolving_to_a_harness_definition_is_accepted() {
+ // "orchestrator" is one of the bundled built-in agent definitions
+ // (see `agent_registry::defaults::default_agents_include_core_personas`),
+ // so it must resolve via `AgentRoute::Harness` and never touch the
+ // custom agent registry at all.
+ //
+ // This also exercises the CodeRabbit/Codex #5114 review fix: run via the
+ // scoped `cargo test --lib flows::ops` filter, no other domain's test gets
+ // to call `AgentDefinitionRegistry::init_global_builtins()` first, so this
+ // only passes because `validate_agent_refs` now defensively initialises
+ // the harness registry itself before resolving a ref.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": "orchestrator", "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+ let errors =
+ validate_agent_refs(&crate::core::runtime::DispatchCtx::ambient(), &config, &g).await;
+ assert!(
+ errors.is_empty(),
+ "a real harness agent_ref must never be rejected: {errors:?}"
+ );
+}
+
+#[tokio::test]
+async fn agent_ref_unknown_is_rejected() {
+ // The whole point of the gate (and the branch Codex flagged as uncovered on
+ // #5114): an `agent` node whose `agent_ref` is NOT a real registered agent —
+ // neither a bundled harness definition nor a custom registry entry — must be
+ // REJECTED at author time, with the offending id named, rather than silently
+ // hitting the `RegistryFallback` persona path at run time. Exercises the
+ // error-construction branch of `validate_agent_refs`.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": "no_such_agent_xyz", "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+ let errors =
+ validate_agent_refs(&crate::core::runtime::DispatchCtx::ambient(), &config, &g).await;
+ assert!(!errors.is_empty(), "an unknown agent_ref must be rejected");
+ assert!(
+ errors.iter().any(|e| e.contains("no_such_agent_xyz")),
+ "the rejection error must name the offending agent_ref: {errors:?}"
+ );
+}
+
+// ── dynamic agent_ref: refused at authoring, still reachable at run time ──
+
+/// A `=`-expression `agent_ref` is no longer authorable. TinyFlows requires a
+/// literal agent-registry reference so run data — which may include model
+/// output — cannot choose an agent with different privileges, the same
+/// reasoning this host already applies to `tool_call` slugs.
+///
+/// Pinned here rather than left to the vendor's own suite because the
+/// `workflow_builder` agent can propose this shape, and the message a builder
+/// sees on rejection is this host's contract with it.
+#[tokio::test]
+async fn dynamic_agent_ref_is_rejected_during_structural_validation() {
+ let err = validate_and_migrate_graph(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Dynamic",
+ "config": { "agent_ref": "=nodes.t.item.agent_choice", "prompt": "go" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }),
+ )
+ .await
+ .expect_err("dynamic agent_ref must fail structural validation");
+ assert!(
+ err.contains("agent_ref") && err.contains("must be a literal"),
+ "the message must say what is wrong, not just that something is: {err}"
+ );
+}
+
+#[tokio::test]
+async fn inference_gate_reports_signed_out_for_dynamic_agent_ref_only_graph() {
+ // Finding C, and it survives the rule above: an `agent` node whose
+ // `agent_ref` is `=`-derived means "this graph runs inference" whatever
+ // its concrete route resolves to, so it must stay in scope for Layer 1
+ // (signed-out/session) even though its per-model role cannot be resolved
+ // statically. The bug this pins is a graph made up only of such nodes
+ // returning `None` — no readiness signal at all — so a signed-out session
+ // went completely unreported.
+ //
+ // This is NOT a dead path just because authoring now refuses the shape.
+ // `store::load` runs `tinyflows::migrate::migrate` and deserializes, but
+ // never `validate`, and `run_flow_body` hands the loaded `flow.graph`
+ // straight to `validate_inference_readiness` — so a flow persisted before
+ // the vendor rule still reaches this gate with a dynamic ref, which is
+ // also what makes `agent_node_role`'s `=`-filter (and its fallback to the
+ // default role) load-bearing rather than vestigial.
+ //
+ // Built as a struct literal for that reason: `graph()` would reject it,
+ // and going through `graph()` would only prove the rule above twice.
+ let _signed_out = crate::platform::llm_gate::SignedOutTestGuard::set(true);
+
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let g = WorkflowGraph {
+ nodes: vec![
+ tinyflows::model::Node {
+ id: "t".to_string(),
+ kind: NodeKind::Trigger,
+ type_version: 1,
+ name: "Manual".to_string(),
+ config: json!({ "trigger_kind": "manual" }),
+ ports: Vec::new(),
+ position: None,
+ },
+ tinyflows::model::Node {
+ id: "a".to_string(),
+ kind: NodeKind::Agent,
+ type_version: 1,
+ name: "Dynamic".to_string(),
+ config: json!({ "agent_ref": "=nodes.t.item.agent_choice", "prompt": "go" }),
+ ports: Vec::new(),
+ position: None,
+ },
+ ],
+ ..Default::default()
+ };
+
+ let errors =
+ validate_inference_readiness(&crate::core::runtime::DispatchCtx::ambient(), &config, &g)
+ .await;
+ assert!(
+ !errors.is_empty(),
+ "a signed-out session must still be reported even though the only agent node's \
+ agent_ref is dynamic: {errors:?}"
+ );
+ assert!(
+ errors
+ .iter()
+ .any(|e| e.to_ascii_lowercase().contains("signed out")),
+ "{errors:?}"
+ );
+ // `SignedOutTestGuard` restores the prior flag on drop at the end of this
+ // scope — no other test observes this override.
+}
+
+#[tokio::test]
+async fn proposal_includes_inference_status_for_agent_graph() {
+ // `build_builder_proposal`'s payload carries the same inference-readiness
+ // evaluation, ADVISORY only (B45 design correction), so the UI can render
+ // provider-connectivity state alongside the built workflow. This pins the
+ // happy-path shape: a `"ready"` graph carries no `inference_message`. A
+ // local (`ollama:...`) provider construction is the pass path, matching
+ // `inference_gate_passes_when_model_constructs` — no network, no
+ // process-global test seam.
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.memory_provider = Some("ollama:llama3".to_string());
+
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan", "config": { "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+
+ let payload = build_builder_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "propose_workflow",
+ "agent-flow",
+ &g,
+ false,
+ false,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect("proposal must succeed for a well-formed agent graph");
+
+ assert_eq!(payload["inference_status"], json!("ready"));
+ assert!(
+ payload.get("inference_message").is_none(),
+ "a ready status must omit inference_message: {payload:?}"
+ );
+}
+
+#[tokio::test]
+async fn proposal_omits_inference_status_for_tool_call_only_graph() {
+ // A graph with no `agent` node has nothing for this check to evaluate —
+ // the field must be absent entirely, never a meaningless "ready".
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "oh:noop" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+
+ let payload = build_builder_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "propose_workflow",
+ "tool-flow",
+ &g,
+ false,
+ false,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect("proposal must succeed for a tool_call-only graph");
+
+ assert!(
+ payload.get("inference_status").is_none(),
+ "a graph with no agent node must omit inference_status: {payload:?}"
+ );
+}
+
+/// B45 run-time preflight (design correction, judge finding on live run
+/// 104aab90): since authoring no longer hard-blocks on inference readiness, a
+/// flow whose `agent` node cannot currently reach a working LLM provider can
+/// be created and then RUN. `run_flow_body` must catch that BEFORE invoking
+/// the tinyflows engine, finalizing the run row as `failed` with a clear,
+/// actionable message rather than letting the engine attempt (and fail) real
+/// work, or surface the opaque several-layers-deep "capability error: graph
+/// error: capability error: model error: ... API key not configured for
+/// provider" a mid-run failure produces.
+///
+/// Uses the signed-out seam (`SignedOutTestGuard`) rather than a mock
+/// provider-not-configured backend response: both are classified `Err` by
+/// `evaluate_inference_readiness` and reach the same preflight code path in
+/// `run_flow_body`, and signed-out needs no network/mock server at all
+/// (matching the existing gate tests' no-network convention). The
+/// provider_not_configured class is covered end-to-end by
+/// `probe_readiness_surfaces_api_key_not_configured` (construction) and the
+/// negative-cache test below (through `cached_probe_inference_readiness`).
+#[tokio::test]
+async fn flows_run_fails_cleanly_without_invoking_engine_when_inference_not_ready() {
+ let _signed_out = crate::platform::llm_gate::SignedOutTestGuard::set(true);
+
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let g = json!({
+ "name": "needs-a-provider",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan", "config": { "prompt": "outline it" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ });
+ let created = flows_create(&config, "needs-a-provider".to_string(), g, false)
+ .await
+ .expect("creating (authoring) an agent-node flow must succeed even when signed out");
+
+ let err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("a run whose agent node cannot reach a provider must fail cleanly");
+ assert!(
+ err.to_ascii_lowercase().contains("ai provider"),
+ "error must explain the AI-provider problem: {err}"
+ );
+ assert!(
+ err.to_ascii_lowercase().contains("signed out"),
+ "error must surface the specific reason (signed out): {err}"
+ );
+
+ // The run row settled `failed` with that same message, and the engine
+ // never ran (no persisted steps) — this is the "no pointless work" half
+ // of the contract, not just "the RPC call returned an error".
+ let runs = flows_list_runs(&config, &created.value.id, 1)
+ .await
+ .unwrap()
+ .value;
+ let run = runs.first().expect("a run row must exist");
+ assert_eq!(run.status, "failed");
+ assert!(
+ run.steps.is_empty(),
+ "the engine must never have executed a step: {:?}",
+ run.steps
+ );
+ let run_error = run
+ .error
+ .as_deref()
+ .expect("a failed run must carry an error message");
+ assert!(
+ run_error.to_ascii_lowercase().contains("ai provider"),
+ "the persisted run error must explain the AI-provider problem: {run_error}"
+ );
+
+ // `SignedOutTestGuard` restores the prior flag on drop at the end of this
+ // scope — no other test observes this override.
+}
+
+#[tokio::test]
+async fn local_agent_flow_is_ready_without_openhuman_session() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let _signed_out = crate::platform::llm_gate::SignedOutTestGuard::set(true);
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.chat_provider = Some("omlx:test-model".into());
+ config.memory_provider = Some("omlx:test-model".into());
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Local", "config": { "prompt": "test" } }
+ ],
+ "edges": [{ "from_node": "t", "to_node": "a" }]
+ }));
+ let errors =
+ validate_inference_readiness(&crate::core::runtime::DispatchCtx::ambient(), &config, &g)
+ .await;
+ assert!(
+ errors.is_empty(),
+ "local flow must not need a session: {errors:?}"
+ );
+}
+
+#[tokio::test]
+async fn claude_agent_flow_readiness_does_not_require_an_openhuman_session() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let _signed_out = crate::platform::llm_gate::SignedOutTestGuard::set(true);
+ // Isolate the caller's session classification from CLI installation/auth
+ // and provider availability. Layer 1 must still reject managed inference
+ // even while the Layer 2 probe has an injected model.
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::replies(vec!["OK"]),
+ ));
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Claude", "config": { "prompt": "test" } }
+ ],
+ "edges": [{ "from_node": "t", "to_node": "a" }]
+ }));
+ for provider in [
+ "claude-code:test-model",
+ "claude_agent_sdk:test-model",
+ "openhuman",
+ ] {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.memory_provider = Some(provider.into());
+ let errors = validate_inference_readiness(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &g,
+ )
+ .await;
+ if provider == "openhuman" {
+ assert!(
+ errors.iter().any(|e| e.contains("signed out")),
+ "{errors:?}"
+ );
+ } else {
+ assert!(
+ errors.is_empty(),
+ "{provider} must not require a session: {errors:?}"
+ );
+ }
+ }
+}
+
+#[test]
+fn harness_readiness_uses_runtime_role_and_node_override() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.default_model = None;
+ let mut g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Agent",
+ "config": { "agent_ref": "orchestrator", "prompt": "go" } }
+ ],
+ "edges": [{"from_node": "t", "to_node": "a"}]
+ }));
+ let node = g.nodes.iter_mut().find(|n| n.id == "a").unwrap();
+ assert_eq!(agent_node_role(&config, node), "coding");
+ config.default_model = Some("hint:reasoning".into());
+ assert_eq!(agent_node_role(&config, node), "reasoning");
+ node.config["model"] = json!("chat-v1");
+ assert_eq!(agent_node_role(&config, node), "chat");
+ node.config["model"] = json!("hint:summarization");
+ assert_eq!(agent_node_role(&config, node), "summarization");
+ node.config["model"] = json!("custom-model-id");
+ assert_eq!(agent_node_role(&config, node), "chat");
+}
+
+#[tokio::test]
+async fn harness_readiness_checks_session_for_execution_provider() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let _signed_out = crate::platform::llm_gate::SignedOutTestGuard::set(true);
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::replies(vec!["OK"]),
+ ));
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Agent",
+ "config": { "agent_ref": "orchestrator", "prompt": "go" } }
+ ],
+ "edges": [{"from_node": "t", "to_node": "a"}]
+ }));
+ for (runtime, summary, should_reject) in [
+ ("ollama:test", "openhuman", false),
+ ("openhuman", "ollama:test", true),
+ ] {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.default_model = Some("hint:reasoning".into());
+ config.reasoning_provider = Some(runtime.into());
+ config.memory_provider = Some(summary.into());
+ let errors = validate_inference_readiness(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &g,
+ )
+ .await;
+ assert_eq!(
+ errors.iter().any(|e| e.contains("signed out")),
+ should_reject,
+ "{errors:?}"
+ );
+ if !should_reject {
+ assert!(errors.is_empty(), "{errors:?}");
+ }
+ }
+}
+
+/// The agent-ref gate resolves a custom agent through the context it is handed,
+/// not the one the calling task happens to run under: two tenants' registries
+/// never cross.
+#[tokio::test]
+async fn agent_ref_gate_reads_the_registry_of_the_explicit_context() {
+ use crate::agent::registry::types::{AgentRegistryEntry, AgentRegistrySource};
+ use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};
+
+ let entry = AgentRegistryEntry {
+ id: "tenant_a_only_agent".to_string(),
+ name: "A".to_string(),
+ description: "registered for tenant A".to_string(),
+ source: AgentRegistrySource::Custom,
+ enabled: true,
+ model: None,
+ system_prompt: None,
+ tool_allowlist: Vec::new(),
+ tool_denylist: Vec::new(),
+ tool_rules: None,
+ subagents: Default::default(),
+ tags: Vec::new(),
+ metadata: Value::Null,
+ };
+ let tmp_a = TempDir::new().unwrap();
+ let tmp_b = TempDir::new().unwrap();
+ let mut config_a = test_config(&tmp_a);
+ config_a.agent_registry.entries.push(entry);
+ let config_b = test_config(&tmp_b);
+ let core_a = CoreContext::for_test_with_config(DomainSet::full(), config_a.clone());
+ let core_b = CoreContext::for_test_with_config(DomainSet::full(), config_b.clone());
+ let ctx_a = DispatchCtx::new(core_a);
+ let ctx_b = DispatchCtx::new(std::sync::Arc::clone(&core_b));
+
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": "tenant_a_only_agent", "prompt": "go" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+
+ // Both calls run scoped to tenant B, so an ambient read would answer B's
+ // registry for A's call.
+ let (for_a, for_b) = CoreContext::scope(core_b, async {
+ (
+ validate_agent_refs(&ctx_a, &config_a, &g).await,
+ validate_agent_refs(&ctx_b, &config_b, &g).await,
+ )
+ })
+ .await;
+ assert!(
+ for_a.is_empty(),
+ "tenant A's own agent must resolve: {for_a:?}"
+ );
+ assert!(
+ for_b.iter().any(|e| e.contains("tenant_a_only_agent")),
+ "tenant B must not see tenant A's agent: {for_b:?}"
+ );
+}
diff --git a/crates/openhuman-core/src/flows/ops_approval_manifest_and_catalog_tests.rs b/crates/openhuman-core/src/flows/ops_approval_manifest_and_catalog_tests.rs
index e69de29bb2..1ab05cc6c0 100644
--- a/crates/openhuman-core/src/flows/ops_approval_manifest_and_catalog_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_approval_manifest_and_catalog_tests.rs
@@ -0,0 +1,619 @@
+use super::*;
+
+#[tokio::test]
+async fn flows_run_detached_returns_running_run_id_and_inserts_row() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "detached".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let outcome = flows_run_detached(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &flow.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("detached run must start");
+
+ assert_eq!(outcome.value["status"], json!("running"));
+ assert_eq!(outcome.value["detached"], json!(true));
+ let run_id = outcome.value["run_id"]
+ .as_str()
+ .expect("run_id must be a string")
+ .to_string();
+ assert!(
+ run_id.starts_with(&format!("flow:{}:", flow.id)),
+ "run_id: {run_id}"
+ );
+
+ // The `running` row is inserted synchronously before the background task is
+ // spawned, so the copilot's immediate `get_flow_run(run_id)` poll finds it.
+ let row = store::get_flow_run(&config, &run_id)
+ .unwrap()
+ .expect("a run row must exist immediately after detaching");
+ assert_eq!(row.flow_id, flow.id);
+}
+
+#[tokio::test]
+async fn flows_run_detached_registers_the_run_before_returning_its_id() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "detached-cancel-race".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let outcome = flows_run_detached(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &flow.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("detached run must start");
+ let run_id = outcome.value["run_id"].as_str().unwrap().to_string();
+
+ // The moment the agent can see this `run_id` it can be cancelled. If
+ // registration happened inside the spawned task instead, this would be
+ // false until the task was first polled — and `flows_cancel_run` would take
+ // its "parked/stale" branch, writing a terminal `cancelled` row and
+ // dropping the checkpoint while the background run went on to execute the
+ // flow's real side effects and overwrite that status.
+ assert!(
+ run_registry::is_in_flight(&run_id),
+ "a detached run must be registered before its run_id is returned"
+ );
+}
+
+#[tokio::test]
+async fn approval_manifest_lists_gated_nodes_and_skips_curated_reads() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp); // default tier: Supervised
+ let entries = compute_approval_manifest(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &manifest_graph(),
+ )
+ .await
+ .unwrap();
+
+ let kinds = entry_kinds_by_tool(&entries);
+ // Supervised prompts on every acting class → all three are approvable.
+ assert!(kinds.contains(&("flows_http_request".into(), "approvable".into())));
+ assert!(kinds.contains(&("flows_code".into(), "approvable".into())));
+ assert!(kinds.contains(&("SHOPIFY_CREATE_ORDER".into(), "approvable".into())));
+ // A curated Read action never reaches the gate — must NOT be listed.
+ assert!(
+ !kinds.iter().any(|(t, _)| t == "SHOPIFY_COUNT_PRODUCTS"),
+ "curated Read slug must be excluded from the manifest: {kinds:?}"
+ );
+ assert_eq!(entries.len(), 3, "{entries:?}");
+}
+
+#[tokio::test]
+async fn approval_manifest_marks_blocked_classes_under_readonly_tier() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.autonomy.level = crate::security::AutonomyLevel::ReadOnly;
+ let entries = compute_approval_manifest(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &manifest_graph(),
+ )
+ .await
+ .unwrap();
+
+ let kinds = entry_kinds_by_tool(&entries);
+ // Read-only blocks every non-Read class: informational, never approvable.
+ assert!(kinds.contains(&("flows_http_request".into(), "blocked".into())));
+ assert!(kinds.contains(&("flows_code".into(), "blocked".into())));
+ assert!(kinds.contains(&("SHOPIFY_CREATE_ORDER".into(), "blocked".into())));
+ assert!(!kinds.iter().any(|(_, k)| k == "approvable"), "{kinds:?}");
+}
+
+#[tokio::test]
+async fn approval_manifest_dedupes_repeated_tools_and_flags_dynamic_slugs() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let graph = structurally_valid_graph(json!({
+ "name": "dedupe-dynamic",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "h1", "kind": "http_request", "name": "One",
+ "config": { "url": "https://a.example.com", "method": "GET" } },
+ { "id": "h2", "kind": "http_request", "name": "Two",
+ "config": { "url": "https://b.example.com", "method": "POST" } },
+ { "id": "d", "kind": "tool_call", "name": "Dynamic",
+ "config": { "slug": "={{ $json.slug }}" } }
+ ],
+ "edges": [
+ { "from_node": "t", "from_port": "main", "to_node": "h1" },
+ { "from_node": "h1", "from_port": "main", "to_node": "h2" },
+ { "from_node": "h2", "from_port": "main", "to_node": "d" }
+ ]
+ }));
+ let entries = compute_approval_manifest(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &graph,
+ )
+ .await
+ .unwrap();
+
+ // Two http nodes share one trust key → exactly one row.
+ let http_rows = entries
+ .iter()
+ .filter(|e| e.get("tool_name").and_then(Value::as_str) == Some("flows_http_request"))
+ .count();
+ assert_eq!(http_rows, 1, "{entries:?}");
+ // The `=` slug cannot be pre-approved; it is disclosed as dynamic.
+ assert!(
+ entries
+ .iter()
+ .any(|e| e.get("kind").and_then(Value::as_str) == Some("dynamic")),
+ "{entries:?}"
+ );
+}
+
+#[tokio::test]
+async fn approval_manifest_discloses_agent_ref_nodes_only() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let graph = structurally_valid_graph(json!({
+ "name": "agent-disclosure",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "plain", "kind": "agent", "name": "Plain LLM",
+ "config": { "prompt": "Summarize {{input}}" } },
+ { "id": "harness", "kind": "agent", "name": "Full agent",
+ "config": { "prompt": "Do things", "agent_ref": "orchestrator" } }
+ ],
+ "edges": [
+ { "from_node": "t", "from_port": "main", "to_node": "plain" },
+ { "from_node": "plain", "from_port": "main", "to_node": "harness" }
+ ]
+ }));
+ let entries = compute_approval_manifest(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &graph,
+ )
+ .await
+ .unwrap();
+
+ let agent_rows: Vec<_> = entries
+ .iter()
+ .filter(|e| e.get("kind").and_then(Value::as_str) == Some("agent"))
+ .collect();
+ // Only the harness-backed agent node is disclosed; a plain LLM node has
+ // no acting side effect and must not scare the user with a row.
+ assert_eq!(agent_rows.len(), 1, "{entries:?}");
+ assert_eq!(
+ agent_rows[0].get("node_id").and_then(Value::as_str),
+ Some("harness")
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Run-lifecycle parity for `flows_resume` + guarded terminal writes
+// (R-M1 / R-M2 / R-M3 / R-M5 / R-m4).
+//
+// `flows_run` has had cancellation-safety since B41/B42 — register-before-row,
+// a `RunRowFinalizer` drop-guard, and terminal writes ordered row-then-summary.
+// `flows_resume` had none of it despite executing the flow's real approved side
+// effects for up to `FLOW_RUN_TIMEOUT_SECS`. These pin the mechanisms that
+// close that gap.
+
+/// R-M2: the terminal write is guarded, so a row that already settled can never
+/// be relabelled. Without the `status IN ('running','pending_approval')`
+/// predicate this was an unconditional `WHERE id = ?`.
+#[tokio::test]
+async fn finish_flow_run_refuses_to_overwrite_an_already_terminal_row() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "guarded-finish".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let run_id = "run-guarded-1";
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &now).unwrap();
+
+ // First terminal write wins.
+ let first =
+ store::finish_flow_run(&config, run_id, "completed", &now, &[], &[], None, None).unwrap();
+ assert!(first, "the first terminal write must land on a live row");
+
+ // A late cancel (or any second settler) must NOT overwrite it.
+ let second = store::finish_flow_run(
+ &config,
+ run_id,
+ "cancelled",
+ &now,
+ &[],
+ &[],
+ Some("late"),
+ None,
+ )
+ .unwrap();
+ assert!(
+ !second,
+ "a terminal row must not be overwritten by a second settler"
+ );
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(
+ row.status, "completed",
+ "the run's real outcome must survive a losing concurrent cancel"
+ );
+}
+
+/// R-M2 end-to-end: `flows_cancel_run` reads the status and consults the
+/// registry as two separate observations. A run that settles in that window is
+/// not in flight, so the "parked/stale" branch used to write `cancelled` over a
+/// completed run whose side effects had already fired.
+#[tokio::test]
+async fn cancel_does_not_relabel_a_run_that_settled_concurrently() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "cancel-toctou".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let run_id = "run-toctou-1";
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &now).unwrap();
+ // The run settles on its own (real side effects fired) and deregisters —
+ // exactly the state `flows_cancel_run` can observe one instant too late.
+ store::finish_flow_run(&config, run_id, "completed", &now, &[], &[], None, None).unwrap();
+
+ let result = flows_cancel_run(&config, run_id).await;
+ assert!(
+ result.is_err(),
+ "cancelling an already-settled run must report the conflict, not silently rewrite it"
+ );
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(
+ row.status, "completed",
+ "a completed run must never be recorded as cancelled"
+ );
+}
+
+/// R-M1 (store half): claiming a parked run for a resume is a guarded flip, so
+/// a run cancelled or TTL-expired in the meantime can never be revived.
+#[tokio::test]
+async fn mark_run_resuming_claims_only_a_parked_row() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "resume-claim".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let run_id = "run-claim-1";
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &now).unwrap();
+ // Park it.
+ store::finish_flow_run(
+ &config,
+ run_id,
+ "pending_approval",
+ &now,
+ &[],
+ &["gate".to_string()],
+ None,
+ None,
+ )
+ .unwrap();
+
+ assert!(
+ store::mark_run_resuming(&config, run_id).unwrap(),
+ "a parked run must be claimable for resume"
+ );
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+
+ // Claiming twice must not succeed — the second resume would execute the
+ // same approved side effects again.
+ assert!(
+ !store::mark_run_resuming(&config, run_id).unwrap(),
+ "a run already claimed (or cancelled/expired) must not be claimable again"
+ );
+}
+
+/// R-M1 (the race that mattered): a run approved just before its TTL used to be
+/// swept to `cancelled` — and have its durable checkpoint dropped — WHILE the
+/// resume was actively executing approved outbound nodes, because the row sat
+/// at `pending_approval` for the whole resume. Claiming it as `running` moves it
+/// out of the sweep's predicate.
+#[tokio::test]
+async fn ttl_sweep_cannot_expire_a_run_a_resume_has_claimed() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "resume-vs-ttl".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ // A run parked well past the TTL — the sweep would expire it right now.
+ let stale = (Utc::now() - chrono::Duration::seconds(FLOW_PARKED_TTL_SECS * 4)).to_rfc3339();
+ let run_id = "run-ttl-race";
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &stale).unwrap();
+ store::finish_flow_run(
+ &config,
+ run_id,
+ "pending_approval",
+ &stale,
+ &[],
+ &["gate".to_string()],
+ None,
+ None,
+ )
+ .unwrap();
+
+ // The user approves in the nick of time and the resume claims the run.
+ assert!(store::mark_run_resuming(&config, run_id).unwrap());
+
+ // Any read-path sweep that now fires must leave the in-flight resume alone.
+ sweep_expired_parked_runs(&config).await;
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(
+ row.status, "running",
+ "a claimed resume must survive the parked-run TTL sweep — expiring it would drop the \
+ checkpoint out from under a run that is executing real side effects"
+ );
+}
+
+/// A genuinely stale parked run (never claimed) must still be swept — the guard
+/// above must not have disabled the TTL sweep wholesale.
+#[tokio::test]
+async fn ttl_sweep_still_expires_an_unclaimed_parked_run() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "ttl-still-works".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let stale = (Utc::now() - chrono::Duration::seconds(FLOW_PARKED_TTL_SECS * 4)).to_rfc3339();
+ let run_id = "run-ttl-stale";
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &stale).unwrap();
+ store::finish_flow_run(
+ &config,
+ run_id,
+ "pending_approval",
+ &stale,
+ &[],
+ &["gate".to_string()],
+ None,
+ None,
+ )
+ .unwrap();
+
+ let swept = sweep_expired_parked_runs(&config).await;
+ assert_eq!(swept, 1, "an unclaimed stale parked run must still expire");
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(row.status, "cancelled");
+}
+
+/// T-M1 refusal must not clobber a run another resume already owns.
+///
+/// The stale-approval check runs BEFORE this call claims the run, so a losing
+/// resume can reach the refusal branch after a concurrent winner has flipped
+/// the row to `running` and begun executing approved side effects. Because
+/// `finish_flow_run_row`'s guard admits `running` as well as
+/// `pending_approval`, a blind write from the loser would relabel the winner's
+/// live row `cancelled` and drop a checkpoint it is actively using — the exact
+/// hazard `flows_cancel_run` already guards. The refusal must therefore treat
+/// the guarded write's verdict as the authority: refuse either way (its own
+/// view of the graph is stale), but only record the summary and drop the
+/// checkpoint when the write actually matched.
+#[tokio::test]
+async fn stale_approval_refusal_does_not_settle_a_run_another_resume_claimed() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "refusal-vs-winner".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let run_id = "run-refusal-race";
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(&config, run_id, &flow.id, run_id, &now).unwrap();
+ store::finish_flow_run(
+ &config,
+ run_id,
+ "pending_approval",
+ &now,
+ &[],
+ &["gate".to_string()],
+ None,
+ Some("hash-from-park"),
+ )
+ .unwrap();
+
+ // The winning resume claims the run: row flips to `running` and it starts
+ // executing. The loser's refusal must not touch this.
+ assert!(store::mark_run_resuming(&config, run_id).unwrap());
+
+ // The loser now settles its refusal against the claimed row.
+ let observed = current_persisted_steps(&config, run_id);
+ let settled = finish_flow_run_row(
+ &config,
+ run_id,
+ &flow.id,
+ "cancelled",
+ &observed,
+ &[],
+ Some(GRAPH_CHANGED_SINCE_PARK_ERROR),
+ None,
+ );
+
+ // The guard admits `running`, so the write DOES match — which is precisely
+ // why the refusal path must consult its verdict rather than assume the row
+ // was still parked. Pin the observable contract: whatever the write did,
+ // the caller learns about it instead of silently proceeding.
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(
+ settled,
+ row.status == "cancelled",
+ "finish_flow_run_row's return must reflect whether it actually settled the row — the \
+ refusal path keys its record_run + drop_checkpoint off this exact value"
+ );
+}
+
+#[tokio::test]
+async fn approval_manifest_never_claims_trust_that_was_never_granted() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // A candidate graph carries no flow id, so there is no `flow_tool_trust`
+ // row to join against and nothing can legitimately be "already trusted" —
+ // whether or not this process happens to have an `ApprovalGate` installed.
+ let outcome = flows_approval_manifest(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ None,
+ Some(manifest_graph_json()),
+ )
+ .await
+ .expect("manifest must compute for a candidate graph");
+
+ let already_trusted = outcome.value["already_trusted"]
+ .as_array()
+ .expect("already_trusted must be an array");
+ assert!(
+ already_trusted.is_empty(),
+ "already_trusted must never name a permission no grant was ever made for; \
+ the save+enable card renders these as authorized: {outcome:?}"
+ );
+
+ let gate_installed = outcome.value["gate_installed"]
+ .as_bool()
+ .expect("gate_installed must be a bool");
+ let missing: Vec<&str> = outcome.value["missing"]
+ .as_array()
+ .expect("missing must be an array")
+ .iter()
+ .filter_map(Value::as_str)
+ .collect();
+ if gate_installed {
+ // Gate installed, no grants held: every approvable key is asked for.
+ assert!(
+ missing.contains(&"flows_http_request") && missing.contains(&"flows_code"),
+ "{missing:?}"
+ );
+ } else {
+ // No gate: nothing ever parks, so nothing is missing either — the two
+ // lists are empty together and `gate_installed` is the only signal.
+ assert!(missing.is_empty(), "{missing:?}");
+ }
+}
+
+#[tokio::test]
+async fn get_tool_contract_rejects_a_malformed_slug_before_any_catalog_fetch() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // Each of these fails the `<TOOLKIT>_<ACTION>` shape, so the guard must
+ // fire and no live catalog round trip may be attempted (these tests run
+ // without Composio credentials or network).
+ for slug in ["nodashhere", " ", "_LEADING_UNDERSCORE", "GMAIL_"] {
+ let err = flows_get_tool_contract(&config, slug)
+ .await
+ .expect_err("a malformed slug must be rejected");
+ assert!(
+ err.contains("'<TOOLKIT>_<ACTION>'"),
+ "slug {slug:?} must get the malformed-slug message, got: {err}"
+ );
+ }
+
+ // The message names what the caller sent, not the trimmed form — a blank
+ // slug used to be reported as `slug ''`, naming nothing the caller typed.
+ let err = flows_get_tool_contract(&config, " nodashhere ")
+ .await
+ .expect_err("a malformed slug must be rejected");
+ assert!(
+ err.contains("slug ' nodashhere '"),
+ "the error must quote the caller's own slug, got: {err}"
+ );
+}
+
+#[test]
+fn toolkit_for_contract_slug_accepts_real_action_slugs() {
+ // Ordinary single-segment toolkit.
+ assert_eq!(
+ toolkit_for_contract_slug("GMAIL_SEND_EMAIL").as_deref(),
+ Some("gmail")
+ );
+ // Surrounding whitespace is tolerated, as it was before the guard.
+ assert_eq!(
+ toolkit_for_contract_slug(" GMAIL_SEND_EMAIL ").as_deref(),
+ Some("gmail")
+ );
+ // Every multi-segment toolkit prefix ends in `_`, so a real action under
+ // one of them always has non-empty segments either side of its first `_`.
+ assert_eq!(
+ toolkit_for_contract_slug("ZOHO_MAIL_SEND_EMAIL").as_deref(),
+ Some("zoho_mail")
+ );
+ assert_eq!(
+ toolkit_for_contract_slug("ONE_DRIVE_UPLOAD_FILE").as_deref(),
+ Some("one_drive")
+ );
+ assert_eq!(
+ toolkit_for_contract_slug("MICROSOFT_TEAMS_SEND_MESSAGE").as_deref(),
+ Some("microsoft_teams")
+ );
+
+ // The shared helper stays permissive for its other callers — this stricter
+ // rule is this controller's, not `toolkit_from_slug`'s.
+ assert_eq!(
+ crate::integrations::composio::contract::toolkit_from_slug("nodashhere").as_deref(),
+ Some("nodashhere")
+ );
+ assert_eq!(toolkit_for_contract_slug("nodashhere"), None);
+}
diff --git a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
index e69de29bb2..8ad1591bdd 100644
--- a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
@@ -0,0 +1,154 @@
+use super::super::trail_off::{backend_repair_message, is_backend_or_infrastructure_failure};
+use super::*;
+use crate::core::runtime::DispatchCtx;
+use crate::{
+ config::Config,
+ flows::ops::{FlowStreamTarget, flows_build_with_extra_hidden_tools},
+};
+
+#[tokio::test]
+async fn classifies_backend_failures_without_classifying_graph_timeouts() {
+ let config = Config::default();
+ assert!(
+ is_backend_or_infrastructure_failure(
+ &config,
+ "File upload failed: Backend returned 500 Internal Server Error"
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ !is_backend_or_infrastructure_failure(
+ &config,
+ "File upload failed: Backend returned 400 Bad Request"
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ is_backend_or_infrastructure_failure(
+ &config,
+ "connection timed out while calling file storage"
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ is_backend_or_infrastructure_failure(
+ &config,
+ "POST https://api.example.test/files failed: connection timed out"
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ !is_backend_or_infrastructure_failure(
+ &config,
+ "agent node fetch_profile timed out after 30 seconds"
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ !is_backend_or_infrastructure_failure(
+ &config,
+ "required argument resolved null: nodes.get_link.item.json.url"
+ )
+ .await
+ .unwrap()
+ );
+}
+
+#[tokio::test]
+async fn backend_repair_message_explains_why_the_graph_was_preserved() {
+ let message = backend_repair_message(&Config::default(), "HTTP 503 from file storage")
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert!(message.contains("workflow was not changed"));
+ assert!(message.contains("HTTP 503 from file storage"));
+ assert!(
+ backend_repair_message(
+ &Config::default(),
+ "agent node fetch_profile timed out after 30 seconds",
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[test]
+fn repair_backend_failure_returns_no_proposal_before_starting_the_builder() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(1)
+ .thread_stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .enable_all()
+ .build()
+ .expect("build agent-sized test runtime");
+
+ runtime.block_on(async {
+ let req = tinyflows_bus::copilot::BuilderPromptRequest {
+ mode: "repair".to_string(),
+ instruction: "repair the failed workflow".to_string(),
+ graph: Some(json!({"nodes": [], "edges": []})),
+ flow_id: Some("flow-1".to_string()),
+ run_id: Some("run-1".to_string()),
+ error: Some("Backend returned 503 Service Unavailable".to_string()),
+ failing_node_ids: vec!["fetch".to_string()],
+ };
+
+ let outcome = flows_build_with_extra_hidden_tools(
+ &DispatchCtx::process_default(),
+ &Config::default(),
+ req.clone(),
+ None,
+ &[],
+ )
+ .await
+ .expect("backend failure should short-circuit before the builder starts");
+
+ assert_eq!(outcome.value["proposal"], Value::Null);
+ assert_eq!(outcome.value["error"], Value::Null);
+ assert!(
+ outcome.value["assistant_text"]
+ .as_str()
+ .expect("assistant text")
+ .contains("workflow was not changed")
+ );
+
+ let request_id = format!("backend-repair-{}", uuid::Uuid::new_v4());
+ let stream = FlowStreamTarget {
+ thread_id: "backend-repair-thread".to_string(),
+ request_id: request_id.clone(),
+ };
+ let mut events = crate::web_chat::subscribe_web_channel_events();
+
+ flows_build_with_extra_hidden_tools(
+ &DispatchCtx::process_default(),
+ &Config::default(),
+ req,
+ Some(stream),
+ &[],
+ )
+ .await
+ .expect("streamed backend failure should short-circuit before the builder starts");
+
+ let done = loop {
+ match events.try_recv() {
+ Ok(event) if event.request_id == request_id => break event,
+ Ok(_) | Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
+ Err(error) => panic!("missing streamed backend-repair event: {error}"),
+ }
+ };
+ assert_eq!(done.event, "chat_done");
+ assert_eq!(done.thread_id, "backend-repair-thread");
+ assert!(
+ done.full_response
+ .as_deref()
+ .expect("terminal response text")
+ .contains("workflow was not changed")
+ );
+ });
+}
diff --git a/crates/openhuman-core/src/flows/ops_engine_compatibility_tests.rs b/crates/openhuman-core/src/flows/ops_engine_compatibility_tests.rs
index e69de29bb2..8d2db3c32d 100644
--- a/crates/openhuman-core/src/flows/ops_engine_compatibility_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_engine_compatibility_tests.rs
@@ -0,0 +1,319 @@
+use super::*;
+
+#[tokio::test]
+async fn resolver_lookup_rejects_an_incompatible_saved_child() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+
+ let error = load_engine_compatible_flow_graph(&config, &child.id)
+ .await
+ .expect_err("resolver lookup must reject an unsafe legacy child");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+}
+
+#[tokio::test]
+async fn resolver_lookup_rejects_an_incompatible_saved_grandchild() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let grandchild = store::create_flow(
+ &config,
+ "legacy unsafe grandchild".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let child = store::create_flow(
+ &config,
+ "saved child".to_string(),
+ structurally_valid_graph(referenced_child_graph(&grandchild.id)),
+ false,
+ false,
+ )
+ .unwrap();
+
+ let error = load_engine_compatible_flow_graph(&config, &child.id)
+ .await
+ .expect_err("resolver lookup must reject an unsafe saved grandchild");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+ assert!(error.contains(&grandchild.id), "{error}");
+ assert!(error.contains("saved-child"), "{error}");
+}
+
+#[tokio::test]
+async fn flows_validate_returns_stable_nested_conditional_fan_in_error() {
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ nested_conditional_fan_in_graph(),
+ )
+ .await;
+ assert!(!outcome.value.valid);
+ assert_eq!(outcome.value.error_details.len(), 1);
+ assert_eq!(
+ outcome.value.error_details[0].code,
+ UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN
+ );
+ assert_eq!(outcome.value.error_details[0].node_id.as_deref(), Some("m"));
+ assert!(outcome.value.warnings.is_empty());
+}
+
+#[tokio::test]
+async fn flows_run_rejects_legacy_nested_conditional_fan_in_before_execution() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ // Bypass the current author-time gate to simulate a definition persisted
+ // by an older OpenHuman build. Reads remain supported; execution does not.
+ let graph = structurally_valid_graph(nested_conditional_fan_in_graph());
+ let flow = store::create_flow(&config, "legacy".to_string(), graph, false, true).unwrap();
+
+ let err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &flow.id,
+ json!({ "outer": true, "inner": true }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("legacy unsafe topology must fail closed");
+ assert!(err.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN), "{err}");
+
+ let reloaded = flows_get(&config, &flow.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status, None);
+ assert_eq!(
+ reloaded.value.graph, flow.graph,
+ "stored graph must be preserved"
+ );
+}
+
+#[tokio::test]
+async fn flows_run_rejects_an_incompatible_saved_child_before_execution() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let parent = store::create_flow(
+ &config,
+ "parent".to_string(),
+ structurally_valid_graph(referenced_child_graph(&child.id)),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let error = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &parent.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("an unsafe saved child must fail before root execution starts");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+
+ let reloaded = flows_get(&config, &parent.id).await.unwrap().value;
+ assert_eq!(reloaded.last_status, None, "no run should have started");
+}
+
+#[tokio::test]
+async fn flows_update_allows_metadata_only_edits_of_legacy_incompatible_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let graph = structurally_valid_graph(nested_conditional_fan_in_graph());
+ let flow = store::create_flow(&config, "legacy".to_string(), graph, false, false).unwrap();
+
+ let updated = flows_update(
+ &config,
+ &flow.id,
+ Some("renamed legacy".to_string()),
+ None,
+ Some(true),
+ None,
+ )
+ .await
+ .expect("metadata-only update should preserve access to a legacy graph");
+
+ assert_eq!(updated.value.name, "renamed legacy");
+ assert!(updated.value.require_approval);
+ assert_eq!(updated.value.graph, flow.graph);
+}
+
+#[tokio::test]
+async fn flows_create_rejects_an_incompatible_saved_child_before_persisting() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+
+ let error = flows_create(
+ &config,
+ "rejected parent".to_string(),
+ referenced_child_graph(&child.id),
+ false,
+ )
+ .await
+ .expect_err("create must reject an unsafe saved child");
+
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+ let (flows, _skipped) = store::list_flows(&config).unwrap();
+ assert_eq!(flows.len(), 1, "the rejected parent must not be persisted");
+ assert_eq!(flows[0].id, child.id);
+}
+
+#[tokio::test]
+async fn flows_update_rejects_an_incompatible_saved_child_before_persisting() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let original_graph = structurally_valid_graph(trigger_only_graph());
+ let parent = store::create_flow(
+ &config,
+ "safe parent".to_string(),
+ original_graph.clone(),
+ false,
+ true,
+ )
+ .unwrap();
+
+ let error = flows_update(
+ &config,
+ &parent.id,
+ None,
+ Some(referenced_child_graph(&child.id)),
+ None,
+ None,
+ )
+ .await
+ .expect_err("update must reject an unsafe saved child");
+
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+ let reloaded = flows_get(&config, &parent.id).await.unwrap().value;
+ assert_eq!(
+ reloaded.graph, original_graph,
+ "the rejected graph update must not be persisted"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_rejects_graph_without_trigger() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph_without_trigger = json!({
+ "name": "bad",
+ "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],
+ "edges": []
+ });
+
+ let err = flows_create(&config, "bad".to_string(), graph_without_trigger, false)
+ .await
+ .expect_err("graph without a trigger must be rejected");
+ assert!(
+ err.contains("trigger"),
+ "expected a MissingTrigger-style error, got: {err}"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_get_list_delete_roundtrip() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+ let flow_id = created.value.id.clone();
+
+ let fetched = flows_get(&config, &flow_id).await.unwrap();
+ assert_eq!(fetched.value.id, flow_id);
+ assert_eq!(fetched.value.name, "demo");
+
+ let listed = flows_list(&config).await.unwrap();
+ assert_eq!(listed.value.len(), 1);
+
+ flows_delete(&config, &flow_id).await.unwrap();
+ assert!(flows_get(&config, &flow_id).await.is_err());
+ assert!(flows_list(&config).await.unwrap().value.is_empty());
+}
+
+#[tokio::test]
+async fn flows_duplicate_produces_disabled_unbound_copy_with_new_id() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // Enabled source with require_approval set.
+ let created = flows_create(&config, "My Flow".to_string(), trigger_only_graph(), true)
+ .await
+ .unwrap();
+ assert!(created.value.enabled);
+ let source_id = created.value.id.clone();
+
+ let dup = flows_duplicate(&config, &source_id).await.unwrap();
+
+ // New id, suffixed name, DISABLED (so no trigger is bound => never fires).
+ assert_ne!(dup.value.id, source_id);
+ assert_eq!(dup.value.name, "My Flow (copy)");
+ assert!(
+ !dup.value.enabled,
+ "a duplicate must be disabled and thus not schedule/trigger-bound"
+ );
+ // Identical graph + require_approval carried over; run history reset.
+ assert_eq!(dup.value.graph, created.value.graph);
+ assert!(dup.value.require_approval);
+ assert!(dup.value.last_run_at.is_none());
+ assert!(dup.value.last_status.is_none());
+
+ // Both flows now exist independently.
+ let listed = flows_list(&config).await.unwrap();
+ assert_eq!(listed.value.len(), 2);
+}
diff --git a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
index e69de29bb2..0bd6d8eebd 100644
--- a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
@@ -0,0 +1,569 @@
+use super::*;
+
+/// Regression for issue #4868: `flows_discover`'s `flow_discovery` agent must
+/// also resolve to its definition's effective cap (50, `iteration_policy =
+/// "extended"`), not the global default of 10. Before the systemic fix, this
+/// call site had NO override at all (unlike `flows_build`'s now-deleted
+/// `apply_builder_iteration_cap`), so it silently got the global 10 in
+/// production.
+#[tokio::test]
+async fn flows_discover_applies_the_flow_discovery_definitions_effective_iteration_cap() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ assert_eq!(config.agent.max_tool_iterations, 10);
+
+ // Building an agent constructs a memory client, which needs the host seams
+ // wired. `Once`-guarded, so this is free when another test got there first.
+ crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global(
+ &config.workspace_dir,
+ )
+ .expect("agent registry init");
+ let def = crate::agent::harness::host_definition::AgentDefinitionRegistry::global()
+ .expect("registry initialised")
+ .get("flow_discovery")
+ .expect("flow_discovery definition registered")
+ .clone();
+ let expected = def.effective_max_iterations();
+ assert_eq!(expected, 50);
+
+ let agent = crate::agent::OpenHumanSessionHost::from_config_for_agent(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "flow_discovery",
+ )
+ .expect("build flow_discovery agent");
+ assert_eq!(agent.agent_config().max_tool_iterations, expected);
+}
+
+#[tokio::test]
+async fn flows_create_rejects_condition_edges_with_branch_label_on_to_port() {
+ // The same hard gate applies at the actual persistence path
+ // (`flows_create`), not just the standalone validate helper — a graph
+ // with this shape must never reach the store.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let bad_graph = condition_graph("main", "true", "main", "false");
+ let err = flows_create(&config, "bad-condition".to_string(), bad_graph, false)
+ .await
+ .expect_err("flows_create must reject a condition graph routed on to_port");
+ assert!(
+ err.contains("condition") && err.contains("from_port"),
+ "expected an InvalidConditionRouting-style error, got: {err}"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_schedule_trigger_creates_disabled() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "scheduled".to_string(),
+ schedule_trigger_graph("30 7 * * 1-5"),
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ !created.value.enabled,
+ "a schedule-trigger flow must create disabled"
+ );
+ assert!(
+ crate::cron::find_flow_schedule_job(&config, &created.value.id)
+ .unwrap()
+ .is_none(),
+ "no cron job may be bound for a disabled-on-create schedule flow"
+ );
+ assert!(
+ created
+ .logs
+ .iter()
+ .any(|l| l.starts_with("Flow created DISABLED")),
+ "flows_create must loudly log the disabled-on-create decision: {:?}",
+ created.logs
+ );
+}
+
+#[tokio::test]
+async fn flows_create_app_event_trigger_creates_disabled() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "app-event".to_string(),
+ app_event_trigger_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ !created.value.enabled,
+ "an app_event-trigger flow must create disabled"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_manual_trigger_creates_enabled() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(&config, "manual".to_string(), manual_trigger_graph(), false)
+ .await
+ .unwrap();
+
+ assert!(
+ created.value.enabled,
+ "a manual-trigger flow only ever fires via explicit flows_run — it must create enabled"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_no_trigger_kind_creates_enabled() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(&config, "legacy".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ assert!(
+ created.value.enabled,
+ "a trigger with no trigger_kind discriminator never self-fires — not a surprise, must \
+ create enabled"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_outbound_node_forces_require_approval() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(&config, "tool-flow".to_string(), tool_call_graph(), false)
+ .await
+ .unwrap();
+
+ assert!(
+ created.value.require_approval,
+ "a graph with a tool_call node must force require_approval, even though the caller \
+ passed false"
+ );
+ assert!(
+ created
+ .logs
+ .iter()
+ .any(|l| l.contains("require_approval forced to true")),
+ "flows_create must loudly log the forced require_approval: {:?}",
+ created.logs
+ );
+}
+
+#[tokio::test]
+async fn flows_create_outbound_http_forces_require_approval() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "http-flow".to_string(),
+ http_request_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ created.value.require_approval,
+ "a graph with an http_request node must force require_approval"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_outbound_code_forces_require_approval() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(&config, "code-flow".to_string(), code_graph(), false)
+ .await
+ .unwrap();
+
+ assert!(
+ created.value.require_approval,
+ "a graph with a code node must force require_approval"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_readonly_graph_respects_caller_require_approval() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "readonly-flow".to_string(),
+ readonly_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ !created.value.require_approval,
+ "a read-only graph (no tool_call/http_request/code) must not have require_approval \
+ forced — the caller's choice stands"
+ );
+}
+
+#[tokio::test]
+async fn flows_create_schedule_outbound_creates_disabled_and_approval() {
+ // The exact bug scenario from the ticket: a scheduled flow that posts to
+ // Slack, saved with `require_approval: false` — it must come back BOTH
+ // disabled AND with require_approval forced true.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "scheduled-slack-post",
+ "nodes": [
+ {
+ "id": "t",
+ "kind": "trigger",
+ "name": "Trigger",
+ "config": { "trigger_kind": "schedule", "schedule": "30 7 * * 1-5" }
+ },
+ {
+ "id": "post",
+ "kind": "tool_call",
+ "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE", "args": { "channel": "general" } }
+ }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ });
+
+ let created = flows_create(&config, "scheduled-slack".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ assert!(
+ !created.value.enabled,
+ "a scheduled flow with an outbound node must still create disabled (Rule 1)"
+ );
+ assert!(
+ created.value.require_approval,
+ "a scheduled flow with an outbound node must force require_approval (Rule 2)"
+ );
+}
+
+#[tokio::test]
+async fn flows_update_forces_require_approval_when_adding_side_effect_nodes() {
+ // Compound bypass fix, half 2: `flows_create`'s Rule 2 (force
+ // require_approval when the graph gains an outbound side-effect node)
+ // must also re-apply on `flows_update` — a flow that starts read-only and
+ // is later edited to add a Composio/http_request/code node must not be
+ // able to keep require_approval=false just because the update path never
+ // re-checked.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+ assert!(
+ !created.value.require_approval,
+ "a trigger-only graph must not force require_approval on create"
+ );
+
+ let updated = flows_update(
+ &config,
+ &created.value.id,
+ None,
+ Some(tool_call_graph()),
+ Some(false),
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ updated.value.require_approval,
+ "flows_update must force require_approval when the replacement graph adds an outbound \
+ side-effect node (tool_call), even though the caller passed false"
+ );
+ assert!(
+ updated
+ .logs
+ .iter()
+ .any(|l| l.contains("require_approval forced to true")),
+ "flows_update must loudly log the forced require_approval: {:?}",
+ updated.logs
+ );
+}
+
+#[tokio::test]
+async fn flows_update_does_not_force_require_approval_on_readonly_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+ assert!(!created.value.require_approval);
+
+ // Name-only update — no graph change, no side-effect nodes.
+ let updated = flows_update(
+ &config,
+ &created.value.id,
+ Some("renamed".to_string()),
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ !updated.value.require_approval,
+ "a name-only update to a read-only graph must not force require_approval"
+ );
+}
+
+#[tokio::test]
+async fn strict_gate_passes_a_valid_graph_and_rejects_a_structurally_invalid_one() {
+ let config = Config::default();
+ // A trigger-only graph is structurally valid and has no outbound gates.
+ assert!(
+ strict_gate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &trigger_only_graph()
+ )
+ .await
+ .is_ok()
+ );
+
+ // No trigger → structural failure surfaced by strict mode.
+ let bad = json!({
+ "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],
+ "edges": []
+ });
+ let err = strict_gate(&crate::core::runtime::DispatchCtx::ambient(), &config, &bad)
+ .await
+ .unwrap_err();
+ assert!(err.contains("structurally invalid"), "{err}");
+ assert!(err.contains("trigger"), "{err}");
+
+ // A structurally valid graph must still pass the shared engine gate.
+ let err = strict_gate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &nested_conditional_fan_in_graph(),
+ )
+ .await
+ .unwrap_err();
+ assert!(err.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN), "{err}");
+}
+
+#[tokio::test]
+async fn strict_gate_rejects_an_incompatible_saved_child_reference() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+
+ let error = strict_gate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &referenced_child_graph(&child.id),
+ )
+ .await
+ .expect_err("strict authoring must reject an incompatible saved child");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+ assert!(error.contains("saved-child"), "{error}");
+}
+
+#[tokio::test]
+async fn builder_proposal_rejects_an_incompatible_saved_child_reference() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let parent = structurally_valid_graph(referenced_child_graph(&child.id));
+
+ let error = build_builder_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "propose_workflow",
+ "parent",
+ &parent,
+ false,
+ false,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect_err("a proposal must reject an incompatible saved child");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+ assert!(error.contains("saved-child"), "{error}");
+}
+
+#[tokio::test]
+async fn referenced_child_compatibility_stops_at_saved_workflow_cycles() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow_a = store::create_flow(
+ &config,
+ "cycle a".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let flow_b = store::create_flow(
+ &config,
+ "cycle b".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ store::update_flow_graph(
+ &config,
+ &flow_a.id,
+ flow_a.name.clone(),
+ structurally_valid_graph(referenced_child_graph(&flow_b.id)),
+ false,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+ store::update_flow_graph(
+ &config,
+ &flow_b.id,
+ flow_b.name.clone(),
+ structurally_valid_graph(referenced_child_graph(&flow_a.id)),
+ false,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+
+ let candidate = structurally_valid_graph(referenced_child_graph(&flow_a.id));
+ assert!(
+ config_aware_engine_compatibility_errors(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ serde_json::to_value(candidate).unwrap(),
+ )
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+// ── core-managed drafts (F5) ─────────────────────────────────────────────────
+
+#[tokio::test]
+async fn draft_promote_creates_a_new_flow_and_removes_the_draft() {
+ use tinyflows_catalog::DraftOrigin;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let draft = flows_draft_create(
+ &config,
+ None,
+ "From draft".to_string(),
+ trigger_only_graph(),
+ DraftOrigin::Chat,
+ )
+ .unwrap()
+ .value;
+
+ let flow = flows_draft_promote(&config, &draft.id, None)
+ .await
+ .unwrap()
+ .value;
+ assert_eq!(flow.name, "From draft");
+ // The draft file is gone once promoted.
+ assert!(flows_draft_get(&config, &draft.id).is_err());
+ // The flow really exists.
+ assert!(flows_get(&config, &flow.id).await.is_ok());
+}
+
+#[tokio::test]
+async fn draft_promote_with_flow_id_updates_the_existing_flow() {
+ use tinyflows_catalog::DraftOrigin;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let flow = flows_create(&config, "Original".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap()
+ .value;
+
+ let draft = flows_draft_create(
+ &config,
+ Some(flow.id.clone()),
+ "Renamed via draft".to_string(),
+ trigger_only_graph(),
+ DraftOrigin::Canvas,
+ )
+ .unwrap()
+ .value;
+
+ let updated = flows_draft_promote(&config, &draft.id, None)
+ .await
+ .unwrap()
+ .value;
+ assert_eq!(updated.id, flow.id, "same flow, not a new one");
+ assert_eq!(updated.name, "Renamed via draft");
+ assert!(
+ flows_draft_get(&config, &draft.id).is_err(),
+ "draft removed"
+ );
+}
+
+#[tokio::test]
+async fn draft_promote_of_invalid_graph_is_rejected_and_keeps_the_draft() {
+ use tinyflows_catalog::DraftOrigin;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // A graph with no trigger fails the create gate.
+ let bad = json!({
+ "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],
+ "edges": []
+ });
+ let draft = flows_draft_create(&config, None, "Bad".to_string(), bad, DraftOrigin::Chat)
+ .unwrap()
+ .value;
+
+ assert!(flows_draft_promote(&config, &draft.id, None).await.is_err());
+ // The draft survives a failed promote so the user can fix it.
+ assert!(flows_draft_get(&config, &draft.id).is_ok());
+}
diff --git a/crates/openhuman-core/src/flows/ops_resume_checkpoint_tests.rs b/crates/openhuman-core/src/flows/ops_resume_checkpoint_tests.rs
index e69de29bb2..c126d29f6b 100644
--- a/crates/openhuman-core/src/flows/ops_resume_checkpoint_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_resume_checkpoint_tests.rs
@@ -0,0 +1,664 @@
+use super::*;
+
+/// The success-path mirror of the refusal test above: when nothing rewrites
+/// the flow between park and resume, the recomputed hash matches the pinned
+/// one and the resume proceeds exactly as it did before this guard existed.
+#[tokio::test]
+async fn flows_resume_succeeds_when_the_graph_is_unchanged() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(run.value["pending_approvals"].clone()).unwrap();
+
+ let parked_row = flows_get_run(&config, &thread_id).await.unwrap().value;
+ assert!(
+ parked_row.graph_hash.is_some(),
+ "a freshly parked run must pin the graph it parked against"
+ );
+
+ let resumed = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ pending,
+ vec![],
+ )
+ .await
+ .expect("resume must succeed when the pinned graph still matches the current one");
+ assert_eq!(resumed.value["pending_approvals"], json!([]));
+ assert!(
+ !resumed.value["output"]["nodes"]["downstream"]["items"].is_null(),
+ "downstream should run once the gate is approved via resume"
+ );
+
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap().value;
+ assert_eq!(run_row.status, "completed");
+ assert!(
+ run_row.graph_hash.is_none(),
+ "a settled row clears its park-time pin rather than leaving it stale: {run_row:?}"
+ );
+}
+
+/// Migration safety (T-M1 requirement #4): a `flow_runs` row written before
+/// this guard existed reads back with `graph_hash IS NULL`. That must be
+/// treated as "unknown — allow, with a warning", never as a hard refusal, so
+/// upgrading mid-park can never strand an otherwise-valid in-flight approval
+/// — even if the flow's graph was *also* edited in the meantime, since there
+/// is nothing recorded to compare it against.
+#[tokio::test]
+async fn flows_resume_allows_a_legacy_row_with_null_graph_hash() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(run.value["pending_approvals"].clone()).unwrap();
+
+ // Simulate a row written before the T-M1 migration: still `pending_approval`,
+ // but with no graph hash pinned — exactly what `add_column_if_missing`
+ // leaves behind for every row that existed before this feature shipped.
+ let now = Utc::now().to_rfc3339();
+ store::finish_flow_run(
+ &config,
+ &thread_id,
+ "pending_approval",
+ &now,
+ &[],
+ &pending,
+ None,
+ None,
+ )
+ .unwrap();
+ let staged = flows_get_run(&config, &thread_id).await.unwrap().value;
+ assert!(
+ staged.graph_hash.is_none(),
+ "fixture must simulate a legacy row with no pin"
+ );
+
+ // The flow is ALSO rewritten afterward — a legacy row has nothing to
+ // compare against, so this must not matter.
+ let mut rewritten = approval_gated_graph();
+ rewritten["nodes"][2]["name"] = json!("Downstream (renamed)");
+ store::update_flow_graph(
+ &config,
+ &created.value.id,
+ created.value.name.clone(),
+ structurally_valid_graph(rewritten),
+ created.value.require_approval,
+ None, // enabled_override
+ false, // force_disarm_if_automatic — this fixture isn't exercising the
+ // manual->automatic disarm path, only the graph swap.
+ None,
+ )
+ .unwrap();
+
+ let resumed = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ pending,
+ vec![],
+ )
+ .await
+ .expect("a legacy row with no graph_hash must still resume (unknown treated as allow)");
+ assert_eq!(resumed.value["pending_approvals"], json!([]));
+}
+
+/// The stale-approval pin is a persisted format. The algorithm and its
+/// key-order / `require_approval` properties are tested in `tinyflows-catalog`;
+/// this pins the same digests in the host build, where `serde_json` has
+/// `preserve_order` active, so a feature-unification change cannot silently
+/// invalidate every parked run's pin.
+#[test]
+fn graph_hash_matches_the_persisted_vector_under_preserve_order() {
+ let graph = structurally_valid_graph(json!({
+ "name": "order-test",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ {
+ "id": "n",
+ "kind": "output_parser",
+ "name": "N",
+ "config": { "nested": { "y": 2, "x": 1 }, "b": 2, "a": 1 }
+ }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "n" } ]
+ }));
+ assert_eq!(
+ compute_graph_hash(&graph, false).as_deref(),
+ Some("33ff2f572641fba1b81c6726161314f8a9e725a6b8c33a0a119cbe0564b57ad2")
+ );
+ assert_eq!(
+ compute_graph_hash(&graph, true).as_deref(),
+ Some("a13666dfbcff29a5509b0ee4d0bc50199b47eb11cb32f5ba2b00c7ae626cd179")
+ );
+}
+
+#[tokio::test]
+async fn flows_resume_marks_an_incompatible_legacy_checkpoint_failed() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(run.value["pending_approvals"].clone()).unwrap();
+
+ // Simulate a graph persisted before the host compatibility gate existed.
+ // The store layer intentionally trusts its typed caller; authoring paths
+ // own validation.
+ let legacy_graph = structurally_valid_graph(nested_conditional_fan_in_graph());
+ store::update_flow_graph(
+ &config,
+ &created.value.id,
+ created.value.name.clone(),
+ legacy_graph.clone(),
+ created.value.require_approval,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+ // T-M1: re-pin the parked row's graph_hash to this same (legacy,
+ // incompatible) graph. Without this the fixture reads as "the graph
+ // changed after park" (a DIFFERENT bug class this same PR now catches
+ // earlier and refuses with a distinct message) rather than "the
+ // checkpoint has always been incompatible" — the scenario this test
+ // means to pin. A real legacy row predating T-M1 would carry
+ // `graph_hash: NULL` and fall through the same way (see the
+ // `flows_resume_allows_a_legacy_row_with_null_graph_hash` test above).
+ let run_row_before = flows_get_run(&config, &thread_id).await.unwrap().value;
+ let legacy_hash = compute_graph_hash(&legacy_graph, created.value.require_approval)
+ .expect("fixture graph should hash");
+ store::finish_flow_run(
+ &config,
+ &thread_id,
+ "pending_approval",
+ &run_row_before.finished_at.unwrap_or_default(),
+ &run_row_before.steps,
+ &run_row_before.pending_approvals,
+ None,
+ Some(&legacy_hash),
+ )
+ .unwrap();
+
+ let error = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ pending,
+ vec![],
+ )
+ .await
+ .expect_err("an incompatible checkpoint cannot be resumed safely");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap().value;
+ assert_eq!(run_row.status, "failed");
+ assert!(run_row.pending_approvals.is_empty());
+ assert!(
+ run_row
+ .error
+ .as_deref()
+ .is_some_and(|value| value.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN)),
+ "the terminal run row should retain the rejection reason: {run_row:?}"
+ );
+ let flow = flows_get(&config, &created.value.id).await.unwrap().value;
+ assert_eq!(flow.last_status.as_deref(), Some("failed"));
+}
+
+#[tokio::test]
+async fn flows_resume_marks_a_checkpoint_with_an_incompatible_saved_child_failed() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(run.value["pending_approvals"].clone()).unwrap();
+ let child = store::create_flow(
+ &config,
+ "legacy unsafe child".to_string(),
+ structurally_valid_graph(nested_conditional_fan_in_graph()),
+ false,
+ false,
+ )
+ .unwrap();
+ let legacy_graph = structurally_valid_graph(referenced_child_graph(&child.id));
+ store::update_flow_graph(
+ &config,
+ &created.value.id,
+ created.value.name.clone(),
+ legacy_graph.clone(),
+ created.value.require_approval,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+ // T-M1: re-pin the parked row's hash to this same graph — see the sibling
+ // legacy-checkpoint test above for why this fixture needs it now that a
+ // graph swap is independently caught by the stale-approval guard.
+ let run_row_before = flows_get_run(&config, &thread_id).await.unwrap().value;
+ let legacy_hash = compute_graph_hash(&legacy_graph, created.value.require_approval)
+ .expect("fixture graph should hash");
+ store::finish_flow_run(
+ &config,
+ &thread_id,
+ "pending_approval",
+ &run_row_before.finished_at.unwrap_or_default(),
+ &run_row_before.steps,
+ &run_row_before.pending_approvals,
+ None,
+ Some(&legacy_hash),
+ )
+ .unwrap();
+
+ let error = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ pending,
+ vec![],
+ )
+ .await
+ .expect_err("an incompatible saved child cannot be resumed safely");
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+ assert!(error.contains(&child.id), "{error}");
+
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap().value;
+ assert_eq!(run_row.status, "failed");
+ assert!(run_row.pending_approvals.is_empty());
+ assert!(
+ run_row
+ .error
+ .as_deref()
+ .is_some_and(|value| value.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN))
+ );
+ let flow = flows_get(&config, &created.value.id).await.unwrap().value;
+ assert_eq!(flow.last_status.as_deref(), Some("failed"));
+}
+
+#[tokio::test]
+async fn flows_resume_missing_flow_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "missing",
+ "thread-1",
+ vec![],
+ vec![],
+ )
+ .await
+ .expect_err("must error");
+ assert!(err.contains("not found"));
+}
+
+// ── flows_resume host-side approval guard (issue B2 finding #3) ──────────
+//
+// tinyflows 0.2's `resume_with_checkpointer` treats the resume call itself
+// as approval of whatever gate paused the run — its `approvals` argument is
+// advisory, not enforced by the crate. Live testing confirmed
+// `flows_resume(..., approvals: [])` on a paused run still completed it.
+// These tests exercise the host-side guard added in `flows::ops::flows_resume`
+// that requires `approvals` to actually name a currently-pending gate,
+// straight from the persisted `flow_runs` row, before ever calling into the
+// engine.
+
+#[tokio::test]
+async fn flows_resume_with_empty_approvals_is_rejected_and_does_not_complete_the_run() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec![],
+ vec![],
+ )
+ .await
+ .expect_err("an empty approvals list must not silently approve the pending gate");
+ assert!(
+ err.contains("no pending approval matches"),
+ "expected a clear approval-mismatch error, got: {err}"
+ );
+
+ // The run must still be sitting at pending_approval, not completed.
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "pending_approval");
+ assert_eq!(run_row.value.pending_approvals, vec!["gate".to_string()]);
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(
+ reloaded.value.last_status.as_deref(),
+ Some("pending_approval"),
+ "a rejected resume attempt must not overwrite the flow's last_status as completed"
+ );
+}
+
+#[tokio::test]
+async fn flows_resume_with_mismatched_approvals_is_rejected() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ // Names a node id that is not actually pending for this run.
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec!["not-a-real-gate".to_string()],
+ vec![],
+ )
+ .await
+ .expect_err("approvals naming no actually-pending gate must be rejected");
+ assert!(err.contains("no pending approval matches"));
+}
+
+#[tokio::test]
+async fn flows_resume_with_the_correct_gate_completes_and_runs_downstream() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let resumed = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec!["gate".to_string()],
+ vec![],
+ )
+ .await
+ .unwrap();
+ assert_eq!(resumed.value["pending_approvals"], json!([]));
+ assert!(
+ !resumed.value["output"]["nodes"]["downstream"]["items"].is_null(),
+ "downstream should run once the correct gate is named in approvals"
+ );
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("completed"));
+}
+
+#[tokio::test]
+async fn flows_resume_denying_a_gate_routes_to_its_error_port() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(
+ &config,
+ "gated-deny".to_string(),
+ approval_gated_graph_with_error_port(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ // Deny the gate: no approvals, `gate` in rejections.
+ let resumed = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec![],
+ vec!["gate".to_string()],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resumed.value["pending_approvals"], json!([]));
+ assert_eq!(
+ resumed.value["output"]["nodes"]["recover"]["items"][0]["json"]["error"]["node"],
+ json!("gate"),
+ "a denied gate must route its error item to the `error`-port recovery node"
+ );
+ assert!(
+ resumed.value["output"]["nodes"]["downstream"].is_null(),
+ "the main branch must not run when the gate is denied"
+ );
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("completed"));
+
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "completed");
+ assert!(run_row.value.pending_approvals.is_empty());
+}
+
+#[tokio::test]
+async fn flows_resume_denying_a_gate_with_no_error_port_fails_the_run() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ // `approval_gated_graph()` has only a `main` edge out of the gate — no
+ // `error` port to route a denial to, so the whole run must fail.
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec![],
+ vec!["gate".to_string()],
+ )
+ .await
+ .expect_err("denying a gate with no error port must fail the run");
+ assert!(
+ err.contains("denied"),
+ "expected a denial error, got: {err}"
+ );
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("failed"));
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "failed");
+}
+
+#[tokio::test]
+async fn flows_resume_rejects_a_gate_named_in_both_approvals_and_rejections() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec!["gate".to_string()],
+ vec!["gate".to_string()],
+ )
+ .await
+ .expect_err("a gate cannot be both approved and rejected");
+ assert!(err.contains("cannot be both approved and rejected"));
+
+ // The run must be untouched (still pending), never half-resumed.
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "pending_approval");
+}
+
+#[tokio::test]
+async fn flows_resume_of_a_non_paused_run_errors_clearly() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ // This run completes outright (no approval gate) — its recorded status
+ // is "completed", not "pending_approval".
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &thread_id,
+ vec![],
+ vec![],
+ )
+ .await
+ .expect_err("resuming an already-completed run must be a clear error, not a silent no-op");
+ assert!(
+ err.contains("not pending approval") || err.contains("no paused run"),
+ "expected a clear non-paused-run error, got: {err}"
+ );
+}
diff --git a/crates/openhuman-core/src/flows/ops_resume_race_tests.rs b/crates/openhuman-core/src/flows/ops_resume_race_tests.rs
index e69de29bb2..1a9306acc5 100644
--- a/crates/openhuman-core/src/flows/ops_resume_race_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_resume_race_tests.rs
@@ -0,0 +1,375 @@
+use super::*;
+
+fn insert_parked_run(config: &Config, flow_id: &str, run_id: &str) {
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(config, run_id, flow_id, run_id, &now).unwrap();
+ assert!(
+ store::finish_flow_run(
+ config,
+ run_id,
+ "pending_approval",
+ &now,
+ &[],
+ &["gate".into()],
+ None,
+ Some("parked-graph"),
+ )
+ .unwrap()
+ );
+}
+
+async fn park_approval_flow(config: &Config, name: &str) -> (String, String, Vec<String>) {
+ let created = flows_create(config, name.to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+ let parked = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let run_id = parked.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(parked.value["pending_approvals"].clone()).unwrap();
+ assert!(!pending.is_empty());
+ (created.value.id, run_id, pending)
+}
+
+async fn checkpoint_count(config: &Config, thread_id: &str) -> usize {
+ let checkpointer = crate::flows::tinyflows::open_flow_checkpointer(config).unwrap();
+ let thread_id = thread_id.to_string();
+ crate::storage::block_on_anyhow(
+ async move { Ok(checkpointer.get_thread(&thread_id).await?.len()) },
+ )
+ .unwrap()
+}
+
+#[tokio::test]
+async fn duplicate_resume_preserves_the_registered_run_and_parked_checkpoint() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(
+ &config,
+ "duplicate-resume".to_string(),
+ approval_gated_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+ let parked = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let run_id = parked.value["thread_id"].as_str().unwrap().to_string();
+ let pending: Vec<String> =
+ serde_json::from_value(parked.value["pending_approvals"].clone()).unwrap();
+ assert!(!pending.is_empty());
+
+ // Resume A has registered its cancellation token but has not yet flipped
+ // the durable row from pending_approval to running. Resume B must refuse
+ // to replace that token or claim the checkpoint out from under A.
+ let (active_token, active_guard) = run_registry::register(&run_id);
+ let duplicate = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &run_id,
+ pending.clone(),
+ vec![],
+ )
+ .await
+ .expect_err("a second resume must refuse an already registered run");
+ assert!(duplicate.contains("in flight"), "{duplicate}");
+ assert!(!active_token.is_cancelled());
+ assert!(run_registry::is_in_flight(&run_id));
+
+ let row = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert_eq!(row.status, "pending_approval");
+ assert_eq!(row.pending_approvals, pending);
+ let checkpointer = crate::flows::tinyflows::open_flow_checkpointer(&config).unwrap();
+ let checkpoint_thread = run_id.clone();
+ let checkpoints = crate::storage::block_on_anyhow(async move {
+ Ok(checkpointer.get_thread(&checkpoint_thread).await?.len())
+ })
+ .unwrap();
+ assert!(
+ checkpoints > 0,
+ "the active resume's checkpoint must remain stored"
+ );
+
+ drop(active_guard);
+ let resumed = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &run_id,
+ pending,
+ vec![],
+ )
+ .await
+ .expect("the preserved checkpoint must still resume after the active owner exits");
+ assert_eq!(resumed.value["pending_approvals"], json!([]));
+ assert_eq!(
+ store::get_flow_run(&config, &run_id)
+ .unwrap()
+ .unwrap()
+ .status,
+ "completed"
+ );
+}
+
+#[tokio::test]
+async fn stale_graph_refusal_does_not_settle_a_resume_claimed_after_its_snapshot() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let (flow_id, run_id, pending) = park_approval_flow(&config, "stale-resume-race").await;
+ let summary_before = store::get_flow(&config, &flow_id)
+ .unwrap()
+ .unwrap()
+ .last_status;
+ let mut changed_graph = approval_gated_graph();
+ changed_graph["nodes"][2]["name"] = json!("Downstream changed after park");
+ let flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ store::update_flow_graph(
+ &config,
+ &flow_id,
+ flow.name,
+ structurally_valid_graph(changed_graph),
+ flow.require_approval,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+
+ let mut owner = None;
+ let error = {
+ let mut claim_resume = || {
+ owner = Some(
+ run_registry::try_register(&run_id)
+ .expect("the competing resume must reserve the parked run"),
+ );
+ assert!(store::mark_run_resuming(&config, &run_id).unwrap());
+ };
+ resume::flows_resume_with_refusal_hook(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &flow_id,
+ &run_id,
+ pending,
+ vec![],
+ &mut claim_resume,
+ )
+ .await
+ .unwrap_err()
+ };
+ assert!(error.contains(GRAPH_CHANGED_SINCE_PARK_ERROR), "{error}");
+
+ let (token, guard) = owner.take().unwrap();
+ assert!(!token.is_cancelled());
+ assert!(run_registry::is_in_flight(&run_id));
+ let row = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ assert_eq!(flow.last_status, summary_before);
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+
+ let cancel = flows_cancel_run(&config, &run_id).await.unwrap();
+ assert_eq!(cancel.value["was_in_flight"], true);
+ assert!(token.is_cancelled());
+ assert_eq!(
+ store::get_flow_run(&config, &run_id)
+ .unwrap()
+ .unwrap()
+ .status,
+ "running"
+ );
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+ drop(guard);
+}
+
+#[tokio::test]
+async fn compatibility_refusal_does_not_settle_a_resume_claimed_after_its_snapshot() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let (flow_id, run_id, pending) = park_approval_flow(&config, "compatibility-resume-race").await;
+ let flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ let incompatible_graph = structurally_valid_graph(nested_conditional_fan_in_graph());
+ store::update_flow_graph(
+ &config,
+ &flow_id,
+ flow.name,
+ incompatible_graph.clone(),
+ flow.require_approval,
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+ let current_flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ let hash = compute_graph_hash(&incompatible_graph, current_flow.require_approval).unwrap();
+ let row = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert!(
+ store::finish_flow_run(
+ &config,
+ &run_id,
+ "pending_approval",
+ row.finished_at.as_deref().unwrap_or(&row.started_at),
+ &row.steps,
+ &pending,
+ None,
+ Some(&hash),
+ )
+ .unwrap()
+ );
+ let summary_before = current_flow.last_status;
+
+ let mut owner = None;
+ let error = {
+ let mut claim_resume = || {
+ owner = Some(
+ run_registry::try_register(&run_id)
+ .expect("the competing resume must reserve the parked run"),
+ );
+ assert!(store::mark_run_resuming(&config, &run_id).unwrap());
+ };
+ resume::flows_resume_with_refusal_hook(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &flow_id,
+ &run_id,
+ pending,
+ vec![],
+ &mut claim_resume,
+ )
+ .await
+ .unwrap_err()
+ };
+ assert!(
+ error.contains(UNSUPPORTED_NESTED_CONDITIONAL_FAN_IN),
+ "{error}"
+ );
+
+ let (token, guard) = owner.take().unwrap();
+ assert!(!token.is_cancelled());
+ assert!(run_registry::is_in_flight(&run_id));
+ let row = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ assert_eq!(flow.last_status, summary_before);
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+
+ let cancel = flows_cancel_run(&config, &run_id).await.unwrap();
+ assert_eq!(cancel.value["was_in_flight"], true);
+ assert!(token.is_cancelled());
+ assert_eq!(
+ store::get_flow_run(&config, &run_id)
+ .unwrap()
+ .unwrap()
+ .status,
+ "running"
+ );
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+ drop(guard);
+}
+
+#[tokio::test]
+async fn cancel_after_a_parked_snapshot_does_not_drop_a_resume_starting() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let (flow_id, run_id, _) = park_approval_flow(&config, "cancel-resume-start-race").await;
+ let observed = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert_eq!(observed.status, "pending_approval");
+ let summary_before = store::get_flow(&config, &flow_id)
+ .unwrap()
+ .unwrap()
+ .last_status;
+
+ let mut owner = None;
+ let error = {
+ let mut claim_resume = || {
+ owner = Some(
+ run_registry::try_register(&run_id)
+ .expect("the starting resume must reserve the parked run"),
+ );
+ assert!(store::mark_run_resuming(&config, &run_id).unwrap());
+ };
+ run_management::flows_cancel_run_with_snapshot(
+ &config,
+ &run_id,
+ observed,
+ &mut claim_resume,
+ )
+ .await
+ .unwrap_err()
+ };
+ assert!(
+ error.contains("settled before it could be cancelled"),
+ "{error}"
+ );
+
+ let (token, guard) = owner.take().unwrap();
+ assert!(!token.is_cancelled());
+ assert!(run_registry::is_in_flight(&run_id));
+ let row = store::get_flow_run(&config, &run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow_id).unwrap().unwrap();
+ assert_eq!(flow.last_status, summary_before);
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+
+ let cancel = flows_cancel_run(&config, &run_id).await.unwrap();
+ assert_eq!(cancel.value["was_in_flight"], true);
+ assert!(token.is_cancelled());
+ assert_eq!(
+ store::get_flow_run(&config, &run_id)
+ .unwrap()
+ .unwrap()
+ .status,
+ "running"
+ );
+ assert!(checkpoint_count(&config, &run_id).await > 0);
+ drop(guard);
+}
+
+#[tokio::test]
+async fn compatibility_refusal_does_not_label_a_resume_claimed_run_failed() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "compatibility-race".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+ let run_id = "compatibility-race-run";
+ insert_parked_run(&config, &flow.id, run_id);
+ assert!(store::mark_run_resuming(&config, run_id).unwrap());
+
+ assert!(
+ !run_management::settle_parked_run(
+ &config,
+ run_id,
+ &flow.id,
+ "failed",
+ "unsupported graph topology",
+ )
+ .await
+ );
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow.id).unwrap().unwrap();
+ assert!(flow.last_status.is_none());
+}
diff --git a/crates/openhuman-core/src/flows/ops_run_lifecycle_tests.rs b/crates/openhuman-core/src/flows/ops_run_lifecycle_tests.rs
index e69de29bb2..da4dc331f2 100644
--- a/crates/openhuman-core/src/flows/ops_run_lifecycle_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_run_lifecycle_tests.rs
@@ -0,0 +1,721 @@
+use super::*;
+
+fn insert_parked_run(config: &Config, flow_id: &str, run_id: &str) {
+ let now = Utc::now().to_rfc3339();
+ store::insert_flow_run(config, run_id, flow_id, run_id, &now).unwrap();
+ assert!(
+ store::finish_flow_run(
+ config,
+ run_id,
+ "pending_approval",
+ &now,
+ &[],
+ &["gate".into()],
+ None,
+ Some("parked-graph"),
+ )
+ .unwrap()
+ );
+}
+
+#[tokio::test]
+async fn stale_graph_refusal_leaves_a_resume_claimed_run_and_summary_untouched() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "stale-graph-race".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+ let run_id = "stale-graph-race-run";
+ insert_parked_run(&config, &flow.id, run_id);
+
+ // A winning resume claims the row between the stale graph check's read
+ // and its attempted refusal write.
+ assert!(store::mark_run_resuming(&config, run_id).unwrap());
+ assert!(
+ !run_management::settle_parked_run(
+ &config,
+ run_id,
+ &flow.id,
+ "cancelled",
+ GRAPH_CHANGED_SINCE_PARK_ERROR,
+ )
+ .await
+ );
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow.id).unwrap().unwrap();
+ assert!(flow.last_status.is_none());
+}
+
+#[tokio::test]
+async fn cancel_observed_parked_does_not_tear_down_a_resume_starting() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = store::create_flow(
+ &config,
+ "cancel-start-race".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+ let run_id = "cancel-start-race-run";
+ insert_parked_run(&config, &flow.id, run_id);
+
+ // Cancel already read `pending_approval` and found no registry entry;
+ // resume then registers and claims the row before cancel's CAS.
+ assert!(store::mark_run_resuming(&config, run_id).unwrap());
+ assert!(
+ !run_management::settle_parked_run(&config, run_id, &flow.id, "cancelled", "run cancelled")
+ .await
+ );
+
+ let row = store::get_flow_run(&config, run_id).unwrap().unwrap();
+ assert_eq!(row.status, "running");
+ let flow = store::get_flow(&config, &flow.id).unwrap().unwrap();
+ assert!(flow.last_status.is_none());
+}
+
+#[tokio::test]
+async fn flows_duplicate_missing_flow_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let err = flows_duplicate(&config, "missing").await.unwrap_err();
+ assert!(err.contains("not found"));
+}
+
+#[tokio::test]
+async fn flows_set_enabled_toggles() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+ assert!(created.value.enabled);
+
+ let disabled = flows_set_enabled(&config, &created.value.id, false)
+ .await
+ .unwrap();
+ assert!(!disabled.value.enabled);
+
+ let enabled = flows_set_enabled(&config, &created.value.id, true)
+ .await
+ .unwrap();
+ assert!(enabled.value.enabled);
+}
+
+#[tokio::test]
+async fn flows_update_replaces_name_and_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let mut new_graph = trigger_only_graph();
+ new_graph["name"] = json!("renamed-graph");
+
+ let updated = flows_update(
+ &config,
+ &created.value.id,
+ Some("renamed".to_string()),
+ Some(new_graph),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(updated.value.name, "renamed");
+ assert_eq!(updated.value.graph.name, "renamed-graph");
+}
+
+#[tokio::test]
+async fn flows_update_can_set_require_approval() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+ assert!(!created.value.require_approval);
+
+ let updated = flows_update(&config, &created.value.id, None, None, Some(true), None)
+ .await
+ .unwrap();
+ assert!(updated.value.require_approval);
+
+ // Omitting `require_approval` on a later update preserves the current value.
+ let unchanged = flows_update(&config, &created.value.id, None, None, None, None)
+ .await
+ .unwrap();
+ assert!(unchanged.value.require_approval);
+}
+
+#[tokio::test]
+async fn flows_update_rejects_invalid_replacement_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let invalid_graph = json!({
+ "name": "no-trigger",
+ "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],
+ "edges": []
+ });
+
+ let err = flows_update(
+ &config,
+ &created.value.id,
+ None,
+ Some(invalid_graph),
+ None,
+ None,
+ )
+ .await
+ .expect_err("invalid replacement graph must be rejected");
+ assert!(err.contains("trigger"));
+}
+
+#[tokio::test]
+async fn flows_run_completes_trigger_only_graph() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let outcome = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "hello": "world" }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(outcome.value["pending_approvals"], json!([]));
+ assert_eq!(
+ outcome.value["output"]["run"]["trigger"],
+ json!({ "hello": "world" })
+ );
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("completed"));
+ assert!(reloaded.value.last_run_at.is_some());
+}
+
+/// Live finding: a trigger-only graph (no downstream action nodes at all)
+/// used to report `status="completed" pending_approvals=0` from `flows_run`
+/// completely indistinguishably from a run that actually did something —
+/// "triggered but nothing happened" read as a plain success. This asserts
+/// the run still completes (running an empty flow isn't an error), but now
+/// carries a human-readable `note` in the result so the UI can show
+/// "nothing to run" instead of a bare "completed".
+#[tokio::test]
+async fn flows_run_on_trigger_only_graph_surfaces_no_actionable_nodes_note() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "empty".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let outcome = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+
+ let note = outcome.value["note"]
+ .as_str()
+ .expect("trigger-only run must carry a human-readable 'note' field");
+ assert!(
+ note.contains("no actionable nodes") || note.to_lowercase().contains("nothing"),
+ "note should explain that nothing ran, got: {note}"
+ );
+ assert!(
+ outcome.logs.iter().any(|l| l.contains("no actionable")),
+ "the note should also surface via the Outcome logs, got: {:?}",
+ outcome.logs
+ );
+
+ // Still a completed run, not an error — an empty flow isn't a failure,
+ // just a no-op that must not masquerade as having done real work.
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("completed"));
+}
+
+/// A graph with a real downstream node, wired up by an edge, must NOT carry
+/// the "nothing to run" note — only a graph with no actionable nodes at all.
+/// Uses `output_parser` nodes (like the approval-gated fixture above) rather
+/// than an `agent`/`tool_call` node so the run completes deterministically
+/// without needing a configured LLM provider or network access.
+#[tokio::test]
+async fn flows_run_on_graph_with_actionable_nodes_has_no_empty_flow_note() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "has-work",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "downstream", "kind": "output_parser", "name": "Downstream" }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "downstream" }
+ ]
+ });
+ let created = flows_create(&config, "has-work".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let outcome = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ outcome.value.get("note").is_none(),
+ "a graph with real downstream nodes must not get the empty-flow note, got: {:?}",
+ outcome.value.get("note")
+ );
+}
+
+/// `graph_has_actionable_nodes` must walk from the trigger, not merely check
+/// "any non-trigger node plus any edge". A component with edges of its own,
+/// but no path back to the trigger, is unreachable and must still surface
+/// the "nothing to run" note — a naive count-based check would have missed
+/// this and wrongly suppressed the note.
+#[tokio::test]
+async fn flows_run_on_graph_with_disconnected_component_still_surfaces_empty_flow_note() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "disconnected",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "a", "kind": "output_parser", "name": "Orphan A" },
+ { "id": "b", "kind": "output_parser", "name": "Orphan B" }
+ ],
+ "edges": [
+ // "a" -> "b" is wired up, but neither is reachable from "t" — the
+ // trigger has no outgoing edges at all.
+ { "from_node": "a", "to_node": "b" }
+ ]
+ });
+ let created = flows_create(&config, "disconnected".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let outcome = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+
+ let note = outcome.value["note"]
+ .as_str()
+ .expect("a component disconnected from the trigger must still surface the empty-flow note");
+ assert!(
+ note.contains("no actionable nodes") || note.to_lowercase().contains("nothing"),
+ "note should explain that nothing ran, got: {note}"
+ );
+}
+
+#[tokio::test]
+async fn flows_run_reports_pending_approval_and_blocks_downstream() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "approval-gated",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "gate", "kind": "output_parser", "name": "Gate", "config": { "requires_approval": true } },
+ { "id": "downstream", "kind": "output_parser", "name": "Downstream" }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "to_node": "downstream" }
+ ]
+ });
+
+ let created = flows_create(&config, "gated".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let outcome = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "x": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+
+ let pending = outcome.value["pending_approvals"].as_array().unwrap();
+ assert!(pending.iter().any(|v| v == "gate"));
+ assert!(outcome.value["output"]["nodes"]["downstream"].is_null());
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(
+ reloaded.value.last_status.as_deref(),
+ Some("pending_approval")
+ );
+}
+
+#[tokio::test]
+async fn flows_get_missing_flow_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let err = flows_get(&config, "missing").await.expect_err("must error");
+ assert!(err.contains("not found"));
+}
+
+#[tokio::test]
+async fn flows_run_missing_flow_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ "missing",
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("must error");
+ assert!(err.contains("not found"));
+}
+
+#[tokio::test]
+async fn flows_run_threads_declared_inputs_into_the_run() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "parameterized".to_string(),
+ parameterized_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ input_values(&[("repo", json!("acme/api"))]),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("a run supplying its required input must succeed");
+
+ let output = &run.value["output"];
+ assert_eq!(
+ output["run"]["inputs"]["repo"],
+ json!("acme/api"),
+ "the supplied value must reach run.inputs"
+ );
+ assert_eq!(
+ output["run"]["inputs"]["depth"],
+ json!(3),
+ "the declared default must be applied"
+ );
+ assert_eq!(
+ output["nodes"]["shape"]["items"][0]["json"]["repo"],
+ json!("acme/api"),
+ "the node's `=inputs.repo` binding must resolve"
+ );
+}
+
+#[tokio::test]
+async fn flows_run_detached_threads_and_validates_declared_inputs_too() {
+ // `run_detached` is the entry point both UI Run controls call, so a flow
+ // with a required input is only runnable from the UI through here — it must
+ // enforce the same contract as the blocking path, synchronously, before it
+ // reports a run id the caller will go on to poll.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "parameterized".to_string(),
+ parameterized_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let err = flows_run_detached(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("a missing required input must be refused before a run id is handed out");
+ assert!(err.contains("repo"), "got: {err}");
+
+ let started = flows_run_detached(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ input_values(&[("repo", json!("acme/api"))]),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("a run supplying its required input must start");
+ assert_eq!(started.value["status"], "running");
+}
+
+#[tokio::test]
+async fn flows_run_rejects_a_missing_required_input_without_creating_a_run_row() {
+ // The whole point of resolving in `prepare_flow_run`: a caller that gets
+ // this error can be certain nothing was started and nothing was recorded.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "parameterized".to_string(),
+ parameterized_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("a missing required input must fail the call");
+ assert!(
+ err.contains("repo"),
+ "the error must name the offending input, got: {err}"
+ );
+
+ let runs = flows_list_runs(&config, &created.value.id, 10)
+ .await
+ .unwrap();
+ assert!(
+ runs.value.is_empty(),
+ "a rejected call must leave no run row behind, got {:?}",
+ runs.value
+ );
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert!(
+ reloaded.value.last_run_at.is_none(),
+ "a rejected call must not stamp last_run_at"
+ );
+}
+
+#[tokio::test]
+async fn flows_run_rejects_a_wrongly_typed_or_undeclared_input() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "parameterized".to_string(),
+ parameterized_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let type_err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ input_values(&[("repo", json!("acme/api")), ("depth", json!("3"))]),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("a string for a number input must be rejected");
+ assert!(type_err.contains("depth"), "got: {type_err}");
+
+ let unknown_err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ input_values(&[("repo", json!("acme/api")), ("reop", json!("typo"))]),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("an undeclared key must be rejected rather than dropped");
+ assert!(unknown_err.contains("reop"), "got: {unknown_err}");
+}
+
+#[tokio::test]
+async fn flows_run_leaves_a_flow_declaring_no_inputs_unchanged() {
+ // The pre-existing call shape — empty `inputs` against a graph that
+ // declares none — must behave exactly as before.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "plain",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "shape", "kind": "transform", "name": "Shape",
+ "config": { "set": { "seen": "=run.trigger.hi" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "shape" } ]
+ });
+ let created = flows_create(&config, "plain".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({ "hi": 1 }),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("run");
+ assert_eq!(
+ run.value["output"]["nodes"]["shape"]["items"][0]["json"]["seen"],
+ json!(1)
+ );
+}
+
+#[tokio::test]
+async fn flows_run_records_failed_status_when_a_node_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // A `tool_call` with no `slug` errors in the node executor before reaching
+ // any external service; with the default `on_error: stop` the whole run
+ // fails deterministically — no network/credentials needed.
+ let graph = json!({
+ "name": "boom",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "x", "kind": "tool_call", "name": "X" }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "x" } ]
+ });
+
+ let created = flows_create(&config, "boom".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let err = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect_err("a run whose node errors under on_error:stop must fail");
+ assert!(!err.is_empty());
+
+ // The failed attempt must be recorded, not left on the prior state.
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(
+ reloaded.value.last_status.as_deref(),
+ Some("failed"),
+ "a failed run must record last_status=failed"
+ );
+ assert!(
+ reloaded.value.last_run_at.is_some(),
+ "a failed run must stamp last_run_at"
+ );
+}
+
+#[tokio::test]
+async fn flows_run_populates_error_when_a_continue_policy_node_errors() {
+ // Unlike the default `on_error: stop` (previous test), `"continue"` turns
+ // the node failure into data on the default port instead of failing the
+ // run future — the run settles `Ok`, but the errored step still degrades
+ // the terminal status to `"failed"` via `degrade_completed_status`. That
+ // path must still populate `FlowRun.error` (its doc contract: "Error
+ // message when status == \"failed\"") even though the engine's
+ // `ExecutionStep` carries no message of its own for this case.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let graph = json!({
+ "name": "boom-continue",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "x", "kind": "tool_call", "name": "X", "config": { "on_error": "continue" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "x" } ]
+ });
+
+ let created = flows_create(&config, "boom-continue".to_string(), graph, false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .expect("on_error:continue must settle the run future Ok, not bubble up an Err");
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "failed");
+ let error = run_row
+ .value
+ .error
+ .as_deref()
+ .expect("a degraded-to-failed run must populate FlowRun.error, not leave it None");
+ assert!(error.contains('x'), "got: {error}");
+
+ let reloaded = flows_get(&config, &created.value.id).await.unwrap();
+ assert_eq!(reloaded.value.last_status.as_deref(), Some("failed"));
+}
diff --git a/crates/openhuman-core/src/flows/ops_tests.rs b/crates/openhuman-core/src/flows/ops_tests.rs
index e69de29bb2..711528cafd 100644
--- a/crates/openhuman-core/src/flows/ops_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_tests.rs
@@ -0,0 +1,741 @@
+use super::*;
+use crate::config::Config;
+use serde_json::json;
+use tempfile::TempDir;
+
+fn test_config(tmp: &TempDir) -> Config {
+ let mut config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ // These suites are about the approval gate and the tier, which only bind
+ // with the policy on; the shipped config default is off. Without this the
+ // manifest tests pass vacuously — a disabled policy answers `Allow` for
+ // every class, so nothing is ever `blocked`.
+ config.autonomy.enabled = true;
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config
+}
+
+fn trigger_only_graph() -> Value {
+ json!({
+ "name": "trigger-only",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" }
+ ],
+ "edges": []
+ })
+}
+
+fn nested_conditional_fan_in_graph() -> Value {
+ json!({
+ "name": "nested-conditional-fan-in",
+ "nodes": [
+ { "id": "start", "kind": "trigger", "name": "Trigger" },
+ { "id": "outer", "kind": "condition", "name": "Outer", "config": { "field": "outer" } },
+ { "id": "inner", "kind": "condition", "name": "Inner", "config": { "field": "inner" } },
+ { "id": "outer_else", "kind": "output_parser", "name": "Outer else" },
+ { "id": "inner_else", "kind": "output_parser", "name": "Inner else" },
+ { "id": "a", "kind": "output_parser", "name": "A" },
+ { "id": "c", "kind": "output_parser", "name": "C" },
+ { "id": "m", "kind": "merge", "name": "Merge" }
+ ],
+ "edges": [
+ { "from_node": "start", "from_port": "main", "to_node": "outer" },
+ { "from_node": "start", "from_port": "main", "to_node": "c" },
+ { "from_node": "outer", "from_port": "true", "to_node": "inner" },
+ { "from_node": "outer", "from_port": "false", "to_node": "outer_else" },
+ { "from_node": "inner", "from_port": "true", "to_node": "a" },
+ { "from_node": "inner", "from_port": "false", "to_node": "inner_else" },
+ { "from_node": "a", "from_port": "main", "to_node": "m" },
+ { "from_node": "c", "from_port": "main", "to_node": "m" }
+ ]
+ })
+}
+
+fn referenced_child_graph(workflow_id: &str) -> Value {
+ json!({
+ "name": "parent-with-saved-child",
+ "nodes": [
+ { "id": "start", "kind": "trigger", "name": "Trigger" },
+ {
+ "id": "saved-child",
+ "kind": "sub_workflow",
+ "name": "Saved child",
+ "config": { "workflow_id": workflow_id }
+ }
+ ],
+ "edges": [
+ { "from_node": "start", "from_port": "main", "to_node": "saved-child" }
+ ]
+ })
+}
+
+fn structurally_valid_graph(value: Value) -> WorkflowGraph {
+ let graph = tinyflows::migrate::deserialize_graph(value).expect("graph should deserialize");
+ tinyflows::validate::validate(&graph).expect("fixture should be structurally valid");
+ graph
+}
+
+#[tokio::test]
+async fn flows_import_uses_the_tinyflows_authoring_module_in_a_cold_process() {
+ const CHILD_ENV: &str = "OPENHUMAN_FLOWS_IMPORT_AUTHORING_CHILD";
+ if std::env::var_os(CHILD_ENV).is_none() {
+ let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
+ .args([
+ "--exact",
+ "flows::ops::tests::flows_import_uses_the_tinyflows_authoring_module_in_a_cold_process",
+ "--nocapture",
+ "--test-threads=1",
+ ])
+ .env(CHILD_ENV, "1")
+ .output()
+ .expect("run cold-process import test");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ print!("{stdout}");
+ eprint!("{stderr}");
+ let child_output = format!("{stdout}{stderr}");
+ assert!(
+ output.status.success(),
+ "cold-process import test failed:\n{child_output}"
+ );
+ assert!(
+ child_output.contains("running 1 test")
+ && child_output.contains(
+ "flows_import_uses_the_tinyflows_authoring_module_in_a_cold_process ... ok"
+ )
+ && child_output.contains("1 passed; 0 failed"),
+ "child must prove exactly one test ran:\n{child_output}"
+ );
+ return;
+ }
+
+ assert_eq!(
+ crate::modules::state_of("tinyflows"),
+ crate::modules::ModuleState::Available,
+ "the isolated process must start with TinyFlows unloaded"
+ );
+ let result = flows_import(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ json!({
+ "name": "constant import",
+ "nodes": [{"id":"trigger","kind":"trigger","name":"Trigger"}],
+ "edges": []
+ }),
+ Some("native".to_string()),
+ )
+ .await
+ .expect("valid native graph imports")
+ .value;
+ assert_eq!(result.graph.name, "constant import");
+ assert_eq!(
+ crate::modules::state_of("tinyflows"),
+ crate::modules::ModuleState::Ready,
+ "public import must dispatch through the Authoring module"
+ );
+}
+
+/// A graph declaring `repo` (required) and `depth` (defaulted), whose single
+/// `transform` node copies both out via `=inputs.<name>`.
+fn parameterized_graph() -> Value {
+ json!({
+ "name": "parameterized",
+ "inputs": [
+ { "name": "repo", "type": "string", "required": true, "description": "Repo to review" },
+ { "name": "depth", "type": "number", "default": 3 }
+ ],
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "shape", "kind": "transform", "name": "Shape",
+ "config": { "set": { "repo": "=inputs.repo", "depth": "=inputs.depth" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "shape" } ]
+ })
+}
+
+/// Collects `pairs` into the supplied-values map `flows_run` takes.
+fn input_values(pairs: &[(&str, Value)]) -> serde_json::Map<String, Value> {
+ pairs
+ .iter()
+ .map(|(k, v)| ((*k).to_string(), v.clone()))
+ .collect()
+}
+
+// ── automatic-dispatch binding (issue B2 finding #1, revised by B29) ──────
+//
+// Live testing found that `flows_create` persisted a freshly-created,
+// `enabled = true` schedule flow WITHOUT registering its cron job — only
+// `flows_set_enabled` bound it. So a brand-new enabled schedule flow would
+// silently never fire until an app restart (boot reconcile) or a manual
+// disable→enable toggle.
+//
+// Issue B29 (save/enable safety) then found the OTHER half of that same bug:
+// `flows_create` used to default a schedule flow straight to `enabled: true`
+// on create, arming it live before the user ever saw a toggle. Rule 1 now
+// creates an automatic-trigger flow DISABLED — so these tests explicitly
+// enable via `flows_set_enabled` (the real caller-facing arming path) before
+// exercising the cron-binding behavior below, against the real `cron` store
+// (not a mock), the same way `bind_schedule_trigger` itself does.
+
+fn schedule_trigger_graph(cron_expr: &str) -> Value {
+ json!({
+ "name": "scheduled",
+ "nodes": [
+ {
+ "id": "t",
+ "kind": "trigger",
+ "name": "Trigger",
+ "config": { "trigger_kind": "schedule", "schedule": cron_expr }
+ }
+ ],
+ "edges": []
+ })
+}
+
+// ── flows_resume (issue B2) ───────────────────────────────────────────────
+
+fn approval_gated_graph() -> Value {
+ json!({
+ "name": "approval-gated",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "gate", "kind": "output_parser", "name": "Gate", "config": { "requires_approval": true } },
+ { "id": "downstream", "kind": "output_parser", "name": "Downstream" }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "to_node": "downstream" }
+ ]
+ })
+}
+
+// ── flows_resume deny semantics (issue G4) ────────────────────────────────
+
+/// A gate with BOTH a `main` edge (to `downstream`) and an `error` edge (to
+/// `recover`): denying the gate routes to `recover`, not `downstream`.
+fn approval_gated_graph_with_error_port() -> Value {
+ json!({
+ "name": "approval-gated-error-port",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "gate", "kind": "output_parser", "name": "Gate", "config": { "requires_approval": true } },
+ { "id": "downstream", "kind": "output_parser", "name": "Downstream" },
+ { "id": "recover", "kind": "output_parser", "name": "Recover" }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "gate" },
+ { "from_node": "gate", "from_port": "main", "to_node": "downstream" },
+ { "from_node": "gate", "from_port": "error", "to_node": "recover" }
+ ]
+ })
+}
+
+// ── Live run observation (issue G2) ───────────────────────────────────────
+
+use crate::flows::tinyflows::observability::FlowRunObserver;
+use std::sync::Arc as StdArc;
+// `RunObserver` must be in scope to call `on_step_finish` on the observer.
+use tinyflows::observability::{ExecutionStep, RunObserver as _, StepStatus};
+
+/// trigger -> output_parser passthrough: the parser is a non-trigger node, so
+/// the engine fires `on_step_finish` for it, exercising live persistence.
+fn passthrough_graph() -> Value {
+ json!({
+ "name": "passthrough",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "p", "kind": "output_parser", "name": "Parse" }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "p" } ]
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Unfired-trigger-kind warnings (PHASE 1a validation + PHASE 3c flows_validate)
+// ---------------------------------------------------------------------------
+
+fn webhook_trigger_graph() -> Value {
+ json!({
+ "name": "hooked",
+ "nodes": [
+ {
+ "id": "t",
+ "kind": "trigger",
+ "name": "Trigger",
+ "config": { "trigger_kind": "webhook" }
+ }
+ ],
+ "edges": []
+ })
+}
+
+// ── flows_list_connections (picker source) ──────────────────────────────
+
+use crate::integrations::composio::ComposioConnection;
+use crate::security::credentials::{HttpCredential, HttpCredentialSummary, HttpCredentialsStore};
+
+fn composio_conn(id: &str, toolkit: &str, status: &str, email: Option<&str>) -> ComposioConnection {
+ ComposioConnection {
+ id: id.to_string(),
+ toolkit: toolkit.to_string(),
+ status: status.to_string(),
+ created_at: None,
+ account_email: email.map(str::to_string),
+ workspace: None,
+ username: None,
+ }
+}
+
+fn http_summary(name: &str, scheme: &str) -> HttpCredentialSummary {
+ HttpCredentialSummary {
+ name: name.to_string(),
+ scheme: scheme.to_string(),
+ header_name: None,
+ username: None,
+ updated_at: "2026-01-01T00:00:00Z".to_string(),
+ }
+}
+
+// ── Flow Scout suggestion lifecycle ──────────────────────────────────────────
+
+fn seed_suggestion(config: &Config, id: &str) {
+ let s = tinyflows_catalog::FlowSuggestion {
+ id: id.to_string(),
+ title: format!("Idea {id}"),
+ one_liner: "does a thing".to_string(),
+ rationale: "grounded".to_string(),
+ trigger_hint: Some("schedule".to_string()),
+ steps_outline: vec!["a".to_string()],
+ suggested_connections: vec![],
+ suggested_slugs: vec![],
+ build_prompt: "Build a workflow…".to_string(),
+ confidence: 0.5,
+ status: tinyflows_catalog::SuggestionStatus::New,
+ created_at: "2026-07-05T00:00:00Z".to_string(),
+ source_run_id: None,
+ };
+ crate::flows::store::upsert_suggestions(config, &[s]).unwrap();
+}
+
+// ── validate_binding_resolvability ──────────────────────────────────────────
+
+/// Runs a candidate graph `Value` through the exact same migrate/validate
+/// path the builder tools use, for a [`WorkflowGraph`] test fixture.
+fn graph(value: Value) -> WorkflowGraph {
+ let graph = tinyflows::migrate::deserialize_graph(value).expect("test graph deserializes");
+ tinyflows::validate::validate(&graph).expect("structurally valid test graph");
+ tinyflows::compat::ensure_compatible(&graph).expect("engine-compatible test graph");
+ graph
+}
+
+// ── validate_inference_readiness (provider-connectivity author gate, B45) ──
+//
+// An `agent` node needs a working LLM inference provider the same way a
+// `tool_call` node needs a real Composio connection — but no author-time gate
+// previously checked it at all, so a signed-in user with no provider API key
+// configured on the managed backend only found out mid-run. These tests never
+// touch the network AND never install the process-global
+// `test_provider_override` seam (which would race any other test in this
+// binary that also installs it): the "construction succeeds" case points the
+// role at a local runtime (`ollama:...`), which `resolves_to_managed_backend`
+// correctly identifies as non-managed, so `probe_inference_readiness` never
+// reaches for the network; the construction-error case is engineered to fail
+// purely on a config lookup (`resolve_cloud_slug`'s "no cloud provider
+// configured for slug" branch), before any HTTP client is built.
+
+fn seed_app_session_for_gate_test(tmp: &TempDir) {
+ use crate::security::credentials::{
+ APP_SESSION_PROVIDER, AuthService, DEFAULT_AUTH_PROFILE_NAME,
+ };
+ // `verify_session_active` reads from `config.config_path.parent()`, which
+ // `test_config` sets to `tmp.path()` itself (distinct from
+ // `tmp.path()/workspace`) — seed the session there.
+ AuthService::new(tmp.path(), false)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ "test.session.jwt",
+ std::collections::HashMap::new(),
+ true,
+ )
+ .expect("seed app-session token");
+}
+
+// ── validate_tool_contracts (systemic tool-contract fix, Part 2) ───────────
+//
+// The live-catalog cache is process-global (`LIVE_CATALOG_CACHE`) — every
+// test below seeds the exact toolkit it needs via `seed_live_catalog_cache`
+// so none of this touches a live Composio backend.
+
+use crate::integrations::composio::catalog::{
+ ProbedOutputSample, ToolContract, seed_live_catalog_cache, seed_probe_cache,
+};
+
+fn seeded_slack_send_contract() -> ToolContract {
+ ToolContract {
+ slug: "SLACK_SEND_MESSAGE".to_string(),
+ toolkit: "slack".to_string(),
+ description: None,
+ required_args: vec!["channel".to_string(), "text".to_string()],
+ input_schema: None,
+ output_fields: vec!["ts".to_string(), "channel".to_string()],
+ output_schema: Some(json!({
+ "type": "object",
+ "properties": { "ts": {"type": "string"}, "channel": {"type": "string"} }
+ })),
+ primary_array_path: None,
+ // `slack` ships a static curated catalog (`catalog_for_toolkit`), so
+ // `validate_tool_contracts` now enforces the same curated-only bar
+ // `flow_tool_allowed`'s Path A does at runtime (Codex feedback on
+ // this PR) — this fixture models a real curated Slack action, not
+ // an uncurated one, since these tests exercise the required-arg /
+ // hallucinated-slug checks rather than the curation gate itself.
+ is_curated: true,
+ }
+}
+
+// ── validate_connection_refs (WS3) ──────────────────────────────────────────
+//
+// The transcript bug: the user's connections were twitter →
+// `composio:twitter:ca_JX6QU88UfSk4`, gmail → `composio:gmail:ca_vX_WA8FsqNmE`,
+// tiktok → `composio:tiktok:ca_LPCp3WQpaDma`. The agent wired
+// `composio:twitter:ca_LPCp3WQpaDma` (the TIKTOK id) onto a Twitter node and
+// every author-time gate returned ok. These tests exercise the pure matcher so
+// no live Composio backend is touched.
+
+/// Build a composio `FlowConnection` fixture (the exact shape
+/// `build_flow_connections` produces).
+fn ws3_flow_conn(toolkit: &str, id: &str) -> FlowConnection {
+ FlowConnection {
+ connection_ref: format!("composio:{toolkit}:{id}"),
+ kind: "composio".to_string(),
+ display: toolkit.to_string(),
+ toolkit: Some(toolkit.to_string()),
+ scheme: None,
+ platform_user_id: None,
+ }
+}
+
+/// The user's real connected set from the transcript.
+fn ws3_transcript_connections() -> Vec<FlowConnection> {
+ vec![
+ ws3_flow_conn("twitter", "ca_JX6QU88UfSk4"),
+ ws3_flow_conn("gmail", "ca_vX_WA8FsqNmE"),
+ ws3_flow_conn("tiktok", "ca_LPCp3WQpaDma"),
+ ]
+}
+
+/// A single tool_call node graph with `slug` + optional `connection_ref`.
+fn ws3_tool_call_graph(slug: &str, connection_ref: Option<&str>) -> WorkflowGraph {
+ let mut config = json!({ "slug": slug, "args": {} });
+ if let Some(cr) = connection_ref {
+ config["connection_ref"] = json!(cr);
+ }
+ graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "act", "kind": "tool_call", "name": "Act", "config": config }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "act" } ]
+ }))
+}
+
+fn upload_graph(path: Value) -> WorkflowGraph {
+ graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "up", "kind": "tool_call", "name": "Upload",
+ "config": { "slug": "oh:storage_upload_file", "args": { "path": path } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "up" } ]
+ }))
+}
+
+// ── validate_tool_contracts: arg-NAME validation against the input schema
+// (B13 — a misnamed/unsupported field, e.g. `text` instead of
+// `markdown_text` for `SLACK_SEND_MESSAGE`, used to sail through
+// `missing_required_args` because SOME value was present, just under the
+// wrong key) ────────────────────────────────────────────────────────────
+
+/// Models `SLACK_SEND_MESSAGE`'s real `input_schema` (naming `channel` and
+/// `markdown_text` — the live bug this fixes: `markdown_text` is the real
+/// field, `text` is not) but under a **fictional toolkit key**
+/// (`slackargnametest`), never the real `"slack"` key: `seeded_slack_send_contract`
+/// above (input_schema: `None`) also seeds `"slack"` and is used by several
+/// sibling tests in this file whose `args` still carry `text` — sharing the
+/// real key would race those tests over the process-global
+/// `LIVE_CATALOG_CACHE` entry for `"slack"` (same discipline
+/// `builder_tools_tests.rs` already applies for its own `slack`/`gmail`
+/// fixtures that don't match the shared-key contract byte-for-byte).
+fn seeded_slack_send_message_contract_with_schema() -> ToolContract {
+ ToolContract {
+ slug: "SLACKARGNAMETEST_SEND_MESSAGE".to_string(),
+ toolkit: "slackargnametest".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: Some(json!({
+ "type": "object",
+ "properties": {
+ "channel": { "type": "string" },
+ "markdown_text": { "type": "string" }
+ }
+ })),
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: false,
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// degrade_completed_status (PR2 — run honesty)
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn clean_step(node_id: &str) -> FlowRunStep {
+ FlowRunStep {
+ node_id: node_id.to_string(),
+ output: Value::Null,
+ port: None,
+ status: Some("success".to_string()),
+ duration_ms: Some(1),
+ diagnostics: Vec::new(),
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// B23/B24 — condition node branch label must be on `from_port`, not `to_port`
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn condition_graph(
+ true_from_port: &str,
+ true_to_port: &str,
+ false_from_port: &str,
+ false_to_port: &str,
+) -> Value {
+ json!({
+ "name": "condition-routing",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "gate", "kind": "condition", "name": "Gate", "config": { "field": "has_important" } },
+ { "id": "send_summary", "kind": "output_parser", "name": "Send" },
+ { "id": "done", "kind": "output_parser", "name": "Done" }
+ ],
+ "edges": [
+ { "from_node": "t", "from_port": "main", "to_node": "gate", "to_port": "main" },
+ { "from_node": "gate", "from_port": true_from_port, "to_node": "send_summary", "to_port": true_to_port },
+ { "from_node": "gate", "from_port": false_from_port, "to_node": "done", "to_port": false_to_port }
+ ]
+ })
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Issue B29 — save/enable safety: `flows_create` gating (Rule 1 + Rule 2)
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// Saving a scheduled/automatic flow used to silently arm it live and
+// unattended: `store::create_flow` hardcoded `enabled: true`, and
+// `require_approval` defaulted to `false` on most creation paths. These
+// tests exercise the two server-side rules `flows_create` now enforces,
+// regardless of what the caller passed.
+
+fn app_event_trigger_graph() -> Value {
+ json!({
+ "name": "app-event",
+ "nodes": [
+ {
+ "id": "t",
+ "kind": "trigger",
+ "name": "Trigger",
+ "config": { "trigger_kind": "app_event", "toolkit": "gmail", "event": "GMAIL_NEW_GMAIL_MESSAGE" }
+ }
+ ],
+ "edges": []
+ })
+}
+
+fn manual_trigger_graph() -> Value {
+ json!({
+ "name": "manual",
+ "nodes": [
+ {
+ "id": "t",
+ "kind": "trigger",
+ "name": "Trigger",
+ "config": { "trigger_kind": "manual" }
+ }
+ ],
+ "edges": []
+ })
+}
+
+fn tool_call_graph() -> Value {
+ json!({
+ "name": "with-tool-call",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ {
+ "id": "post",
+ "kind": "tool_call",
+ "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE", "args": { "channel": "general" } }
+ }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ })
+}
+
+fn http_request_graph() -> Value {
+ json!({
+ "name": "with-http",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ {
+ "id": "call",
+ "kind": "http_request",
+ "name": "Call",
+ "config": { "method": "GET", "url": "https://example.com" }
+ }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "call" } ]
+ })
+}
+
+fn code_graph() -> Value {
+ json!({
+ "name": "with-code",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ {
+ "id": "run",
+ "kind": "code",
+ "name": "Run",
+ "config": { "language": "javascript", "source": "return {};" }
+ }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "run" } ]
+ })
+}
+
+fn readonly_graph() -> Value {
+ json!({
+ "name": "readonly",
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "a", "kind": "agent", "name": "Summarize", "config": { "prompt": "hi" } },
+ { "id": "x", "kind": "transform", "name": "Reshape", "config": { "expression": "=item" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "a" },
+ { "from_node": "a", "to_node": "x" }
+ ]
+ })
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Builder convergence fix — trail-off backstop (`flows_build`'s terminal-state
+// guarantee: every turn ends in a proposal or a real question, never silence).
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn builder_tool_call(id: &str, name: &str) -> tinytools_agent::dialect::TranscriptEntry {
+ use tinytools_agent::dialect::NativeToolCall;
+ use tinytools_agent::dialect::TranscriptEntry;
+ TranscriptEntry::AssistantToolCalls {
+ text: None,
+ tool_calls: vec![NativeToolCall {
+ id: id.to_string(),
+ name: name.to_string(),
+ arguments: "{}".to_string(),
+ extra_content: None,
+ }],
+ reasoning_content: None,
+ extra_metadata: None,
+ }
+}
+
+fn builder_tool_result(call_id: &str, content: &str) -> tinytools_agent::dialect::TranscriptEntry {
+ use tinytools_agent::dialect::{ToolResultEntry, TranscriptEntry};
+ TranscriptEntry::ToolResults(vec![ToolResultEntry {
+ tool_call_id: call_id.to_string(),
+ content: content.to_string(),
+ trusted_verbatim: false,
+ }])
+}
+
+// ── Live-run reliability: drop-guard + boot sweep + detach (bugs B41/B42) ───
+
+/// Seeds a real flow plus an already-inserted `running` `flow_runs` row, and
+/// returns `(config, flow_id, run_id)`. The `TempDir` is returned so the caller
+/// keeps the on-disk store alive for the duration of the test.
+fn seed_running_run(tmp: &TempDir) -> (Config, String, String) {
+ let config = test_config(tmp);
+ let flow = store::create_flow(
+ &config,
+ "reliability".to_string(),
+ structurally_valid_graph(trigger_only_graph()),
+ false,
+ true,
+ )
+ .unwrap();
+ let run_id = format!("flow:{}:{}", flow.id, uuid::Uuid::new_v4());
+ // Stamped well before `PROCESS_RUN_FLOOR` so this row models what the boot
+ // sweep actually targets: a `running` row left behind by a *prior* process.
+ // Using `Utc::now()` here would make the sweep tests order-dependent — the
+ // floor is a process-wide `LazyLock`, so a sibling test that ran a real
+ // flow first would push it past a "now" seed and the row would (correctly)
+ // fall out of the candidate set.
+ store::insert_flow_run(
+ &config,
+ &run_id,
+ &flow.id,
+ &run_id,
+ PRIOR_PROCESS_STARTED_AT,
+ )
+ .unwrap();
+ (config, flow.id, run_id)
+}
+
+/// A `started_at` that provably predates this process's `PROCESS_RUN_FLOOR`.
+const PRIOR_PROCESS_STARTED_AT: &str = "2020-01-01T00:00:00+00:00";
+
+#[path = "ops_support_tests.rs"]
+mod support_tests;
+use support_tests::*;
+
+#[path = "ops_agent_binding_tests.rs"]
+mod agent_binding_tests;
+#[path = "ops_approval_manifest_and_catalog_tests.rs"]
+mod approval_manifest_and_catalog_tests;
+#[path = "ops_builder_repair_tests.rs"]
+mod builder_repair_tests;
+#[path = "ops_builder_trail_off_tests.rs"]
+mod builder_trail_off_tests;
+#[path = "ops_connection_ref_gate_tests.rs"]
+mod connection_ref_gate_tests;
+#[path = "ops_engine_compatibility_tests.rs"]
+mod engine_compatibility_tests;
+#[path = "ops_inference_gate_tests.rs"]
+mod inference_gate_tests;
+#[path = "ops_migration_and_side_effect_tests.rs"]
+mod migration_and_side_effect_tests;
+#[path = "ops_resume_checkpoint_tests.rs"]
+mod resume_checkpoint_tests;
+#[path = "ops_resume_race_tests.rs"]
+mod resume_race_tests;
+#[path = "ops_run_finalizer_tests.rs"]
+mod run_finalizer_tests;
+#[path = "ops_run_lifecycle_tests.rs"]
+mod run_lifecycle_tests;
+#[path = "ops_run_rows_and_notifications_tests.rs"]
+mod run_rows_and_notifications_tests;
+#[path = "ops_run_status_and_prompt_binding_tests.rs"]
+mod run_status_and_prompt_binding_tests;
+#[path = "ops_tool_contract_and_wiring_warnings_tests.rs"]
+mod tool_contract_and_wiring_warnings_tests;
+#[path = "ops_triggers_and_resume_tests.rs"]
+mod triggers_and_resume_tests;
+#[path = "ops_validate_warnings_and_connections_tests.rs"]
+mod validate_warnings_and_connections_tests;
diff --git a/crates/openhuman-core/src/flows/ops_tool_contract_and_wiring_warnings_tests.rs b/crates/openhuman-core/src/flows/ops_tool_contract_and_wiring_warnings_tests.rs
index e69de29bb2..f8978c93a6 100644
--- a/crates/openhuman-core/src/flows/ops_tool_contract_and_wiring_warnings_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_tool_contract_and_wiring_warnings_tests.rs
@@ -0,0 +1,691 @@
+use super::*;
+use crate::integrations::composio::catalog::{ToolContract, seed_live_catalog_cache};
+
+fn seeded_alias_contract() -> ToolContract {
+ ToolContract {
+ slug: "GOOGLEDRIVE_FIND_FILE".to_string(),
+ toolkit: "googledrive".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: None,
+ output_fields: vec!["files".to_string()],
+ output_schema: Some(json!({
+ "type": "object",
+ "properties": { "files": { "type": "array" } }
+ })),
+ primary_array_path: Some("data.files".to_string()),
+ is_curated: true,
+ }
+}
+
+#[tokio::test]
+async fn flows_get_tool_contract_rpc_warns_for_runtime_gated_uncurated_action() {
+ seed_live_catalog_cache(
+ "airtable",
+ vec![ToolContract {
+ slug: "AIRTABLE_OBSCURE_RPC_ACTION".to_string(),
+ toolkit: "airtable".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: None,
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: false,
+ }],
+ );
+
+ let outcome = flows_get_tool_contract(&Config::default(), "AIRTABLE_OBSCURE_RPC_ACTION")
+ .await
+ .expect("seeded catalog lookup should succeed");
+
+ assert_eq!(
+ outcome.value["contract"]["slug"],
+ "AIRTABLE_OBSCURE_RPC_ACTION"
+ );
+ assert_eq!(outcome.value["contract"]["is_curated"], false);
+ assert!(
+ outcome.value["runtime_gate"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("REJECTED on every real run")),
+ "RPC should explain the runtime rejection: {}",
+ outcome.value
+ );
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_accepts_a_separated_action_slug_alias() {
+ seed_live_catalog_cache("googledrive", vec![seeded_alias_contract()]);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "find", "kind": "tool_call", "name": "Find",
+ "config": { "slug": "GOOGLE_DRIVE_FIND_FILE", "args": {} } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "find" } ]
+ }));
+
+ let errors = validate_tool_contracts(&Config::default(), &g).await;
+
+ assert!(
+ errors.is_empty(),
+ "valid action alias was rejected: {errors:?}"
+ );
+}
+
+#[tokio::test]
+async fn graph_wiring_warnings_resolves_a_separated_action_slug_alias() {
+ seed_live_catalog_cache("googledrive", vec![seeded_alias_contract()]);
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "find", "kind": "tool_call", "name": "Find",
+ "config": { "slug": "GOOGLE_DRIVE_FIND_FILE", "args": {} } },
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "json.data.wrong" } },
+ { "id": "shape", "kind": "transform", "name": "Shape",
+ "config": { "set": { "file": "=nodes.find.item.json.data.wrong" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "find" },
+ { "from_node": "find", "to_node": "split" },
+ { "from_node": "find", "to_node": "shape" }
+ ]
+ }));
+
+ let warnings = graph_wiring_warnings(&Config::default(), &g).await;
+
+ assert_eq!(
+ warnings.len(),
+ 2,
+ "alias should reach both wiring checks: {warnings:?}"
+ );
+ assert!(
+ warnings
+ .iter()
+ .any(|warning| warning.contains("json.data.files")),
+ "{warnings:?}"
+ );
+ assert!(
+ warnings.iter().any(|warning| warning.contains("wrong")),
+ "{warnings:?}"
+ );
+}
+
+/// (Codex feedback on this PR) `notion` ships a static curated catalog
+/// (`catalog_for_toolkit`), so at RUNTIME `flow_tool_allowed`'s Path A
+/// hard-rejects any slug `find_curated` doesn't recognize — even a real,
+/// live action. Without this check, a real-but-uncurated action for a
+/// statically-catalogued toolkit would pass authoring/save here and then
+/// fail every single run as "tool not permitted". Uses its own toolkit key
+/// (`notion`, not `slack`/`gmail`) since it seeds different `is_curated`
+/// content than every other test sharing those keys.
+#[tokio::test]
+async fn validate_tool_contracts_rejects_a_real_but_uncurated_action_on_a_statically_catalogued_toolkit()
+ {
+ seed_live_catalog_cache(
+ "notion",
+ vec![ToolContract {
+ slug: "NOTION_UNCURATED_ACTION".to_string(),
+ toolkit: "notion".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: None,
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ // Real (a live catalog fetch found it), but NOT one of
+ // OpenHuman's curated Notion actions.
+ is_curated: false,
+ }],
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "NOTION_UNCURATED_ACTION", "args": {} } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert_eq!(errors.len(), 1, "{errors:?}");
+ assert!(
+ errors[0].contains("NOTION_UNCURATED_ACTION"),
+ "{}",
+ errors[0]
+ );
+ assert!(errors[0].contains("curated"), "{}", errors[0]);
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_skips_expression_derived_and_native_slugs() {
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "dynamic", "kind": "tool_call", "name": "Dynamic",
+ "config": { "slug": "=item.tool", "args": {} } },
+ { "id": "native", "kind": "tool_call", "name": "Native",
+ "config": { "slug": "oh:web_search", "args": {} } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "dynamic" },
+ { "from_node": "t", "to_node": "native" }
+ ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert!(errors.is_empty(), "{errors:?}");
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_skips_rather_than_rejects_when_the_catalog_is_unreachable() {
+ // No seed for this toolkit and no live backend configured — the fetch
+ // fails, and the node must be SKIPPED (never false-rejected).
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SOMEUNSEEDEDTOOLKIT_DO_THING", "args": {} } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert!(
+ errors.is_empty(),
+ "a live-catalog fetch failure must skip, not reject: {errors:?}"
+ );
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_rejects_an_arg_name_not_in_the_input_schema() {
+ seed_live_catalog_cache(
+ "slackargnametest",
+ vec![seeded_slack_send_message_contract_with_schema()],
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACKARGNAMETEST_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert_eq!(errors.len(), 1, "{errors:?}");
+ assert!(errors[0].contains("post"), "{}", errors[0]);
+ assert!(errors[0].contains("`text`"), "{}", errors[0]);
+ assert!(errors[0].contains("markdown_text"), "{}", errors[0]);
+ assert!(errors[0].contains("get_tool_contract"), "{}", errors[0]);
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_passes_the_real_arg_name_from_the_input_schema() {
+ seed_live_catalog_cache(
+ "slackargnametest",
+ vec![seeded_slack_send_message_contract_with_schema()],
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACKARGNAMETEST_SEND_MESSAGE",
+ "args": { "channel": "#general", "markdown_text": "hi" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert!(errors.is_empty(), "{errors:?}");
+}
+
+/// Uses its own cache key/toolkit (never `"slack"`/`"gmail"`) since the
+/// arg-name check must behave identically no matter which slug it's
+/// exercised against, and a dedicated, unregistered toolkit sidesteps both
+/// the process-global `LIVE_CATALOG_CACHE` sharing risk the other
+/// `validate_tool_contracts` tests accept AND the static curated-catalog
+/// gate (this toolkit has none, so `is_curated` is irrelevant here).
+#[tokio::test]
+async fn validate_tool_contracts_skips_arg_name_check_when_input_schema_is_unknown() {
+ seed_live_catalog_cache(
+ "argschemaunknown",
+ vec![ToolContract {
+ slug: "ARGSCHEMAUNKNOWN_DO_THING".to_string(),
+ toolkit: "argschemaunknown".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: None,
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: false,
+ }],
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "ARGSCHEMAUNKNOWN_DO_THING",
+ "args": { "totally_made_up_field": "hi" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert!(
+ errors.is_empty(),
+ "an unknown input_schema must skip the arg-name check, never reject: {errors:?}"
+ );
+}
+
+#[tokio::test]
+async fn validate_tool_contracts_allows_arbitrary_arg_names_when_schema_permits_additional_properties()
+ {
+ seed_live_catalog_cache(
+ "argschemaadditional",
+ vec![ToolContract {
+ slug: "ARGSCHEMAADDITIONAL_DO_THING".to_string(),
+ toolkit: "argschemaadditional".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: Some(json!({
+ "type": "object",
+ "properties": { "channel": { "type": "string" } },
+ "additionalProperties": true
+ })),
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: false,
+ }],
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "ARGSCHEMAADDITIONAL_DO_THING",
+ "args": { "channel": "#general", "any_extra_field": "hi" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let errors = validate_tool_contracts(&config, &g).await;
+ assert!(
+ errors.is_empty(),
+ "additionalProperties: true must allow arbitrary arg names: {errors:?}"
+ );
+}
+
+// ── graph_wiring_warnings: required-arg advisory + output-field/split_out.path
+// advisories (Part 2c/2d) ────────────────────────────────────────────────
+
+/// `graph_wiring_warnings`'s own required-arg check, exercised DIRECTLY
+/// (rather than through `revise_workflow`/`save_workflow`, where the newer
+/// `validate_tool_contracts` hard-rejects the identical condition first —
+/// see `revise_workflow_rejects_a_missing_required_composio_arg` in
+/// `builder_tools_tests.rs`). Keeps this advisory code path covered for any
+/// caller that consults `graph_wiring_warnings` without also running the
+/// hard gate first.
+#[tokio::test]
+async fn graph_wiring_warnings_flags_a_missing_required_arg() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general" } } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "post" } ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings
+ .iter()
+ .any(|w| w.contains("`text`") && w.contains("post")),
+ "{warnings:?}"
+ );
+}
+
+#[tokio::test]
+async fn graph_wiring_warnings_flags_a_downstream_field_not_in_output_fields() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "xform", "kind": "transform", "name": "Log",
+ // Correctly `data.`-prefixed (a real tool_call's payload is
+ // always nested under `data`), but the field itself isn't in
+ // SLACK_SEND_MESSAGE's real output_fields (`ts`/`channel`) —
+ // must WARN, not reject.
+ "config": { "set": { "note": "=nodes.post.item.json.data.not_a_real_field" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "xform" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings
+ .iter()
+ .any(|w| w.contains("not_a_real_field") && w.contains("post")),
+ "{warnings:?}"
+ );
+}
+
+#[tokio::test]
+async fn graph_wiring_warnings_is_silent_when_the_downstream_field_is_real() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "xform", "kind": "transform", "name": "Log",
+ // `data.ts` — correctly dereferences the Composio execute
+ // envelope's `data` wrapper before the real field name.
+ "config": { "set": { "note": "=nodes.post.item.json.data.ts" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "xform" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ !warnings.iter().any(|w| w.contains("not in")),
+ "a real output field must not warn: {warnings:?}"
+ );
+}
+
+/// B1 regression test: the exact "hollow run" bug. Before this fix, a
+/// binding like `=nodes.post.item.json.ts` (a REAL field name, but missing
+/// the `data.` segment every Composio `tool_call`'s runtime output wraps its
+/// payload in) was silently accepted here — it looks like a legitimate
+/// binding to a known output field, but resolves `null` at runtime because
+/// the real value lives one level deeper, under `data`. This must now WARN.
+#[tokio::test]
+async fn graph_wiring_warnings_flags_a_downstream_binding_missing_the_data_prefix() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "xform", "kind": "transform", "name": "Log",
+ // `ts` IS a real SLACK_SEND_MESSAGE output field — but without
+ // the `data.` prefix this is GUARANTEED to resolve null.
+ "config": { "set": { "note": "=nodes.post.item.json.ts" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "xform" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings.iter().any(|w| w.contains("item.json.data.ts")
+ && w.contains("post")
+ && w.contains("wraps its payload in `data`")),
+ "{warnings:?}"
+ );
+}
+
+/// Codex feedback on this PR: a binding to the WHOLE payload
+/// (`=nodes.post.item.json.data`, e.g. wiring an agent's `input_context` off
+/// the entire tool_call result) must NOT be flagged as "missing the `data.`
+/// segment" — it already IS the `data` field, there's nothing to strip a
+/// prefix off of. Before this fix the code suggested rewiring to the
+/// nonsense `item.json.data.data`.
+#[tokio::test]
+async fn graph_wiring_warnings_is_silent_for_a_whole_payload_binding() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "xform", "kind": "transform", "name": "Log",
+ "config": { "set": { "note": "=nodes.post.item.json.data" } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "xform" }
+ ]
+ }));
+ assert!(
+ graph_wiring_warnings(&config, &g).await.is_empty(),
+ "{:?}",
+ graph_wiring_warnings(&config, &g).await
+ );
+}
+
+/// Codex feedback on this PR: `ComposioExecuteResponse`'s OTHER top-level
+/// envelope fields (`successful`, `error`, `costUsd`, `markdownFormatted`)
+/// live alongside `data`, not inside it — a binding straight to one of
+/// these is real and legitimate. Before this fix the code flagged
+/// `.item.json.successful` / `.item.json.error` as missing the `data.`
+/// segment and suggested the nonsense `item.json.data.successful`.
+#[tokio::test]
+async fn graph_wiring_warnings_is_silent_for_composio_envelope_metadata_fields() {
+ seed_live_catalog_cache("slack", vec![seeded_slack_send_contract()]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACK_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "xform", "kind": "transform", "name": "Log",
+ "config": { "set": {
+ "ok": "=nodes.post.item.json.successful",
+ "err": "=nodes.post.item.json.error"
+ } } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "xform" }
+ ]
+ }));
+ assert!(
+ graph_wiring_warnings(&config, &g).await.is_empty(),
+ "{:?}",
+ graph_wiring_warnings(&config, &g).await
+ );
+}
+
+#[tokio::test]
+async fn graph_wiring_warnings_suggests_the_real_split_out_path() {
+ let mut contract = seeded_slack_send_contract();
+ contract.slug = "SLACKFANOUT_SEND_MESSAGE".to_string();
+ contract.toolkit = "slackfanout".to_string();
+ contract.primary_array_path = Some("data.messages".to_string());
+ seed_live_catalog_cache("slackfanout", vec![contract]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "SLACKFANOUT_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "items" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "split" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings.iter().any(|w| w.contains("json.data.messages")),
+ "{warnings:?}"
+ );
+}
+
+/// B12 enforcement: a `split_out.path` that resolves to a NON-array (an
+/// object, here) against a KNOWN output schema is flagged even though the
+/// action names no array anywhere (`primary_array_path` is `None`) — there
+/// is nothing to *suggest*, but a definite non-array hit is still a strong
+/// "wrong array path" signal worth catching at build time.
+#[tokio::test]
+async fn graph_wiring_warnings_flags_a_split_out_path_that_resolves_to_a_non_array() {
+ // seeded_slack_send_contract's output_schema names only scalar fields
+ // (ts/channel) — a real, known schema with no array in it anywhere.
+ let mut contract = seeded_slack_send_contract();
+ contract.slug = "NONARRAYFANOUT_SEND_MESSAGE".to_string();
+ contract.toolkit = "nonarrayfanout".to_string();
+ seed_live_catalog_cache("nonarrayfanout", vec![contract]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "NONARRAYFANOUT_SEND_MESSAGE",
+ "args": { "channel": "#general", "text": "hi" } } },
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "json.data" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "split" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings
+ .iter()
+ .any(|w| w.contains("split") && w.contains("does not name an array")),
+ "{warnings:?}"
+ );
+}
+
+/// The non-array enforcement stays SILENT when the action's output schema is
+/// genuinely unknown (not just "known but arrayless") — nothing real to check
+/// the path against, so no false positive.
+#[tokio::test]
+async fn graph_wiring_warnings_is_silent_on_split_out_when_schema_is_wholly_unknown() {
+ let contract = ToolContract {
+ slug: "UNKNOWNSCHEMA_DO_THING".to_string(),
+ toolkit: "unknownschema".to_string(),
+ description: None,
+ required_args: vec![],
+ input_schema: None,
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: true,
+ };
+ seed_live_catalog_cache("unknownschema", vec![contract]);
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "UNKNOWNSCHEMA_DO_THING", "args": {} } },
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "json.data" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "split" }
+ ]
+ }));
+ assert!(
+ graph_wiring_warnings(&config, &g).await.is_empty(),
+ "{:?}",
+ graph_wiring_warnings(&config, &g).await
+ );
+}
+
+/// B12 end-to-end: the EXACT live bug shape (flow "funny reminders v2").
+/// `GITHUB_LIST_REPOSITORY_ISSUES`-equivalent contract has NO schema at all
+/// (`output_schema: None`, `primary_array_path: None` — verified live for
+/// every GitHub action), so before a probe the enforcement above has nothing
+/// to check the configured `"json.data"` against and stays silent. Once
+/// `get_tool_output_sample` has probed the slug (seeded here via
+/// `seed_probe_cache`, standing in for a real bounded call), the cached
+/// `primary_array_path` overrides the schema-derived (absent) hint and the
+/// EXISTING mismatch-suggestion path fires with the real nested path.
+#[tokio::test]
+async fn graph_wiring_warnings_suggests_the_probed_split_out_path_when_schema_is_unknown() {
+ let contract = ToolContract {
+ slug: "GHPROBEFANOUT_LIST_REPOSITORY_ISSUES".to_string(),
+ toolkit: "ghprobefanout".to_string(),
+ description: None,
+ required_args: vec!["owner".to_string(), "repo".to_string()],
+ input_schema: None,
+ output_fields: vec![],
+ output_schema: None,
+ primary_array_path: None,
+ is_curated: true,
+ };
+ seed_live_catalog_cache("ghprobefanout", vec![contract]);
+ seed_probe_cache(
+ "GHPROBEFANOUT_LIST_REPOSITORY_ISSUES",
+ ProbedOutputSample {
+ primary_array_path: Some("data.issues".to_string()),
+ output_fields: vec!["issues".to_string(), "total_count".to_string()],
+ sample: json!({ "data": { "issues": [], "total_count": 0 } }),
+ },
+ );
+ let config = Config::default();
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "GHPROBEFANOUT_LIST_REPOSITORY_ISSUES",
+ "args": { "owner": "acme", "repo": "widgets" } } },
+ // The exact wrong guess observed live: whole-payload access
+ // instead of the real nested `data.issues`.
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "json.data" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "split" }
+ ]
+ }));
+ let warnings = graph_wiring_warnings(&config, &g).await;
+ assert!(
+ warnings.iter().any(|w| w.contains("json.data.issues")),
+ "{warnings:?}"
+ );
+
+ // Fixed: once config.path matches the probed real path, the warning
+ // clears.
+ let fixed = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "post", "kind": "tool_call", "name": "Post",
+ "config": { "slug": "GHPROBEFANOUT_LIST_REPOSITORY_ISSUES",
+ "args": { "owner": "acme", "repo": "widgets" } } },
+ { "id": "split", "kind": "split_out", "name": "Split",
+ "config": { "path": "json.data.issues" } }
+ ],
+ "edges": [
+ { "from_node": "t", "to_node": "post" },
+ { "from_node": "post", "to_node": "split" }
+ ]
+ }));
+ assert!(
+ graph_wiring_warnings(&config, &fixed).await.is_empty(),
+ "{:?}",
+ graph_wiring_warnings(&config, &fixed).await
+ );
+}
diff --git a/crates/openhuman-core/src/flows/ops_validate_warnings_and_connections_tests.rs b/crates/openhuman-core/src/flows/ops_validate_warnings_and_connections_tests.rs
index e69de29bb2..30e56b16dc 100644
--- a/crates/openhuman-core/src/flows/ops_validate_warnings_and_connections_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_validate_warnings_and_connections_tests.rs
@@ -0,0 +1,618 @@
+use super::*;
+
+#[tokio::test]
+async fn flows_cancel_run_of_a_completed_with_warnings_run_errors() {
+ // A settled `completed_with_warnings` run (run honesty, PR2) must be just
+ // as terminal as a plain `completed` run — otherwise `flows_cancel_run`
+ // falls through to its not-in-flight path and overwrites the row (and the
+ // flow summary) as `"cancelled"`, silently discarding the warning status
+ // the run already recorded.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ // Force the settled row to the warning status directly — an end-to-end
+ // null-binding graph isn't needed to exercise this guard.
+ // Fixture-only forcing write: the run above already settled `completed`, so
+ // `finish_flow_run`'s liveness guard (correctly) refuses a terminal →
+ // terminal transition. Staging a row at an arbitrary terminal status is a
+ // test concern, not a production one.
+ store::force_run_status_for_test(&config, &thread_id, "completed_with_warnings", None).unwrap();
+
+ let err = flows_cancel_run(&config, &thread_id)
+ .await
+ .expect_err("cancelling a completed_with_warnings run must be a clear error");
+ assert!(err.contains("already terminal"), "got: {err}");
+
+ // And the row must still read back as the warning status, not overwritten.
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "completed_with_warnings");
+}
+
+#[tokio::test]
+async fn flows_cancel_run_of_an_interrupted_run_errors() {
+ // An `interrupted` run (bug B42 — reconciled by the drop-guard / boot
+ // sweep) is terminal: cancelling it must be a clear error, never fall
+ // through to the not-in-flight path and clobber the row to `"cancelled"`,
+ // discarding the interruption reason it already carries.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "demo".to_string(), trigger_only_graph(), false)
+ .await
+ .unwrap();
+
+ let run = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let thread_id = run.value["thread_id"].as_str().unwrap().to_string();
+
+ // Force the settled row to `interrupted` directly.
+ // Fixture-only forcing write — see the sibling test above: the run has
+ // already settled, and `finish_flow_run` now (correctly) refuses a
+ // terminal -> terminal transition.
+ store::force_run_status_for_test(
+ &config,
+ &thread_id,
+ "interrupted",
+ Some("interrupted mid-flight"),
+ )
+ .unwrap();
+
+ let err = flows_cancel_run(&config, &thread_id)
+ .await
+ .expect_err("cancelling an interrupted run must be a clear error");
+ assert!(err.contains("already terminal"), "got: {err}");
+
+ // And the row must still read back as `interrupted`, not overwritten.
+ let run_row = flows_get_run(&config, &thread_id).await.unwrap();
+ assert_eq!(run_row.value.status, "interrupted");
+ assert_eq!(
+ run_row.value.error.as_deref(),
+ Some("interrupted mid-flight")
+ );
+}
+
+#[tokio::test]
+async fn flows_cancel_run_missing_run_errors() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let err = flows_cancel_run(&config, "no-such-run")
+ .await
+ .expect_err("must error for an unknown run");
+ assert!(err.contains("not found"));
+}
+
+// ── parked-run TTL sweep (issue G4) ───────────────────────────────────────
+
+#[tokio::test]
+async fn parked_run_ttl_sweep_expires_stale_runs_but_spares_fresh_ones() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let created = flows_create(&config, "gated".to_string(), approval_gated_graph(), false)
+ .await
+ .unwrap();
+
+ // Seed a parked run whose "parked since" (finished_at) is far in the past,
+ // so it is well beyond the TTL.
+ let stale_id = format!("flow:{}:stale-run", created.value.id);
+ let ancient = "2000-01-01T00:00:00+00:00";
+ store::insert_flow_run(&config, &stale_id, &created.value.id, &stale_id, ancient).unwrap();
+ store::finish_flow_run(
+ &config,
+ &stale_id,
+ "pending_approval",
+ ancient,
+ &[],
+ &["gate".to_string()],
+ None,
+ None,
+ )
+ .unwrap();
+
+ // A genuinely fresh parked run (just paused now) must survive the sweep.
+ let fresh = flows_run(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ json!({}),
+ serde_json::Map::new(),
+ FlowRunTrigger::Rpc,
+ )
+ .await
+ .unwrap();
+ let fresh_id = fresh.value["thread_id"].as_str().unwrap().to_string();
+
+ let swept = sweep_expired_parked_runs(&config).await;
+ assert_eq!(swept, 1, "only the stale parked run should be swept");
+
+ let stale_row = store::get_flow_run(&config, &stale_id).unwrap().unwrap();
+ assert_eq!(stale_row.status, "cancelled");
+ assert!(
+ stale_row.error.unwrap_or_default().contains("expired"),
+ "an expired run's error must note the TTL expiry"
+ );
+
+ let fresh_row = store::get_flow_run(&config, &fresh_id).unwrap().unwrap();
+ assert_eq!(
+ fresh_row.status, "pending_approval",
+ "a run parked within the TTL must not be swept"
+ );
+
+ // The swept run is no longer resumable.
+ let err = flows_resume(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &created.value.id,
+ &stale_id,
+ vec!["gate".to_string()],
+ vec![],
+ )
+ .await
+ .expect_err("an expired parked run must not be resumable");
+ assert!(err.contains("not pending approval") || err.contains("no paused run"));
+}
+
+#[tokio::test]
+async fn flows_validate_warns_on_unfired_webhook_trigger() {
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ webhook_trigger_graph(),
+ )
+ .await;
+ assert!(outcome.value.valid, "a webhook graph is structurally valid");
+ assert!(outcome.value.errors.is_empty());
+ assert_eq!(
+ outcome.value.warnings.len(),
+ 1,
+ "an unfired webhook trigger must produce exactly one warning: {:?}",
+ outcome.value.warnings
+ );
+ assert!(
+ outcome.value.warnings[0].contains("webhook")
+ && outcome.value.warnings[0].contains("does not fire"),
+ "warning must name the kind and explain it does not fire: {:?}",
+ outcome.value.warnings
+ );
+}
+
+#[tokio::test]
+async fn flows_validate_does_not_warn_on_schedule_trigger() {
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ schedule_trigger_graph("0 9 * * *"),
+ )
+ .await;
+ assert!(outcome.value.valid);
+ assert!(
+ outcome.value.warnings.is_empty(),
+ "a schedule trigger fires — it must not warn: {:?}",
+ outcome.value.warnings
+ );
+}
+
+#[tokio::test]
+async fn flows_validate_reports_error_for_graph_without_trigger() {
+ let graph = json!({
+ "name": "bad",
+ "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],
+ "edges": []
+ });
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ graph,
+ )
+ .await;
+ assert!(!outcome.value.valid);
+ assert_eq!(outcome.value.errors.len(), 1);
+ assert!(outcome.value.errors[0].contains("trigger"));
+ assert!(
+ outcome.value.warnings.is_empty(),
+ "an invalid graph reports no warnings"
+ );
+}
+
+#[tokio::test]
+async fn flows_validate_accumulates_every_structural_error() {
+ // A graph with several independent problems: no trigger, a duplicate node
+ // id, and a dangling edge. Multi-error validation must surface all of them
+ // in one call (fail-fast would report only the first).
+ let graph = json!({
+ "name": "riddled",
+ "nodes": [
+ { "id": "dup", "kind": "agent", "name": "One" },
+ { "id": "dup", "kind": "agent", "name": "Two" }
+ ],
+ "edges": [ { "from_node": "dup", "to_node": "ghost" } ]
+ });
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ graph,
+ )
+ .await;
+ assert!(!outcome.value.valid);
+ // errors[] and error_details[] must be 1:1.
+ assert_eq!(
+ outcome.value.errors.len(),
+ outcome.value.error_details.len(),
+ "errors and error_details must be parallel: {:?} vs {:?}",
+ outcome.value.errors,
+ outcome.value.error_details
+ );
+ assert!(
+ outcome.value.errors.len() >= 3,
+ "expected >=3 accumulated errors, got {:?}",
+ outcome.value.errors
+ );
+ let codes: Vec<&str> = outcome
+ .value
+ .error_details
+ .iter()
+ .map(|e| e.code.as_str())
+ .collect();
+ assert!(codes.contains(&"missing_trigger"), "{codes:?}");
+ assert!(codes.contains(&"duplicate_node_id"), "{codes:?}");
+ assert!(codes.contains(&"unknown_node"), "{codes:?}");
+ // A node-anchored error carries its node id; a graph-wide one does not.
+ let dup = outcome
+ .value
+ .error_details
+ .iter()
+ .find(|e| e.code == "duplicate_node_id")
+ .unwrap();
+ assert_eq!(dup.node_id.as_deref(), Some("dup"));
+ let missing = outcome
+ .value
+ .error_details
+ .iter()
+ .find(|e| e.code == "missing_trigger")
+ .unwrap();
+ assert_eq!(missing.node_id, None);
+}
+
+#[tokio::test]
+async fn flows_validate_reports_unparseable_graph_as_single_error() {
+ // A pre-validation failure (an unknown node kind can't deserialize) is a
+ // genuine single error, not a structural-error accumulation.
+ let graph = json!({
+ "name": "bad",
+ "nodes": [ { "id": "a", "kind": "not_a_real_kind", "name": "A" } ],
+ "edges": []
+ });
+ let outcome = flows_validate(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &Config::default(),
+ graph,
+ )
+ .await;
+ assert!(!outcome.value.valid);
+ assert_eq!(outcome.value.errors.len(), 1);
+ assert_eq!(outcome.value.error_details.len(), 1);
+ assert_eq!(outcome.value.error_details[0].code, "unparseable_graph");
+}
+
+#[tokio::test]
+async fn flows_set_enabled_surfaces_unfired_trigger_warning_at_enable() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "hooked".to_string(),
+ webhook_trigger_graph(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ // A webhook trigger is automatic (B29 Rule 1) so `flows_create` leaves it
+ // disabled — enable it explicitly here to exercise the enable path's
+ // warning.
+ let enabled = flows_set_enabled(&config, &created.value.id, true)
+ .await
+ .unwrap();
+ assert!(enabled.value.enabled);
+ assert!(
+ enabled
+ .logs
+ .iter()
+ .any(|l| l.starts_with("warning:") && l.contains("webhook")),
+ "enabling a webhook-trigger flow must surface a loud warning log, got: {:?}",
+ enabled.logs
+ );
+}
+
+#[tokio::test]
+async fn flows_set_enabled_schedule_flow_has_no_warning() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let created = flows_create(
+ &config,
+ "scheduled".to_string(),
+ schedule_trigger_graph("0 9 * * *"),
+ false,
+ )
+ .await
+ .unwrap();
+
+ let enabled = flows_set_enabled(&config, &created.value.id, true)
+ .await
+ .unwrap();
+ assert!(
+ !enabled.logs.iter().any(|l| l.starts_with("warning:")),
+ "a schedule-trigger flow must not surface an unfired-trigger warning: {:?}",
+ enabled.logs
+ );
+}
+
+#[test]
+fn build_flow_connections_emits_parseable_refs_for_both_kinds() {
+ let composio = vec![composio_conn(
+ "ca_abc",
+ "Gmail",
+ "ACTIVE",
+ )];
+ let http = vec![http_summary("stripe", "bearer")];
+
+ let out = build_flow_connections(composio, http, &[], &Default::default());
+ assert_eq!(out.len(), 2);
+
+ let gmail = &out[0];
+ assert_eq!(gmail.kind, "composio");
+ // Toolkit is normalized (lowercased) and the ref round-trips through the
+ // exact parser the caps seam uses on execution.
+ assert_eq!(gmail.connection_ref, "composio:gmail:ca_abc");
+ assert_eq!(
+ crate::flows::tinyflows::caps::composio_connection_id(&gmail.connection_ref),
+ Some("ca_abc")
+ );
+ assert_eq!(gmail.toolkit.as_deref(), Some("gmail"));
+ assert_eq!(gmail.display, "Gmail · [email protected]");
+ assert!(gmail.scheme.is_none());
+ assert!(gmail.platform_user_id.is_none());
+
+ let stripe = &out[1];
+ assert_eq!(stripe.kind, "http");
+ assert_eq!(stripe.connection_ref, "http_cred:stripe");
+ assert_eq!(
+ crate::flows::tinyflows::caps::http_cred_name(&stripe.connection_ref),
+ Some("stripe")
+ );
+ assert_eq!(stripe.scheme.as_deref(), Some("bearer"));
+ assert_eq!(stripe.display, "stripe (bearer)");
+ assert!(stripe.toolkit.is_none());
+ assert!(stripe.platform_user_id.is_none());
+}
+
+#[test]
+fn build_flow_connections_skips_non_active_composio_accounts() {
+ let composio = vec![
+ composio_conn("ca_ok", "notion", "ACTIVE", None),
+ composio_conn("ca_pending", "slack", "PENDING", None),
+ ];
+ let out = build_flow_connections(composio, Vec::new(), &[], &Default::default());
+ assert_eq!(out.len(), 1, "only the ACTIVE connection is surfaced");
+ assert_eq!(out[0].connection_ref, "composio:notion:ca_ok");
+ // No cached identity → title-cased toolkit alone.
+ assert_eq!(out[0].display, "Notion");
+}
+
+#[test]
+fn build_flow_connections_never_carries_secret_fields() {
+ let out = build_flow_connections(
+ vec![composio_conn("ca_abc", "gmail", "ACTIVE", Some("[email protected]"))],
+ vec![http_summary("stripe", "header")],
+ &[],
+ &Default::default(),
+ );
+ let json = serde_json::to_string(&out).unwrap();
+ // The serialized picker payload must expose only ref/kind/display/toolkit/
+ // scheme/platform_user_id — no secret-bearing key names at all.
+ for banned in [
+ "secret", "token", "password", "\"key\"", "apiKey", "api_key",
+ ] {
+ assert!(
+ !json
+ .to_ascii_lowercase()
+ .contains(&banned.to_ascii_lowercase()),
+ "serialized FlowConnection leaked a secret-bearing field ({banned}): {json}"
+ );
+ }
+}
+
+#[test]
+fn build_flow_connections_attaches_platform_user_id_from_a_seeded_identity() {
+ use crate::integrations::composio::contract::ConnectedIdentity;
+
+ let composio = vec![composio_conn("ca_slack1", "slack", "ACTIVE", None)];
+ let identities = vec![ConnectedIdentity {
+ source: "slack".to_string(),
+ identifier: "ca_slack1".to_string(),
+ user_id: Some("U123ABC".to_string()),
+ ..Default::default()
+ }];
+
+ let out = build_flow_connections(composio, Vec::new(), &identities, &Default::default());
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].platform_user_id.as_deref(), Some("U123ABC"));
+}
+
+#[test]
+fn build_flow_connections_platform_user_id_is_none_without_a_matching_identity() {
+ use crate::integrations::composio::contract::ConnectedIdentity;
+
+ // No identities at all.
+ let composio = vec![composio_conn("ca_slack1", "slack", "ACTIVE", None)];
+ let out = build_flow_connections(composio, Vec::new(), &[], &Default::default());
+ assert_eq!(out.len(), 1);
+ assert!(out[0].platform_user_id.is_none());
+
+ // An identity exists, but for a different toolkit/connection — must not
+ // cross-wire onto this connection.
+ let composio = vec![composio_conn("ca_slack1", "slack", "ACTIVE", None)];
+ let identities = vec![ConnectedIdentity {
+ source: "gmail".to_string(),
+ identifier: "ca_slack1".to_string(),
+ user_id: Some("U123ABC".to_string()),
+ ..Default::default()
+ }];
+ let out = build_flow_connections(composio, Vec::new(), &identities, &Default::default());
+ assert_eq!(out.len(), 1);
+ assert!(out[0].platform_user_id.is_none());
+}
+
+#[test]
+fn title_case_toolkit_handles_underscores_and_dashes() {
+ assert_eq!(title_case_toolkit("gmail"), "Gmail");
+ assert_eq!(title_case_toolkit("google_calendar"), "Google Calendar");
+ assert_eq!(title_case_toolkit("google-sheets"), "Google Sheets");
+ assert_eq!(title_case_toolkit(""), "");
+}
+
+#[tokio::test]
+async fn flows_list_connections_aggregates_http_creds_and_tolerates_composio() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ // Force Direct mode with no key so the composio source short-circuits to an
+ // empty list offline (no network) — proving the aggregation still returns
+ // the HTTP-credential half.
+ config.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.to_string();
+ // Secrets in the clear at rest for the test (mirrors the E2E config).
+ config.secrets.encrypt = false;
+
+ // Seed one HTTP credential through the same store the op reads.
+ let store = HttpCredentialsStore::from_config(&config);
+ store
+ .upsert(&HttpCredential::bearer("stripe", "sk_live_seed_secret"))
+ .unwrap();
+
+ let outcome = flows_list_connections(&crate::core::runtime::DispatchCtx::ambient(), &config)
+ .await
+ .unwrap();
+ let refs: Vec<_> = outcome
+ .value
+ .iter()
+ .map(|c| c.connection_ref.as_str())
+ .collect();
+ assert!(
+ refs.contains(&"http_cred:stripe"),
+ "http_cred must be surfaced: {refs:?}"
+ );
+
+ // The secret must never appear anywhere in the RPC payload.
+ let json = serde_json::to_string(&outcome.value).unwrap();
+ assert!(
+ !json.contains("sk_live_seed_secret"),
+ "secret leaked into flows_list_connections payload: {json}"
+ );
+}
+
+#[tokio::test]
+async fn list_suggestions_filters_by_status() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ seed_suggestion(&config, "s1");
+ seed_suggestion(&config, "s2");
+
+ let active = flows_list_suggestions(&config, Some(tinyflows_catalog::SuggestionStatus::New))
+ .await
+ .unwrap();
+ assert_eq!(active.value.len(), 2);
+
+ // Unfiltered returns all too.
+ let all = flows_list_suggestions(&config, None).await.unwrap();
+ assert_eq!(all.value.len(), 2);
+}
+
+#[tokio::test]
+async fn dismiss_and_mark_built_move_suggestions_out_of_active() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ seed_suggestion(&config, "s1");
+ seed_suggestion(&config, "s2");
+
+ let d = flows_dismiss_suggestion(&config, "s1").await.unwrap();
+ assert_eq!(d.value["dismissed"], json!(true));
+ let b = flows_mark_suggestion_built(&config, "s2").await.unwrap();
+ assert_eq!(b.value["built"], json!(true));
+
+ // Neither is in the active (New) set anymore.
+ let active = flows_list_suggestions(&config, Some(tinyflows_catalog::SuggestionStatus::New))
+ .await
+ .unwrap();
+ assert!(active.value.is_empty());
+}
+
+#[tokio::test]
+async fn dismiss_unknown_suggestion_reports_not_found() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let d = flows_dismiss_suggestion(&config, "missing").await.unwrap();
+ assert_eq!(d.value["dismissed"], json!(false));
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// FlowStreamTarget (Phase B copilot/scout streaming) — pure param plumbing.
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn flow_stream_target_none_without_thread_id() {
+ // No thread → headless run, regardless of request_id.
+ assert!(FlowStreamTarget::from_params(None, None).is_none());
+ assert!(FlowStreamTarget::from_params(None, Some("r-1".to_string())).is_none());
+}
+
+#[test]
+fn flow_stream_target_blank_thread_id_is_absent() {
+ // Whitespace-only thread id is treated as no thread (callers pass raw input).
+ assert!(FlowStreamTarget::from_params(Some(" ".to_string()), None).is_none());
+ assert!(FlowStreamTarget::from_params(Some(String::new()), None).is_none());
+}
+
+#[test]
+fn flow_stream_target_trims_and_keeps_request_id() {
+ let t = FlowStreamTarget::from_params(Some(" t-1 ".to_string()), Some(" r-1 ".to_string()))
+ .expect("stream target");
+ assert_eq!(t.thread_id, "t-1");
+ assert_eq!(t.request_id, "r-1");
+}
+
+#[test]
+fn flow_stream_target_generates_request_id_when_absent_or_blank() {
+ // Absent request id → a fresh uuid is minted.
+ let a = FlowStreamTarget::from_params(Some("t-1".to_string()), None).expect("target");
+ assert!(!a.request_id.is_empty());
+ assert_ne!(a.request_id, a.thread_id);
+ // Blank request id is treated the same way.
+ let b = FlowStreamTarget::from_params(Some("t-1".to_string()), Some(" ".to_string()))
+ .expect("target");
+ assert!(!b.request_id.is_empty());
+ // Two mints are distinct uuids.
+ assert_ne!(a.request_id, b.request_id);
+}
diff --git a/crates/openhuman-core/src/flows/registration_tests.rs b/crates/openhuman-core/src/flows/registration_tests.rs
index e69de29bb2..a8954febbd 100644
--- a/crates/openhuman-core/src/flows/registration_tests.rs
+++ b/crates/openhuman-core/src/flows/registration_tests.rs
@@ -0,0 +1,42 @@
+use super::*;
+use serde_json::{Value, json};
+
+/// The persisted catalogue is recorded in session transcripts
+/// (`session_host/recorded_tools.rs`), so every tool's name, description,
+/// parameter schema, permission and external-effect flag must stay
+/// byte-identical across moves of the code behind it. Regenerate the snapshot
+/// deliberately with `UPDATE_FLOW_TOOL_SNAPSHOT=1`.
+fn catalogue() -> Value {
+ let config = Arc::new(Config::default());
+ let security = Arc::new(SecurityPolicy::default());
+ Value::Array(
+ tools(config, &security)
+ .iter()
+ .map(|t| {
+ json!({
+ "name": t.name(),
+ "description": t.description(),
+ "parameters": t.parameters_schema(),
+ "permission": format!("{:?}", t.permission_level()),
+ "external_effect": t.external_effect(),
+ })
+ })
+ .collect(),
+ )
+}
+
+#[test]
+fn flow_tool_catalogue_matches_recorded_snapshot() {
+ let actual = catalogue();
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("src/flows/registration_tests/flow_tools.snap.json");
+ if std::env::var_os("UPDATE_FLOW_TOOL_SNAPSHOT").is_some() {
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, serde_json::to_string_pretty(&actual).unwrap() + "\n").unwrap();
+ }
+ let expected: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ assert_eq!(
+ actual, expected,
+ "flow tool catalogue drifted from registration_tests/flow_tools.snap.json"
+ );
+}
diff --git a/crates/openhuman-core/src/flows/schemas.rs b/crates/openhuman-core/src/flows/schemas.rs
index e69de29bb2..83888af3b9 100644
--- a/crates/openhuman-core/src/flows/schemas.rs
+++ b/crates/openhuman-core/src/flows/schemas.rs
@@ -0,0 +1,394 @@
+//! RPC/CLI controller surface for the `flows::` domain. Mirrors
+//! `crates/openhuman-core/src/cron/schemas.rs`'s shape exactly: `schemas(function)` builds
+//! one `ControllerSchema`, `all_controller_schemas()`/
+//! `all_registered_controllers()` aggregate them, and each `handle_*` loads
+//! config, reads params, awaits the matching `ops::flows_*` fn, and converts
+//! the `Outcome` to CLI-compatible JSON.
+
+use serde_json::{Map, Value};
+
+use crate::core::all::{ControllerFuture, RegisteredController};
+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::flows::ops;
+
+fn id_input(comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment,
+ required: true,
+ }
+}
+
+fn flow_output() -> FieldSchema {
+ FieldSchema {
+ name: "flow",
+ ty: TypeSchema::Ref("Flow"),
+ comment: "The flow definition.",
+ required: true,
+ }
+}
+
+fn draft_output() -> FieldSchema {
+ FieldSchema {
+ name: "draft",
+ ty: TypeSchema::Json,
+ comment: "The draft: { id, flow_id?, name, graph, origin, created_at, updated_at }.",
+ required: true,
+ }
+}
+
+/// Output field for the suggestion-returning controllers (`discover`,
+/// `list_suggestions`). Kept in one place so the schema mirrors
+/// `flows::types::FlowSuggestion`.
+fn suggestions_output() -> FieldSchema {
+ FieldSchema {
+ name: "suggestions",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Object {
+ fields: flow_suggestion_fields(),
+ })),
+ comment: "Discovered workflow suggestions (pitches, not graphs) for the Flows page.",
+ required: true,
+ }
+}
+
+/// Per-field schema for one `FlowSuggestion`, mirroring
+/// `flows::types::FlowSuggestion` exactly.
+fn flow_suggestion_fields() -> Vec<FieldSchema> {
+ vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Stable content-hash id (dedupes identical ideas across runs).",
+ required: true,
+ },
+ FieldSchema {
+ name: "title",
+ ty: TypeSchema::String,
+ comment: "Short, human-friendly title.",
+ required: true,
+ },
+ FieldSchema {
+ name: "one_liner",
+ ty: TypeSchema::String,
+ comment: "One-sentence description of what the workflow would do.",
+ required: true,
+ },
+ FieldSchema {
+ name: "rationale",
+ ty: TypeSchema::String,
+ comment: "Why this is suggested to this user, grounded in observed signals.",
+ required: true,
+ },
+ FieldSchema {
+ name: "trigger_hint",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Likely trigger: `schedule` | `app_event` | `manual`.",
+ required: false,
+ },
+ FieldSchema {
+ name: "steps_outline",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Plain-language step outline, one per element.",
+ required: true,
+ },
+ FieldSchema {
+ name: "suggested_connections",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Real connection_ref values grounded via list_flow_connections.",
+ required: true,
+ },
+ FieldSchema {
+ name: "suggested_slugs",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Real Composio action slugs grounded via search_tool_catalog.",
+ required: true,
+ },
+ FieldSchema {
+ name: "build_prompt",
+ ty: TypeSchema::String,
+ comment: "Self-contained brief handed to workflow_builder on 'Build this'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "confidence",
+ ty: TypeSchema::F64,
+ comment: "Agent's confidence in [0,1] that this is useful + buildable.",
+ required: true,
+ },
+ FieldSchema {
+ name: "status",
+ ty: TypeSchema::String,
+ comment: "Lifecycle: `new` | `dismissed` | `built`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "created_at",
+ ty: TypeSchema::String,
+ comment: "RFC3339 timestamp when first discovered.",
+ required: true,
+ },
+ FieldSchema {
+ name: "source_run_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "The discovery run that produced this suggestion, if tracked.",
+ required: false,
+ },
+ ]
+}
+
+/// Optional `thread_id` streaming param shared by `build` + `discover`. When
+/// the copilot/scout passes a chat thread id, the turn streams live
+/// text/thinking/tool/proposal socket events into that thread (Phase B) instead
+/// of running headless; omitting it keeps the prior blocking-only behaviour.
+fn stream_thread_id_input() -> FieldSchema {
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Chat thread to stream this turn into (copilot/scout live view). \
+ Omit for a headless run — the blocking result is returned either way.",
+ required: false,
+ }
+}
+
+/// Optional `request_id` streaming param (per-turn correlation id). Only
+/// meaningful alongside `thread_id`; a fresh uuid is generated when absent.
+fn stream_request_id_input() -> FieldSchema {
+ FieldSchema {
+ name: "request_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Per-turn correlation id for the streamed events (matches the \
+ frontend request_id). Generated when omitted; ignored without `thread_id`.",
+ required: false,
+ }
+}
+
+fn require_approval_input() -> FieldSchema {
+ FieldSchema {
+ name: "require_approval",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "Force a human-approval gate on every outbound tool/HTTP action this flow \
+ takes, regardless of its saved-flow trust root. Defaults to `false`.",
+ required: false,
+ }
+}
+
+fn expected_version_input() -> FieldSchema {
+ FieldSchema {
+ name: "expected_version",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optimistic-concurrency token: the flow's `updated_at` as last observed. If the \
+ flow has changed since, the write is refused with a structured version_conflict \
+ error carrying the current flow, instead of clobbering. Omit for last-write-wins.",
+ required: false,
+ }
+}
+
+fn strict_input() -> FieldSchema {
+ FieldSchema {
+ name: "strict",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "Run the same author hard-gates an agent save must pass (unresolvable bindings, \
+ unreal tool slugs, unwired required args) before persisting, rejecting the \
+ write if any fail. Defaults to `false` — the permissive human-canvas path.",
+ required: false,
+ }
+}
+
+fn run_output_fields() -> Vec<FieldSchema> {
+ vec![
+ FieldSchema {
+ name: "output",
+ ty: TypeSchema::Json,
+ comment: "The run's final state (per-node items, trigger payload).",
+ required: true,
+ },
+ FieldSchema {
+ name: "pending_approvals",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Node ids paused awaiting human approval; empty once completed.",
+ required: true,
+ },
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::String,
+ comment: "Durable checkpoint thread id for this run (needed to resume).",
+ required: true,
+ },
+ ]
+}
+
+fn run_detached_output_fields() -> Vec<FieldSchema> {
+ vec![
+ FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Durable checkpoint thread id for this run (same identifier `flows_get_run` \
+ / `flows_cancel_run` / `flows_resume` expect).",
+ required: true,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the flow that was started.",
+ required: true,
+ },
+ FieldSchema {
+ name: "status",
+ ty: TypeSchema::String,
+ comment: "Always `\"running\"` at the moment this call returns; poll `flows_get_run` \
+ or subscribe to `flow:run_progress` for the terminal state.",
+ required: true,
+ },
+ FieldSchema {
+ name: "detached",
+ ty: TypeSchema::Bool,
+ comment: "Always `true` — marks this response as the immediate, non-blocking shape, \
+ distinct from `run`'s completed-run payload.",
+ required: true,
+ },
+ ]
+}
+
+/// Field schema for one `FlowConnection` element of `flows_list_connections`'s
+/// output. Kept in one place so the schema mirrors
+/// `flows::types::FlowConnection` exactly — and documents that no secret field
+/// exists on the wire.
+fn flow_connection_fields() -> Vec<FieldSchema> {
+ vec![
+ FieldSchema {
+ name: "connection_ref",
+ ty: TypeSchema::String,
+ comment: "Ready-to-use `connection_ref` to stamp onto a node: \
+ `composio:<toolkit>:<connection_id>` or `http_cred:<name>`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "kind",
+ ty: TypeSchema::String,
+ comment: "Source kind: `composio` | `http`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "display",
+ ty: TypeSchema::String,
+ comment: "Human-readable picker label (e.g. `Gmail · [email protected]`). \
+ Never secret material.",
+ required: true,
+ },
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Composio toolkit slug (kind `composio` only).",
+ required: false,
+ },
+ FieldSchema {
+ name: "scheme",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "HTTP credential injection scheme (kind `http` only): \
+ `bearer` | `basic` | `header`.",
+ required: false,
+ },
+ FieldSchema {
+ name: "platform_user_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Connected account's own platform user id (kind `composio` only), \
+ e.g. Slack `U123ABC`. Non-secret identity metadata — lets the \
+ workflow builder wire a self-targeted action (e.g. \"DM me\") to \
+ the user's own account instead of guessing a public channel. \
+ `None` when no identity has synced yet.",
+ required: false,
+ },
+ ]
+}
+
+pub fn all_controller_schemas() -> Vec<ControllerSchema> {
+ vec![
+ schemas("create"),
+ schemas("duplicate"),
+ schemas("validate"),
+ schemas("import"),
+ schemas("get"),
+ schemas("list"),
+ schemas("list_connections"),
+ schemas("update"),
+ schemas("delete"),
+ schemas("set_enabled"),
+ schemas("run"),
+ schemas("run_detached"),
+ schemas("resume"),
+ schemas("cancel_run"),
+ schemas("list_runs"),
+ schemas("list_all_runs"),
+ schemas("get_run"),
+ schemas("prune_runs"),
+ schemas("build"),
+ schemas("build_cancel"),
+ schemas("discover"),
+ schemas("list_suggestions"),
+ schemas("dismiss_suggestion"),
+ schemas("mark_suggestion_built"),
+ schemas("draft_create"),
+ schemas("draft_get"),
+ schemas("draft_update"),
+ schemas("draft_list"),
+ schemas("draft_delete"),
+ schemas("draft_promote"),
+ schemas("get_history"),
+ schemas("rollback"),
+ schemas("search_tool_catalog"),
+ schemas("get_tool_contract"),
+ schemas("required_connections"),
+ schemas("approval_manifest"),
+ ]
+}
+
+pub fn all_registered_controllers() -> Vec<RegisteredController> {
+ registered::all_registered_controllers()
+}
+
+mod builder_schemas;
+mod definition_schemas;
+mod draft_schemas;
+mod handlers;
+mod registered;
+mod run_schemas;
+
+/// Builds the `ControllerSchema` for one `flows.<function>`. Each schema
+/// group owns a disjoint set of function names; an unknown name yields the
+/// placeholder schema below.
+pub fn schemas(function: &str) -> ControllerSchema {
+ if let Some(schema) = definition_schemas::lookup(function) {
+ return schema;
+ }
+ if let Some(schema) = run_schemas::lookup(function) {
+ return schema;
+ }
+ if let Some(schema) = builder_schemas::lookup(function) {
+ return schema;
+ }
+ if let Some(schema) = draft_schemas::lookup(function) {
+ return schema;
+ }
+ ControllerSchema {
+ namespace: "flows",
+ function: "unknown",
+ description: "Unknown flows controller function.",
+ inputs: vec![FieldSchema {
+ name: "function",
+ ty: TypeSchema::String,
+ comment: "Unknown function requested for schema lookup.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
+ }
+}
+
+#[cfg(test)]
+#[path = "schemas_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/schemas/builder_schemas.rs b/crates/openhuman-core/src/flows/schemas/builder_schemas.rs
index e69de29bb2..1293ce60dc 100644
--- a/crates/openhuman-core/src/flows/schemas/builder_schemas.rs
+++ b/crates/openhuman-core/src/flows/schemas/builder_schemas.rs
@@ -0,0 +1,239 @@
+//! Schemas for the authoring copilot (`build`/`build_cancel`), the tool
+//! catalog it browses, and workflow discovery suggestions.
+
+use super::{
+ ControllerSchema, FieldSchema, TypeSchema, id_input, stream_request_id_input,
+ stream_thread_id_input, suggestions_output,
+};
+
+/// Builds the schema for `function` when this group owns it.
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+ "build" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "build",
+ description: "Run the workflow_builder agent for one authoring turn. `mode` selects \
+ create (first draft from `instruction`), revise (refine the injected \
+ `graph`), repair (diagnose a failed `run_id` and fix), or build \
+ (instant-create: build + dry-run + propose against `flow_id`; \
+ propose-only, see #4596). The server renders the agent's brief — the \
+ frontend no longer crafts prompts. Returns `{ proposal, assistant_text, \
+ error }`, where `proposal` is the `{ type: 'workflow_proposal', name, \
+ graph, require_approval, summary, warnings }` the agent produced (or \
+ null). No mode auto-persists a graph; save/enable/run stay behind the \
+ user's explicit action.",
+ inputs: vec![
+ FieldSchema {
+ name: "mode",
+ ty: TypeSchema::String,
+ comment: "One of: `create` | `revise` | `repair` | `build`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "instruction",
+ ty: TypeSchema::String,
+ comment: "The user's ask: description (create/build) or change instruction \
+ (revise); optional note for repair.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "The current draft WorkflowGraph, injected as context for \
+ revise/repair/build.",
+ required: false,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Saved flow id — required for `build` (save target); optional \
+ elsewhere (lets the agent run_flow it to test, with confirmation).",
+ required: false,
+ },
+ FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Failed run id (== thread id) for `repair`, so the agent can \
+ get_flow_run it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "error",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Run-level error message for `repair`, if known.",
+ required: false,
+ },
+ FieldSchema {
+ name: "failing_node_ids",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Node ids implicated in the failure, for `repair` (array of strings).",
+ required: false,
+ },
+ stream_thread_id_input(),
+ stream_request_id_input(),
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ proposal, assistant_text, error }` — `proposal` is the workflow \
+ proposal the agent produced (or null); `error` is set if the run failed \
+ but a prior proposal was still captured.",
+ required: true,
+ }],
+ }),
+ "build_cancel" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "build_cancel",
+ description: "Cancel the in-flight `flows_build` (Workflow Copilot) turn streaming \
+ into `thread_id` — the real cancellation behind the composer's Stop \
+ button. When `request_id` is given, the cancel only fires if it \
+ matches the turn currently registered on the thread (a stale Stop for \
+ a superseded request can't kill a newer turn); omit it to cancel \
+ whatever turn is on the thread. `cancelled: false` is not an error — it \
+ just means nothing was in flight (already settled, or never started).",
+ inputs: vec![
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::String,
+ comment: "The copilot's dedicated chat thread id (the same `thread_id` \
+ passed to `flows.build`'s streaming params).",
+ required: true,
+ },
+ FieldSchema {
+ name: "request_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Per-turn correlation id to scope the cancel to (matches the \
+ `request_id` `flows.build` streamed with). Omit to cancel \
+ unscoped.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![FieldSchema {
+ name: "cancelled",
+ ty: TypeSchema::Bool,
+ comment: "True when an in-flight build turn was found and signalled to \
+ cancel.",
+ required: true,
+ }],
+ },
+ comment: "Cancellation result payload.",
+ required: true,
+ }],
+ }),
+ "search_tool_catalog" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "search_tool_catalog",
+ description: "Search the live Composio tool catalog (secret-free) for the in-canvas \
+ tool browser — the same core as the agent's search_tool_catalog tool.",
+ inputs: vec![
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::String,
+ comment: "Keyword query matched against slug / toolkit / description.",
+ required: true,
+ },
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Restrict to one toolkit slug (e.g. `gmail`); omit to search all.",
+ required: false,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max results (default 25).",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "tools",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Matches: { slug, toolkit, description, required_args, output_fields, primary_array_path, featured }.",
+ required: true,
+ }],
+ }),
+ "get_tool_contract" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "get_tool_contract",
+ description: "Fetch one Composio action's full contract (secret-free) for the canvas \
+ tool browser — the same core as the agent's get_tool_contract tool.",
+ inputs: vec![FieldSchema {
+ name: "slug",
+ ty: TypeSchema::String,
+ comment: "The exact Composio action slug (e.g. `GMAIL_SEND_EMAIL`).",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "contract",
+ ty: TypeSchema::Json,
+ comment: "The action contract: { slug, toolkit, description, required_args, input_schema, output_fields, output_schema, primary_array_path, is_curated }.",
+ required: true,
+ },
+ FieldSchema {
+ name: "runtime_gate",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Present when this real action is outside the toolkit's curated runtime allowlist and will be rejected on every real run.",
+ required: false,
+ },
+ ],
+ }),
+ "discover" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "discover",
+ description: "Run the read-only Flow Scout: it reads the user's \
+ memory/threads/people/connections/existing flows and records a handful \
+ of concrete, buildable workflow suggestions for the Flows page. It never \
+ creates, enables, or runs a flow — turning a suggestion into a real flow \
+ is the user's separate 'Build this' action. Returns the active (new) \
+ suggestions after the run.",
+ inputs: vec![stream_thread_id_input(), stream_request_id_input()],
+ outputs: vec![suggestions_output()],
+ }),
+ "list_suggestions" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "list_suggestions",
+ description: "List persisted workflow suggestions. Filter by lifecycle `status` \
+ (`new` | `dismissed` | `built`); omit to return every status.",
+ inputs: vec![FieldSchema {
+ name: "status",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Lifecycle filter: `new` (active cards) | `dismissed` | `built`. \
+ Omit for all.",
+ required: false,
+ }],
+ outputs: vec![suggestions_output()],
+ }),
+ "dismiss_suggestion" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "dismiss_suggestion",
+ description: "Dismiss a workflow suggestion (the user rejected the card). The row is \
+ kept so a later discovery run dedupes against it and won't re-surface \
+ the idea.",
+ inputs: vec![id_input("Identifier of the suggestion to dismiss.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, dismissed }` — `dismissed` is false if the id was unknown.",
+ required: true,
+ }],
+ }),
+ "mark_suggestion_built" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "mark_suggestion_built",
+ description: "Mark a suggestion as built — called after the user saves a flow authored \
+ from it, so it drops out of the active cards.",
+ inputs: vec![id_input("Identifier of the suggestion that was built.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, built }` — `built` is false if the id was unknown.",
+ required: true,
+ }],
+ }),
+ _ => None,
+ }
+}
diff --git a/crates/openhuman-core/src/flows/schemas/definition_schemas.rs b/crates/openhuman-core/src/flows/schemas/definition_schemas.rs
index e69de29bb2..02baf34745 100644
--- a/crates/openhuman-core/src/flows/schemas/definition_schemas.rs
+++ b/crates/openhuman-core/src/flows/schemas/definition_schemas.rs
@@ -0,0 +1,340 @@
+//! Schemas for the saved-flow definition lifecycle: create, import,
+//! validate, read, update, enable/disable, delete, revision history and the
+//! approval/connection manifests derived from a graph.
+
+use super::{
+ ControllerSchema, FieldSchema, TypeSchema, expected_version_input, flow_connection_fields,
+ flow_output, id_input, require_approval_input, strict_input,
+};
+
+/// Builds the schema for `function` when this group owns it.
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+ "create" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "create",
+ description: "Create a new saved automation workflow from a tinyflows graph.",
+ inputs: vec![
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::String,
+ comment: "Human-readable flow name.",
+ required: true,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "A tinyflows WorkflowGraph (nodes + edges); validated and migrated on save.",
+ required: true,
+ },
+ require_approval_input(),
+ strict_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+ "duplicate" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "duplicate",
+ description: "Duplicate a saved flow: create an independent copy of its graph under a \
+ new id, with the name suffixed \" (copy)\". The copy is created DISABLED \
+ and is NOT schedule/trigger-bound, so it never immediately fires — the \
+ user enables it explicitly once reviewed. Run history does not carry over.",
+ inputs: vec![id_input("Identifier of the flow to duplicate.")],
+ outputs: vec![flow_output()],
+ }),
+ "validate" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "validate",
+ description: "Validate a tinyflows graph without saving it: reports structural \
+ validity plus non-fatal warnings (e.g. a trigger kind that does not \
+ fire automatically yet).",
+ inputs: vec![FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "A tinyflows WorkflowGraph (nodes + edges) to validate and migrate.",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "valid",
+ ty: TypeSchema::Bool,
+ comment: "True when the graph is structurally valid.",
+ required: true,
+ },
+ FieldSchema {
+ name: "errors",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Structural validation errors; empty when `valid`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "warnings",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Non-fatal warnings (e.g. an unfired trigger kind); the graph is \
+ still saveable/enable-able.",
+ required: true,
+ },
+ ],
+ }),
+ "import" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "import",
+ description: "Import a workflow definition WITHOUT saving it: parse a native tinyflows \
+ graph or an n8n workflow export, migrate + validate it, and return the \
+ normalized WorkflowGraph plus non-fatal import warnings. The caller opens \
+ the result on the canvas as a draft and Saves via the normal gate — \
+ import never persists or enables anything.",
+ inputs: vec![
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The workflow JSON to import: a tinyflows WorkflowGraph (native) or \
+ an n8n workflow export.",
+ required: true,
+ },
+ FieldSchema {
+ name: "format",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Enum {
+ variants: vec!["native", "n8n", "auto"],
+ })),
+ comment: "Source format: `native` (tinyflows), `n8n`, or `auto` (default — \
+ detect by shape).",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The normalized, migrated + validated WorkflowGraph, ready to open \
+ as an editable draft.",
+ required: true,
+ },
+ FieldSchema {
+ name: "warnings",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Non-fatal import warnings (unmapped n8n node types, untranslated \
+ expressions, a synthesized/demoted trigger). Empty for a clean \
+ native import.",
+ required: true,
+ },
+ ],
+ }),
+ "get" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "get",
+ description: "Load one saved flow by id.",
+ inputs: vec![id_input("Identifier of the flow to load.")],
+ outputs: vec![flow_output()],
+ }),
+ "list" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "list",
+ description: "List all saved flows.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "flows",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Flow"))),
+ comment: "Flows currently stored in the workspace.",
+ required: true,
+ }],
+ }),
+ "list_connections" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "list_connections",
+ description: "List the connection sources a flow node's `connection_ref` can attach \
+ to: Composio connected accounts (kind `composio`) and stored HTTP \
+ credentials (kind `http`). Returns only non-secret metadata — ids, \
+ display labels, kind, and (for Composio) the connected account's own \
+ `platform_user_id` — never any secret material (OAuth/bearer tokens, \
+ passwords, and API keys stay server-side and are injected only at \
+ execution time).",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "connections",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Object {
+ fields: flow_connection_fields(),
+ })),
+ comment: "Resolvable connections for the flows picker (composio + http), \
+ secret-free.",
+ required: true,
+ }],
+ }),
+ "update" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "update",
+ description: "Update a saved flow's name and/or graph; re-validates before persisting.",
+ inputs: vec![
+ id_input("Identifier of the flow to update."),
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New name, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Replacement WorkflowGraph, if changing it.",
+ required: false,
+ },
+ require_approval_input(),
+ strict_input(),
+ expected_version_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+ "delete" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "delete",
+ description: "Delete a saved flow by id.",
+ inputs: vec![id_input("Identifier of the flow to delete.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Identifier that was requested for removal.",
+ required: true,
+ },
+ FieldSchema {
+ name: "removed",
+ ty: TypeSchema::Bool,
+ comment: "True when the flow was removed.",
+ required: true,
+ },
+ ],
+ },
+ comment: "Removal result payload.",
+ required: true,
+ }],
+ }),
+ "set_enabled" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "set_enabled",
+ description: "Enable or disable a saved flow.",
+ inputs: vec![
+ id_input("Identifier of the flow to toggle."),
+ FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "New enabled state.",
+ required: true,
+ },
+ ],
+ outputs: vec![flow_output()],
+ }),
+ "get_history" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "get_history",
+ description: "List a flow's revision history — prior graph snapshots captured on each \
+ update (capped, newest first). The safety rail behind rollback.",
+ inputs: vec![
+ id_input("Identifier of the flow whose history to list."),
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max revisions to return (defaults to the retention cap).",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "revisions",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Revision snapshots: { id, flow_id, graph, name, require_approval, created_at }.",
+ required: true,
+ }],
+ }),
+ "rollback" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "rollback",
+ description: "Roll a flow back to a prior revision (restores that revision's graph \
+ through the normal update path — itself snapshotted, so rollback is \
+ undoable). Honours optimistic concurrency via expected_version.",
+ inputs: vec![
+ id_input("Identifier of the flow to roll back."),
+ FieldSchema {
+ name: "revision_id",
+ ty: TypeSchema::String,
+ comment: "The revision (from get_history) to restore.",
+ required: true,
+ },
+ expected_version_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+ "required_connections" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "required_connections",
+ description: "Compute which Composio toolkits a candidate graph needs and whether each \
+ is connected — the data behind the canvas/proposal \"Connect <toolkit>\" \
+ CTAs. Native oh: tools and http_request nodes need no connection.",
+ inputs: vec![FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The WorkflowGraph to inspect.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "required_connections",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "One per needed toolkit: { toolkit, status: connected|missing }.",
+ required: true,
+ }],
+ }),
+ "approval_manifest" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "approval_manifest",
+ description: "Compute the approval manifest for a saved flow (by id) or a candidate graph: \
+ every ApprovalGate permission a run will prompt for, joined against the flow's \
+ existing flow_tool_trust grants — the data behind the consolidated save+enable \
+ pre-authorization card. Entries carry kind approvable|blocked|dynamic|agent.",
+ inputs: vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Saved flow id. Provide this or 'graph'.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Candidate WorkflowGraph to inspect (no trust join without an id).",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "entries",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "One per relevant node/tool: {kind: approvable|blocked|dynamic|agent, \
+ node_id, tool_name?, label, class?}.",
+ required: true,
+ },
+ FieldSchema {
+ name: "missing",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Approvable trust keys the flow does not yet hold.",
+ required: true,
+ },
+ FieldSchema {
+ name: "already_trusted",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Approvable trust keys already granted to this flow. Empty when \
+ gate_installed is false — no gate means no grant was ever made.",
+ required: true,
+ },
+ FieldSchema {
+ name: "gate_installed",
+ ty: TypeSchema::Bool,
+ comment: "False when the approval gate is disabled — nothing ever prompts, so \
+ missing is empty by definition.",
+ required: true,
+ },
+ ],
+ }),
+ _ => None,
+ }
+}
diff --git a/crates/openhuman-core/src/flows/schemas/draft_schemas.rs b/crates/openhuman-core/src/flows/schemas/draft_schemas.rs
index e69de29bb2..9bc4e2d78c 100644
--- a/crates/openhuman-core/src/flows/schemas/draft_schemas.rs
+++ b/crates/openhuman-core/src/flows/schemas/draft_schemas.rs
@@ -0,0 +1,119 @@
+//! Schemas for unsaved flow drafts: the copilot's scratch space before a
+//! graph is promoted into a saved flow.
+
+use super::{
+ ControllerSchema, FieldSchema, TypeSchema, draft_output, flow_output, id_input,
+ require_approval_input,
+};
+
+/// Builds the schema for `function` when this group owns it.
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+ "draft_create" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_create",
+ description: "Create a core-managed draft (a durable, non-live working copy of a graph) \
+ shared by the agent tools and the canvas. Never persists a flow.",
+ inputs: vec![
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::String,
+ comment: "Human-readable draft name (carried into the flow on promote).",
+ required: true,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The (possibly incomplete) WorkflowGraph JSON to hold in the draft.",
+ required: true,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "The saved flow this draft edits, if any (promote → update vs create).",
+ required: false,
+ },
+ FieldSchema {
+ name: "origin",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Where the draft came from: `chat` | `canvas` | `import`. Defaults to `canvas`.",
+ required: false,
+ },
+ ],
+ outputs: vec![draft_output()],
+ }),
+ "draft_get" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_get",
+ description: "Fetch a draft by id.",
+ inputs: vec![id_input("Identifier of the draft to fetch.")],
+ outputs: vec![draft_output()],
+ }),
+ "draft_update" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_update",
+ description: "Patch a draft's name/graph/flow_id (any provided field) and bump its \
+ updated_at. Never persists a flow.",
+ inputs: vec![
+ id_input("Identifier of the draft to update."),
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New name, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "New graph JSON, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New linked flow id, if changing it.",
+ required: false,
+ },
+ ],
+ outputs: vec![draft_output()],
+ }),
+ "draft_list" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_list",
+ description: "List all drafts, newest-updated first.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "drafts",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "The drafts (each { id, flow_id?, name, graph, origin, created_at, updated_at }).",
+ required: true,
+ }],
+ }),
+ "draft_delete" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_delete",
+ description: "Delete a draft by id (idempotent).",
+ inputs: vec![id_input("Identifier of the draft to delete.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, deleted }` — `deleted` is false if the id was already absent.",
+ required: true,
+ }],
+ }),
+ "draft_promote" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "draft_promote",
+ description: "Promote a draft into a saved flow through the same create/update gates \
+ (structural validation, forced require_approval floor, born-disabled for \
+ automatic triggers), then delete the draft file. A draft with a flow_id \
+ updates that flow; otherwise it creates a new one.",
+ inputs: vec![
+ id_input("Identifier of the draft to promote."),
+ require_approval_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+ _ => None,
+ }
+}
diff --git a/crates/openhuman-core/src/flows/schemas/run_schemas.rs b/crates/openhuman-core/src/flows/schemas/run_schemas.rs
index e69de29bb2..55005dfd44 100644
--- a/crates/openhuman-core/src/flows/schemas/run_schemas.rs
+++ b/crates/openhuman-core/src/flows/schemas/run_schemas.rs
@@ -0,0 +1,258 @@
+//! Schemas for executing saved flows and inspecting their run history.
+
+use super::{
+ ControllerSchema, FieldSchema, TypeSchema, id_input, run_detached_output_fields,
+ run_output_fields,
+};
+
+/// Builds the schema for `function` when this group owns it.
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+ "run" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "run",
+ description: "Run a saved flow to completion (or until it pauses on a human-approval gate).",
+ inputs: vec![
+ id_input("Identifier of the flow to run."),
+ FieldSchema {
+ name: "input",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Trigger payload seeded into the run; defaults to null.",
+ required: false,
+ },
+ FieldSchema {
+ name: "inputs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Values for the flow's declared workflow inputs, keyed by name \
+ (read the flow's `graph.inputs` for the declarations). Missing \
+ required values, wrong types, and undeclared names are rejected \
+ before the run starts. Distinct from `input`, which is the \
+ free-form trigger payload.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_output_fields(),
+ },
+ comment: "Run outcome payload.",
+ required: true,
+ }],
+ }),
+ "run_detached" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "run_detached",
+ description: "Start a saved flow WITHOUT waiting for it to finish: validates + \
+ compile-checks the flow, registers the run, inserts its `running` row, \
+ and returns the run id immediately. Use this from any UI that wants to \
+ show live per-node progress (`flow:run_progress`) or that must not block \
+ on a run that can take minutes — poll `flows_get_run(run_id)` or the \
+ progress event stream for completion. `run` remains available for callers \
+ that genuinely want to await the final result.",
+ inputs: vec![
+ id_input("Identifier of the flow to run."),
+ FieldSchema {
+ name: "input",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Trigger payload seeded into the run; defaults to null.",
+ required: false,
+ },
+ FieldSchema {
+ name: "inputs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Values for the flow's declared workflow inputs, keyed by name \
+ (read the flow's `graph.inputs` for the declarations). Validated \
+ synchronously, so a bad set is refused here rather than surfacing \
+ later as a failed background run. Distinct from `input`, which is \
+ the free-form trigger payload.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_detached_output_fields(),
+ },
+ comment: "Immediate start-of-run payload — returned as soon as the run is \
+ registered, without waiting for it to finish.",
+ required: true,
+ }],
+ }),
+ "resume" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "resume",
+ description: "Resume a flow run paused at a human-in-the-loop approval gate, \
+ continuing from its durable checkpoint.",
+ inputs: vec![
+ id_input("Identifier of the flow to resume."),
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::String,
+ comment: "The checkpoint thread id returned by `flows_run` / a prior `flows_resume`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "approvals",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Node ids being approved; defaults to an empty list.",
+ required: false,
+ },
+ FieldSchema {
+ name: "rejections",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Node ids being denied; each routes to its `error` port (or fails \
+ the run if it has none). Defaults to an empty list.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_output_fields(),
+ },
+ comment: "Resume outcome payload (same shape as `run`'s).",
+ required: true,
+ }],
+ }),
+ "cancel_run" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "cancel_run",
+ description: "Cancel a flow run: settle it to a terminal `cancelled` status, abort \
+ the in-flight run task if one is executing, and drop its durable \
+ checkpoint so it can't be resumed.",
+ inputs: vec![FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run to cancel (== its checkpoint thread id).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run that was cancelled.",
+ required: true,
+ },
+ FieldSchema {
+ name: "cancelled",
+ ty: TypeSchema::Bool,
+ comment: "True once the run is cancelled or its cancellation requested.",
+ required: true,
+ },
+ FieldSchema {
+ name: "was_in_flight",
+ ty: TypeSchema::Bool,
+ comment: "True when a live run task was signalled to abort; false when \
+ a parked/stale run row was settled directly.",
+ required: true,
+ },
+ ],
+ },
+ comment: "Cancellation result payload.",
+ required: true,
+ }],
+ }),
+ "list_runs" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "list_runs",
+ description: "List the most recent runs for a flow, newest first.",
+ inputs: vec![
+ id_input("Identifier of the flow whose runs to list."),
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum number of runs to return; defaults to 20.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "runs",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
+ comment: "Persisted run records for this flow, newest first.",
+ required: true,
+ }],
+ }),
+ "list_all_runs" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "list_all_runs",
+ description: "List the most recent runs across all flows, newest first.",
+ inputs: vec![FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum number of runs to return; defaults to 100.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "runs",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
+ comment: "Persisted run records across all flows, newest first.",
+ required: true,
+ }],
+ }),
+ "get_run" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "get_run",
+ description: "Load one persisted flow run record by its (checkpoint thread) id.",
+ inputs: vec![FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run to load (== its checkpoint thread id).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "run",
+ ty: TypeSchema::Ref("FlowRun"),
+ comment: "The persisted run record.",
+ required: true,
+ }],
+ }),
+ "prune_runs" => Some(ControllerSchema {
+ namespace: "flows",
+ function: "prune_runs",
+ description: "Manually prune a flow's run history down to the retention cap, deleting \
+ only terminal runs (completed/failed/cancelled) outside the newest-N \
+ window. Never removes a running or pending_approval run. Pruning also \
+ happens automatically on every new run; this is an explicit on-demand \
+ sweep.",
+ inputs: vec![id_input(
+ "Identifier of the flow whose run history to prune.",
+ )],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the flow whose runs were pruned.",
+ required: true,
+ },
+ FieldSchema {
+ name: "pruned",
+ ty: TypeSchema::U64,
+ comment: "Number of run records removed.",
+ required: true,
+ },
+ FieldSchema {
+ name: "kept",
+ ty: TypeSchema::U64,
+ comment: "The retention cap (most-recent runs kept).",
+ required: true,
+ },
+ ],
+ },
+ comment: "Prune result payload.",
+ required: true,
+ }],
+ }),
+ _ => None,
+ }
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
index e69de29bb2..766c097772 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
@@ -0,0 +1,510 @@
+//! The `AgentRunner` capability — running an `agent` node through the harness.
+//!
+//! Resolves `agent_ref` to a route, decides the model and the run timeout, and
+//! builds the prompt the harness receives. The timeout logic is the subtle part:
+//! a per-attempt bound has to be scaled against the iteration cap, or a run that
+//! is progressing normally gets killed for being long rather than for being
+//! stuck.
+
+#![allow(unused_imports)]
+
+use std::borrow::Cow;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::Config;
+use crate::flows::agent_route::{
+ AgentRoute, harness_model_default_override, route_custom_entry_lookup, route_for_agent_ref,
+};
+
+/// [`AgentRunner`] backing an `agent` node's `agent_ref`. It runs the selected
+/// agent kind by one of two paths, chosen by [`route_for_agent_ref`]:
+///
+/// 1. **Full harness turn** (the common case, Phase A). When `agent_ref` names a
+/// harness [`AgentDefinition`](crate::agent::harness::host_definition::AgentDefinition),
+/// the node builds a real session agent
+/// ([`OpenHumanSessionHost::from_config_for_agent`](crate::agent::OpenHumanSessionHost::from_config_for_agent)
+/// + `set_agent_definition_name`) and drives one full turn via
+///
+/// [`OpenHumanSessionHost::run_single`](crate::agent::OpenHumanSessionHost::run_single) — the
+/// complete tool loop. The definition's `ToolScope` / `sandbox_mode` /
+/// `max_iterations` govern the turn, so an agent node gains its curated
+/// toolset with no graph change. This is the same harness pattern
+/// `flows_build` / `flows_discover` / cron use, so "every node
+/// is a tinyagents graph" still holds: `run_single` itself routes through the
+/// default agent graph, i.e. a nested tinyagents graph (the agent turn) inside
+/// the flow's tinyagents graph.
+/// 2. **Persona-shaping completion fallback** (no regression for custom agents).
+/// When `agent_ref` only resolves to a custom
+/// [`AgentRegistryEntry`](crate::agent::registry::AgentRegistryEntry)
+/// (no harness definition), the node keeps the original single-completion
+/// behavior: the entry's `system_prompt` / `model` are shaped on top of the
+/// node request and run through [`OpenHumanLlm::complete`].
+///
+/// **Security.** No new origin is scoped here: the engine future already runs
+/// under the flow's `Workflow` origin (`turn_origin`), so the user's autonomy
+/// tier + approval gate apply to the inner turn automatically, and the agent
+/// definition's `ToolScope`/sandbox is the inner gate. `agent_ref` is resolved
+/// from trusted node config (never model output), so a prompt-injected
+/// completion cannot pick an arbitrary agent kind.
+///
+/// **Per-item cost.** In per-item execution mode the engine calls
+/// [`run_agent`](AgentRunner::run_agent) once per input item, so a full harness
+/// turn (with memory injection) fans out one `Agent` per item. Since the engine
+/// gained bounded per-item concurrency those calls also arrive *simultaneously*,
+/// so the host-side guard this doc used to defer is now
+/// [`HARNESS_AGENT_SLOTS`] — see it for why the engine's own `concurrency`
+/// bound is not enough. Memory injection per node turn is accepted for this
+/// first cut (skip-memory is a follow-up).
+///
+/// **Concurrency safety.** `run_agent` is re-entrant by construction: it builds
+/// a fresh [`Agent`](crate::agent::OpenHumanSessionHost) per call and stamps any
+/// model override onto a *cloned* `Config`, so concurrent calls never mutate
+/// shared state. The origin escalation and approval-run context are task-locals
+/// propagated by the engine's `buffer_unordered` (which polls every item on the
+/// caller's task), so HITL gating still applies to every fanned-out turn.
+pub struct OpenHumanAgentRunner {
+ pub config: Arc<Config>,
+ /// The context the run acts under, handed over by whoever started it.
+ pub ctx: crate::core::runtime::DispatchCtx,
+ /// The run's approval context (flow run correlation), handed to the gate
+ /// with every acting dispatch.
+ pub approval: crate::security::approval::ApprovalTurnContext,
+}
+
+/// Process-wide ceiling on **simultaneous harness agent turns started by flow
+/// nodes**, honoured by [`run_via_harness`](OpenHumanAgentRunner::run_via_harness).
+///
+/// The engine's per-node `concurrency` bounds one node's fan-out; this bounds
+/// the host. Those are different limits and the host one is the load-bearing
+/// one: a graph can fan out `concurrency: "all"` over a 200-item array, and
+/// several nodes (or several concurrent runs) can be fanning out at once, so
+/// without a shared ceiling a single workflow could open hundreds of full agent
+/// sessions — each with its own model context and tool loop — and exhaust
+/// memory or the inference provider's rate limit.
+///
+/// Default 8; override with `OPENHUMAN_FLOWS_MAX_PARALLEL_AGENTS`. Waiting on a
+/// permit is *not* an error — an over-wide fan-out is throttled to this width
+/// rather than rejected, so the workflow still completes, just more slowly.
+static HARNESS_AGENT_SLOTS: std::sync::LazyLock<tokio::sync::Semaphore> =
+ std::sync::LazyLock::new(|| {
+ let permits = max_parallel_harness_agents(
+ std::env::var("OPENHUMAN_FLOWS_MAX_PARALLEL_AGENTS")
+ .ok()
+ .as_deref(),
+ );
+ tracing::debug!(
+ target: "flows",
+ permits,
+ "[flows] agent_runner: harness concurrency ceiling"
+ );
+ tokio::sync::Semaphore::new(permits)
+ });
+
+/// Default value for [`HARNESS_AGENT_SLOTS`].
+const DEFAULT_MAX_PARALLEL_HARNESS_AGENTS: usize = 8;
+
+/// Resolves the harness concurrency ceiling from the raw env-var value.
+///
+/// A malformed or zero override falls back to the default rather than erroring
+/// or, worse, yielding a zero-permit semaphore that would deadlock every flow
+/// agent node in the process.
+fn max_parallel_harness_agents(raw: Option<&str>) -> usize {
+ raw.and_then(|v| v.trim().parse::<usize>().ok())
+ .filter(|n| *n > 0)
+ .unwrap_or(DEFAULT_MAX_PARALLEL_HARNESS_AGENTS)
+}
+
+#[async_trait]
+impl AgentRunner for OpenHumanAgentRunner {
+ async fn run_agent(
+ &self,
+ agent_ref: &str,
+ request: Value,
+ conn: Option<&str>,
+ ) -> Result<Value> {
+ // Entry point of a flow agent node: the run's own context.
+ let dispatch = self.ctx.clone();
+ // The harness definition registry must be initialised before we can
+ // build a named agent. Idempotent: a booted core already did this at
+ // startup; a bare flow run (tests, standalone) has not. A failure here
+ // is non-fatal — we log and fall through to the registry-entry route.
+ if let Err(e) = crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global(
+ &self.config.workspace_dir,
+ ) {
+ tracing::warn!(
+ target: "flows",
+ agent_ref,
+ error = %e,
+ "[flows] agent_runner: agent definition registry init failed — will attempt the \
+ custom registry-entry fallback"
+ );
+ }
+
+ match route_for_agent_ref(agent_ref) {
+ AgentRoute::HostAgent => {
+ // Resolved again rather than carried by the route so the route
+ // stays a plain value; a host that dropped the agent in between
+ // degrades to the registry build below.
+ let host = crate::agent::host_agents::resolve(agent_ref);
+ tracing::info!(
+ target: "flows",
+ agent_ref,
+ "[flows] agent_runner: HOST AGENT path — running the host-registered agent \
+ with its own tools in its own context"
+ );
+ self.run_via_harness(&dispatch, agent_ref, request, conn, None, host)
+ .await
+ }
+ AgentRoute::Harness => {
+ tracing::info!(
+ target: "flows",
+ agent_ref,
+ "[flows] agent_runner: HARNESS path — running the full agent tool loop"
+ );
+ // A shipped/TOML harness definition has no `entry.model` — the
+ // definition's own `ModelSpec` (already applied by the session
+ // builder) is the only model pin in play here.
+ self.run_via_harness(&dispatch, agent_ref, request, conn, None, None)
+ .await
+ }
+ AgentRoute::RegistryFallback => {
+ // `route_for_agent_ref` only consults the harness
+ // `AgentDefinitionRegistry`, so a miss there used to mean
+ // "run the persona-only completion fallback" unconditionally
+ // — even for a user-created custom agent, which has real
+ // `tool_allowlist`/`model` settings that fallback ignores.
+ //
+ // The agent factory (`OpenHumanSessionHost::from_config_for_agent`) now
+ // also consults `config.agent_registry.entries` on a
+ // harness-registry miss and synthesizes a real
+ // `AgentDefinition` for any `AgentRegistrySource::Custom`
+ // entry it finds (issue B38/Gap 2). So: route a *known,
+ // enabled* custom entry through the harness turn — it gets
+ // its real tool belt — and reserve the persona-only
+ // completion for `agent_ref`s that are unknown to both the
+ // harness registry AND the custom config registry (or that
+ // are disabled, which `run_via_registry_fallback` already
+ // rejects with a clear error).
+ let custom_entry =
+ crate::agent::registry::find_custom_in_config(&self.config, agent_ref);
+ let entry_model = custom_entry.as_ref().and_then(|e| e.model.clone());
+ match route_custom_entry_lookup(custom_entry.as_ref()) {
+ AgentRoute::Harness | AgentRoute::HostAgent => {
+ tracing::info!(
+ target: "flows",
+ agent_ref,
+ "[flows] agent_runner: CUSTOM-REGISTRY path — routing through the \
+ harness so the custom agent runs with its real tool belt instead of \
+ the persona-only completion fallback"
+ );
+ // Preserve the custom entry's own `model` pin (e.g.
+ // `hint:reasoning` or a raw BYOK model id) as the
+ // fallback below the node's own override — same
+ // precedence `run_via_registry_fallback` already gave
+ // it, now honored on the harness path too (P2 review
+ // comment on this PR: this previously regressed to the
+ // default chat model for a custom flow agent with no
+ // per-node override).
+ self.run_via_harness(
+ &dispatch,
+ agent_ref,
+ request,
+ conn,
+ entry_model.as_deref(),
+ None,
+ )
+ .await
+ }
+ AgentRoute::RegistryFallback => {
+ tracing::info!(
+ target: "flows",
+ agent_ref,
+ "[flows] agent_runner: FALLBACK path — persona-shaping single \
+ completion for a custom registry entry"
+ );
+ self.run_via_registry_fallback(&dispatch, agent_ref, request, conn)
+ .await
+ }
+ }
+ }
+ }
+ }
+}
+
+impl OpenHumanAgentRunner {
+ /// Full harness turn: build a real session agent for `agent_ref` and drive
+ /// one `run_single` under the node's model override + timeout. See
+ /// [`OpenHumanAgentRunner`] for the security/origin contract.
+ ///
+ /// `entry_model` is the custom `AgentRegistryEntry`'s own `model` pin (a
+ /// `hint:<role>` or raw BYOK model id), when `agent_ref` resolved to one —
+ /// `None` for a shipped/TOML harness definition, which has no such entry.
+ /// It is the fallback below the node's own `config.model` override (see
+ /// `resolve_node_model`), matching the precedence
+ /// `run_via_registry_fallback` already gave `entry.model` — without this,
+ /// a custom flow agent's model pin (e.g. `hint:reasoning`) silently
+ /// dropped to the default chat model once routed through the harness.
+ ///
+ /// **Synchronous only (B40 / Gap 4).** A flow `agent` node runs here with
+ /// no explicit chat thread on its run context. If the
+ /// agent it runs is a delegating agent (e.g. the orchestrator) and
+ /// calls `spawn_async_subagent` directly, the tool now refuses (see the
+ /// `parent_thread_id.is_none()` guard in
+ /// `agent_orchestration::tools::spawn_async_subagent`) rather than
+ /// silently discarding the background result once it finishes —
+ /// `background_delivery` has nowhere to deliver it without a thread id.
+ /// This module does not bridge async subagent delivery into flow runs.
+ /// For work that needs to happen in parallel, model it as parallel flow
+ /// nodes (the tinyflows engine already fans those out) instead of
+ /// reaching for a background sub-agent from inside a single node.
+ async fn run_via_harness(
+ &self,
+ dispatch: &crate::core::runtime::DispatchCtx,
+ agent_ref: &str,
+ request: Value,
+ conn: Option<&str>,
+ entry_model: Option<&str>,
+ host: Option<crate::agent::host_agents::HostAgent>,
+ ) -> Result<Value> {
+ use crate::agent::OpenHumanSessionHost;
+
+ // Hold a slot for the whole turn: a fanned-out node can call this
+ // hundreds of times at once, and each call below builds a full agent
+ // session. Acquired before any work so waiters queue rather than pile
+ // up half-built agents. `_permit` is released on drop at end of scope,
+ // including on every early return below.
+ let _permit = HARNESS_AGENT_SLOTS.acquire().await.map_err(|_| {
+ EngineError::Capability(
+ "agent node: harness concurrency limiter closed unexpectedly".to_string(),
+ )
+ })?;
+
+ if let Some(c) = conn {
+ tracing::debug!(
+ target: "flows",
+ conn = %c,
+ "[flows] agent_runner: connection_ref present but not resolved to a BYOK account \
+ for the harness turn (matches OpenHumanLlm)"
+ );
+ }
+
+ // Model precedence for a harness node: node `config.model` > the
+ // custom registry entry's own `model` pin (if any) > the definition's
+ // own default.
+ let node_model = resolve_node_model(&request, entry_model);
+
+ // Apply the override the cron way (`run_agent_job`): a cloned `Config`
+ // with a new `default_model`, so we never mutate the shared config or
+ // invent a new Agent setter API. The tier is normalised to the
+ // `hint:<role>` form the session builder routes on.
+ // A host-registered agent starts from its own config (its provider
+ // model and route), not the flow runner's.
+ let base: &Config = host
+ .as_ref()
+ .map_or(self.config.as_ref(), |host| &host.config);
+ let effective: Cow<'_, Config> = match node_model.as_deref() {
+ Some(model) => {
+ let mut config = base.clone();
+ config.default_model = Some(harness_model_default_override(model));
+ Cow::Owned(config)
+ }
+ None => Cow::Borrowed(base),
+ };
+
+ let built = match &host {
+ Some(host) => host.session_host(effective.as_ref(), None),
+ None => {
+ OpenHumanSessionHost::from_config_for_agent(dispatch, effective.as_ref(), agent_ref)
+ }
+ };
+ let mut agent = built.map_err(|e| {
+ EngineError::Capability(format!(
+ "agent node: failed to build harness agent '{agent_ref}': {e:#}"
+ ))
+ })?;
+ agent.set_agent_definition_name(agent_ref.to_string());
+
+ let prompt = build_harness_run_prompt(&request);
+
+ let requested_timeout_secs = request.get("timeout_secs").and_then(Value::as_u64);
+ let base_timeout_secs = clamp_run_timeout_secs(requested_timeout_secs);
+
+ // Issue #4868 — the session builder now stamps `agent_ref`'s own
+ // `effective_max_iterations()` onto the agent (instead of the global
+ // default of 10), so `code_executor`/`tools_agent`/etc. can run up to
+ // 50 iterations here. Read the cap actually applied to `agent`
+ // (reflects the definition cap or the global fallback, whichever the
+ // builder resolved) and scale the DEFAULT timeout accordingly — see
+ // `scale_timeout_for_iteration_cap`.
+ //
+ // Post-merge Codex P2 finding: an EXPLICIT `timeout_secs` the node
+ // config supplied is a caller-chosen bound (e.g. a fast-fail/SLA of
+ // 120s) and must be honored as-is, never scaled up just because the
+ // agent's iteration cap is high — see `resolve_run_timeout_secs`.
+ let effective_iteration_cap = agent.agent_config().max_tool_iterations;
+ let timeout_secs =
+ resolve_run_timeout_secs(requested_timeout_secs, effective_iteration_cap);
+
+ tracing::debug!(
+ target: "flows",
+ agent_ref,
+ node_model = node_model.as_deref().unwrap_or("<definition-default>"),
+ default_model = effective.default_model.as_deref().unwrap_or("<config-default>"),
+ effective_iteration_cap,
+ explicit_timeout_secs = requested_timeout_secs.is_some(),
+ base_timeout_secs,
+ timeout_secs,
+ prompt_len = prompt.len(),
+ "[flows] agent_runner: dispatching full harness turn"
+ );
+
+ // Nested-harness HITL escalation (issue #4595): the engine future runs
+ // under the flow's Workflow origin, but the flow author only pre-
+ // declared `agent_ref` — not the concrete tools the harness LLM will
+ // pick from the definition's `ToolScope`. If we let the inner turn
+ // inherit a `Workflow { require_approval: false }` origin,
+ // `ApprovalGate::intercept_audited` treats it as a trust root and
+ // auto-`Allow`s external_effect tools (see
+ // `crates/openhuman-core/src/security/approval/gate.rs` `Workflow { require_approval: false }`
+ // branch), which would let a scheduled / app-event flow reach out to
+ // Slack / email / desktop control with no HITL. We force
+ // `require_approval: true` around `run_single` so external_effect tools
+ // park for a real decision the same way flow acting nodes escalated by
+ // [`gate_call_for_tier`] do. Read-only tools (no `external_effect`)
+ // aren't gated by `intercept_audited` at all, so this doesn't add noise
+ // for pure-read nested agents.
+ //
+ // Cancellation: the run_registry token aborts the engine future, and the
+ // inner turn drops with it (task-local scope unwinds cleanly).
+ use crate::agent::turn_origin;
+ let escalated_origin = escalated_origin_for_nested_harness(self.ctx.turn_origin());
+ if let Some(ref escalated) = escalated_origin {
+ tracing::debug!(
+ target: "flows",
+ agent_ref,
+ origin = ?escalated,
+ "[flows] agent_runner: escalating nested harness turn to Workflow{{require_approval:true}} \
+ so external_effect tools park for HITL (issue #4595)"
+ );
+ }
+ let run: std::pin::Pin<
+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>,
+ > = if let Some(escalated) = escalated_origin {
+ Box::pin(turn_origin::with_origin(
+ escalated,
+ agent.run_single_with_approval(&prompt, None, self.approval.clone()),
+ ))
+ } else {
+ Box::pin(agent.run_single_with_approval(&prompt, None, self.approval.clone()))
+ };
+ // A host agent's turn reads its own context (config, domains, tool
+ // groups, session store); the origin task-local is untouched.
+ let run: std::pin::Pin<
+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>,
+ > = match host
+ .as_ref()
+ .map(|host| std::sync::Arc::clone(&host.context))
+ {
+ Some(context) => Box::pin(crate::core::runtime::CoreContext::scope(context, run)),
+ None => run,
+ };
+ let final_text =
+ match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run).await {
+ Ok(Ok(text)) => text,
+ Ok(Err(e)) => {
+ tracing::warn!(
+ target: "flows",
+ agent_ref,
+ error = %e,
+ "[flows] agent_runner: harness turn failed"
+ );
+ return Err(EngineError::Capability(format!(
+ "agent node '{agent_ref}' turn failed: {e:#}"
+ )));
+ }
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ agent_ref,
+ timeout_secs,
+ "[flows] agent_runner: harness turn timed out"
+ );
+ return Err(EngineError::Capability(format!(
+ "agent node '{agent_ref}' timed out after {timeout_secs}s"
+ )));
+ }
+ };
+
+ Ok(build_agent_result(agent_ref, &final_text, &request))
+ }
+
+ /// Persona-shaping single-completion fallback for a custom
+ /// [`AgentRegistryEntry`](crate::agent::registry::AgentRegistryEntry)
+ /// with no harness definition — the pre-Phase-A behavior, kept so custom
+ /// agents don't regress.
+ async fn run_via_registry_fallback(
+ &self,
+ dispatch: &crate::core::runtime::DispatchCtx,
+ agent_ref: &str,
+ request: Value,
+ conn: Option<&str>,
+ ) -> Result<Value> {
+ // Resolve + validate the requested agent kind against the registry.
+ let entry = crate::agent::registry::get_agent(dispatch, agent_ref)
+ .await
+ .map_err(EngineError::Capability)?
+ .ok_or_else(|| {
+ EngineError::Capability(format!(
+ "agent node: unknown agent_ref '{agent_ref}' (neither a harness definition nor \
+ a custom agent registry entry)"
+ ))
+ })?;
+ if !entry.enabled {
+ return Err(EngineError::Capability(format!(
+ "agent node: agent_ref '{agent_ref}' is disabled"
+ )));
+ }
+
+ tracing::debug!(
+ target: "flows",
+ agent_ref,
+ has_system_prompt = entry.system_prompt.is_some(),
+ model = entry.model.as_deref().unwrap_or("<role-default>"),
+ "[flows] agent_runner: applying custom registered agent-kind persona to the completion"
+ );
+
+ // Shape the completion by the agent kind: prepend the agent's system
+ // prompt (its persona) ahead of the node's messages, and adopt its model
+ // when the node didn't pin one. The completion itself runs through the
+ // same provider path as a plain agent turn (OpenHumanLlm::complete), so
+ // structured-output / envelope behavior is identical.
+ let mut request = request;
+ if let Some(system_prompt) = entry.system_prompt.as_deref().filter(|s| !s.is_empty()) {
+ prepend_system_message(&mut request, system_prompt);
+ }
+ if let Some(model) = entry.model.as_deref().filter(|s| !s.is_empty()) {
+ if request.get("model").and_then(Value::as_str).is_none() {
+ if let Value::Object(map) = &mut request {
+ map.insert("model".to_string(), Value::String(model.to_string()));
+ }
+ }
+ }
+
+ OpenHumanLlm {
+ ctx: self.ctx.clone(),
+ config: self.config.clone(),
+ }
+ .complete(request, conn)
+ .await
+ }
+}
+
+#[cfg(test)]
+#[path = "agent_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs
index e69de29bb2..3beaf27008 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs
@@ -0,0 +1,258 @@
+//! The `CodeRunner` capability for `code` nodes.
+//!
+//! Runs JavaScript or Python inside the sandbox, under a wall-clock timeout, so
+//! a runaway or hostile snippet cannot hold a flow run open indefinitely.
+
+#![allow(unused_imports)]
+
+use crate::core::runtime::DispatchCtx;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::Config;
+use crate::sandbox::{execute_in_sandbox, resolve_sandbox_policy};
+use crate::security::SecurityPolicy;
+use tinyagents_definition::SandboxMode;
+use tinybox_bus::CommandClass;
+
+/// [`CodeRunner`] adapter running sandboxed user code via
+/// `crates/openhuman-core/src/sandbox/ops.rs` (`resolve_sandbox_policy` +
+/// `execute_in_sandbox`), modeled on
+/// the shell tool sandbox runner.
+///
+/// **Mismatch handled here:** the sandbox runs a shell command string, not a
+/// `(language, source, input)` triple. `source` is treated as a function body
+/// receiving the serialized `input` items array and returning the node's
+/// output — this convention is a B1 design choice (not specified by the
+/// crate), matching the mock's "function body" tests
+/// (`tinyflows::nodes::integration::code` — e.g. `"source": "return 1;"`).
+///
+/// Requires `node`/`python3` on the `PATH` the sandbox backend runs under;
+/// there is no managed toolchain wiring here (the same as shell
+/// `NodeBootstrap`).
+///
+/// **Phase 2 — autonomy-tier gating:** a `code` node runs arbitrary user code
+/// in a sandbox, so it is treated as [`CommandClass::Write`] (state-changing but
+/// sandbox-bounded — not inherently catastrophic). Before dispatch it consults
+/// [`enforce_node_tier_gate`]: a read-only run `Block`s and never executes; a
+/// Supervised run then routes through the `ApprovalGate` (Write ⇒ `Prompt`); a
+/// Full run executes silently. This closes the prior gap where the code node had
+/// no policy check and no approval gate at all.
+pub struct OpenHumanCode {
+ pub config: Arc<Config>,
+ /// The context the run acts under, handed over by whoever started it.
+ pub ctx: DispatchCtx,
+ pub security: Arc<SecurityPolicy>,
+ /// The run's approval context (flow run correlation), handed to the gate
+ /// with every acting dispatch.
+ pub approval: crate::security::approval::ApprovalTurnContext,
+}
+
+pub(crate) const CODE_RUN_TIMEOUT_SECS: u64 = 60;
+
+#[async_trait]
+impl CodeRunner for OpenHumanCode {
+ async fn run(&self, language: CodeLanguage, source: &str, input: Value) -> Result<Value> {
+ // Autonomy-tier gate (Phase 2): sandboxed arbitrary-code execution is
+ // Write-class. A read-only run `Block`s here and never spawns anything;
+ // Supervised/Full fall through to the ApprovalGate below.
+ let tier_decision = enforce_current_node_tier_gate(
+ &self.ctx,
+ &self.config,
+ &self.security,
+ CommandClass::Write,
+ "code",
+ )
+ .await?;
+
+ // Approval gate (mirrors OpenHumanTools/OpenHumanHttp): `gate_call_for_tier`
+ // is what turns a Supervised-tier `Prompt` decision into a real human
+ // round-trip before any code runs — escalating past the flow's own
+ // `require_approval` toggle when the tier itself says "ask me" (Codex P1).
+ // A Deny short-circuits. The audit summary is computed on a redacted view
+ // of the request, never the raw source secrets, matching the other
+ // acting adapters.
+ let action = json!({ "language": format!("{language:?}"), "source": source });
+ let summary = crate::security::approval::summarize_action("flows_code", &action);
+ let redacted = crate::security::approval::redact_args(&action);
+ let (gate_outcome, audit_id) = gate_call_for_tier(
+ &self.ctx,
+ &self.approval,
+ tier_decision,
+ "flows_code",
+ &summary,
+ redacted,
+ )
+ .await;
+ if let crate::security::approval::GateOutcome::Deny { reason } = gate_outcome {
+ return Err(EngineError::Capability(reason));
+ }
+
+ let dispatch = self.ctx.clone();
+ let outcome: Result<Value> = async {
+ let policy = resolve_sandbox_policy(
+ &dispatch,
+ SandboxMode::Sandboxed,
+ &self.config.action_dir,
+ &self.config.workspace_dir,
+ &self.config.runtime,
+ false,
+ );
+
+ // Work dir lives under `action_dir` (the sandbox workspace root). We keep
+ // its path *relative* to `action_dir` so the run command works on every
+ // backend: for Local, `execute_in_sandbox`'s `working_dir` is the host
+ // cwd; for Docker, `action_dir` is bind-mounted at `/workspace` with
+ // `-w /workspace`. Host-absolute paths would not exist inside the
+ // container, so we pass `action_dir` as the working dir and reference the
+ // script/input by their `action_dir`-relative paths.
+ let rel_dir = std::path::Path::new(".flows_code").join(uuid::Uuid::new_v4().to_string());
+ let work_dir = self.config.action_dir.join(&rel_dir);
+ tokio::fs::create_dir_all(&work_dir)
+ .await
+ .map_err(|e| EngineError::Capability(format!("failed to create code work dir: {e}")))?;
+
+ // Keep every fallible staging and dispatch step inside one result so
+ // the cleanup below runs for serialization/write failures as well as
+ // sandbox failures.
+ let exec_result = async {
+ let (script_name, interpreter, script_body) = match language {
+ CodeLanguage::JavaScript => ("script.js", "node", js_harness(source)),
+ CodeLanguage::Python => ("script.py", "python3", python_harness(source)),
+ };
+ let script_path = work_dir.join(script_name);
+ let input_path = work_dir.join("input.json");
+
+ let input_json = serde_json::to_string(&input).map_err(|e| {
+ EngineError::Capability(format!("failed to serialize code input: {e}"))
+ })?;
+ tokio::fs::write(&script_path, script_body)
+ .await
+ .map_err(|e| EngineError::Capability(format!("failed to write code script: {e}")))?;
+ tokio::fs::write(&input_path, input_json)
+ .await
+ .map_err(|e| EngineError::Capability(format!("failed to write code input: {e}")))?;
+
+ // Backend-agnostic, `action_dir`-relative command paths (see above).
+ let rel_script = rel_dir.join(script_name);
+ let rel_input = rel_dir.join("input.json");
+ let command = format!(
+ "{} {} {}",
+ shell_quote(interpreter),
+ shell_quote(&rel_script.to_string_lossy()),
+ shell_quote(&rel_input.to_string_lossy()),
+ );
+
+ let mut extra_env = std::collections::HashMap::new();
+ if let Ok(host_path) = std::env::var("PATH") {
+ extra_env.insert("PATH".into(), host_path.into());
+ }
+
+ tracing::debug!(
+ target: "flows",
+ ?language,
+ work_dir = %work_dir.display(),
+ "[flows] code: running sandboxed script"
+ );
+
+ execute_in_sandbox(
+ &dispatch,
+ &policy,
+ &command,
+ &self.config.action_dir,
+ extra_env,
+ std::time::Duration::from_secs(CODE_RUN_TIMEOUT_SECS),
+ )
+ .await
+ .map_err(|e| EngineError::Capability(format!("sandbox execution failed: {e}")))
+ }
+ .await;
+
+ // Always clean up the work dir — even when `execute_in_sandbox` itself
+ // errors (e.g. a spawn failure) — so temp scripts never leak.
+ if let Err(e) = tokio::fs::remove_dir_all(&work_dir).await {
+ tracing::debug!(target: "flows", error = %e, "[flows] code: failed to clean up work dir (non-fatal)");
+ }
+
+ let result = exec_result?;
+
+ if !result.success() {
+ return Err(EngineError::Capability(format!(
+ "code node exited non-zero (timed_out={}): {}",
+ result.timed_out, result.stderr
+ )));
+ }
+
+ serde_json::from_str(result.stdout.trim())
+ .map_err(|e| EngineError::Capability(format!("code output was not valid JSON: {e}")))
+ }
+ .await;
+
+ // Close out the approval audit with the run's success/failure (mirrors
+ // OpenHumanTools/OpenHumanHttp).
+ if let Some(id) = audit_id {
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ let exec = if outcome.is_ok() {
+ crate::security::approval::ExecutionOutcome::Success
+ } else {
+ crate::security::approval::ExecutionOutcome::Failure
+ };
+ gate.record_execution(
+ &id,
+ exec,
+ outcome.as_ref().err().map(ToString::to_string).as_deref(),
+ );
+ }
+ }
+
+ outcome
+ }
+}
+
+/// Wraps user `source` as a function body receiving `input`, executed by Node,
+/// printing the JSON result (or `null`) to stdout.
+pub(crate) fn js_harness(source: &str) -> String {
+ format!(
+ "const fs = require('fs');\n\
+ const input = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));\n\
+ const __result__ = (function(input) {{\n{source}\n}})(input);\n\
+ process.stdout.write(JSON.stringify(__result__ === undefined ? null : __result__));\n"
+ )
+}
+
+/// Wraps user `source` as a function body receiving `input`, executed by
+/// Python, printing the JSON result (or `null`) to stdout.
+pub(crate) fn python_harness(source: &str) -> String {
+ let indented: String = if source.trim().is_empty() {
+ " pass".to_string()
+ } else {
+ source
+ .lines()
+ .map(|line| format!(" {line}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ format!(
+ "import sys, json\n\
+ with open(sys.argv[1]) as __f__:\n input = json.load(__f__)\n\
+ def __user_fn__(input):\n{indented}\n return None\n\
+ __result__ = __user_fn__(input)\n\
+ print(json.dumps(__result__))\n"
+ )
+}
+
+/// POSIX single-quote shell escaping, mirroring
+/// the shell quoting helper.
+pub(crate) fn shell_quote(s: &str) -> String {
+ let escaped = s.replace('\'', "'\\''");
+ format!("'{escaped}'")
+}
+
+#[cfg(test)]
+#[path = "code_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/http.rs b/crates/openhuman-core/src/flows/tinyflows/caps/http.rs
index e69de29bb2..ecf919b9b2 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/http.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/http.rs
@@ -0,0 +1,266 @@
+//! The `HttpClient` capability for `http_request` nodes.
+//!
+//! Allowlist and DNS-rebind protection come from the underlying
+//! `HttpRequestTool`, so this adapter inherits them. What it adds is credential
+//! resolution: a `http_cred:<name>` connection_ref is resolved against the
+//! encrypted credentials store and injected server-side, **after** the approval
+//! gate has computed its redacted summary — so the secret never reaches the
+//! approval UI, the graph, the node output, or the logs.
+
+#![allow(unused_imports)]
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::{Config, HttpRequestConfig};
+use crate::security::SecurityPolicy;
+use crate::security::credentials::{HttpCredential, HttpCredentialsStore};
+use crate::tools::http_request_tool;
+use tinybox_bus::CommandClass;
+use tinytools::Tool as _;
+
+/// [`HttpClient`] adapter over `HttpRequestTool`
+/// (`tinytools_std::network::HttpRequestTool`, built by `tools/impl/network/host.rs`). Allowlist + DNS-rebind
+/// guard live inside `execute`, so this adapter gets them for free.
+///
+/// **B2:** also routes through the OpenHuman `ApprovalGate` before dispatch
+/// (same rationale/shape as [`OpenHumanTools::invoke`] — closes the Codex P1
+/// finding that flow HTTP nodes bypassed the Network approval gate).
+///
+/// **Phase 2 — `http_cred:<name>` resolution:** a `"http_cred:<name>"`
+/// `connection_ref` is now resolved against the credentials domain's
+/// [`HttpCredentialsStore`] (encrypted-at-rest bearer/basic/header templates).
+/// The resolved auth header is injected **server-side** into the outbound
+/// request — after the approval gate has already computed its redacted audit
+/// summary — so the secret is never surfaced to the approval UI, the flow
+/// engine/graph, the node's output, or the logs (only the header *name* and
+/// scheme are logged; the value is redacted). A `connection_ref` that names an
+/// **unknown** credential fails the request closed (`EngineError::Capability`)
+/// rather than silently sending it unauthenticated.
+pub struct OpenHumanHttp {
+ /// The context the run acts under, handed over by whoever started it.
+ pub ctx: crate::core::runtime::DispatchCtx,
+ /// The run's config snapshot, used to reload its anchored autonomy tier.
+ pub config: Arc<Config>,
+ pub security: Arc<SecurityPolicy>,
+ pub http_config: HttpRequestConfig,
+ pub http_creds: Arc<HttpCredentialsStore>,
+ /// The run's approval context (flow run correlation), handed to the gate
+ /// with every acting dispatch.
+ pub approval: crate::security::approval::ApprovalTurnContext,
+}
+
+/// Resolves an optional HTTP `connection_ref` to the stored credential to
+/// inject. Split out as a free function (over the store, not `&self`) so the
+/// resolve/fail-closed policy is unit-testable without constructing a full
+/// [`OpenHumanHttp`] adapter.
+///
+/// - `None` conn, or a `connection_ref` whose prefix isn't `http_cred:` →
+/// `Ok(None)` (no credential to inject; a non-`http_cred:` prefix is logged
+/// and ignored, matching the pre-Phase-2 behavior).
+/// - a `http_cred:<name>` naming a **known** credential → `Ok(Some(cred))`
+/// (secret-bearing — the caller injects it server-side, never logs it).
+/// - a `http_cred:<name>` naming an **unknown** credential, a malformed
+/// (empty/whitespace-only) name, or a store error → `Err` — the request
+/// must fail closed, never proceed unauthenticated. Distinguishing "no
+/// `http_cred:` prefix at all" from "`http_cred:` prefix with a malformed
+/// name" matters: [`http_cred_name`] collapses both to `None`, which would
+/// otherwise let a typo'd or data-derived empty ref (e.g. `"http_cred:"`)
+/// silently fall through to an unauthenticated request (Codex P2 finding).
+pub(crate) fn resolve_http_credential(
+ store: &HttpCredentialsStore,
+ conn: Option<&str>,
+) -> Result<Option<HttpCredential>> {
+ let Some(conn) = conn else {
+ return Ok(None);
+ };
+ if conn.strip_prefix("http_cred:").is_none() {
+ tracing::debug!(target: "flows", %conn, "[flows] http conn: unrecognized connection_ref prefix (expected `http_cred:<name>`) — ignoring");
+ return Ok(None);
+ }
+ let Some(name) = http_cred_name(conn) else {
+ tracing::warn!(
+ target: "flows",
+ %conn,
+ "[flows] http_request: connection_ref has the `http_cred:` prefix but no credential \
+ name — failing the request closed rather than sending it unauthenticated"
+ );
+ return Err(EngineError::Capability(format!(
+ "http_request connection_ref has a malformed http_cred name: {conn:?}"
+ )));
+ };
+
+ match store.get(name) {
+ Ok(Some(cred)) => {
+ tracing::debug!(
+ target: "flows",
+ cred = %name,
+ scheme = cred.scheme.as_str(),
+ "[flows] http_request: resolved http_cred (secret redacted)"
+ );
+ Ok(Some(cred))
+ }
+ Ok(None) => {
+ tracing::warn!(
+ target: "flows",
+ cred = %name,
+ "[flows] http_request: connection_ref names an unknown http_cred — failing the \
+ request closed rather than sending it unauthenticated"
+ );
+ Err(EngineError::Capability(format!(
+ "http_request connection_ref names an unknown http_cred: {name}"
+ )))
+ }
+ Err(e) => {
+ tracing::error!(
+ target: "flows",
+ cred = %name,
+ error = %e,
+ "[flows] http_request: failed to resolve http_cred from the store"
+ );
+ Err(EngineError::Capability(format!(
+ "failed to resolve http_cred '{name}': {e}"
+ )))
+ }
+ }
+}
+
+/// Merges a resolved credential's auth header into the outbound `request`'s
+/// `headers` object (creating it when absent), returning the header **name**
+/// that was injected for redacted logging. The header value carries the secret
+/// and is placed only into the request handed to `HttpRequestTool` — it is
+/// never logged or returned. An explicit stored credential wins over any inline
+/// same-named header the flow author set.
+pub(crate) fn inject_http_credential(request: &mut Value, cred: &HttpCredential) -> Result<String> {
+ let (header_name, header_value) = cred
+ .to_header()
+ .map_err(|e| EngineError::Capability(e.to_string()))?;
+
+ let obj = request.as_object_mut().ok_or_else(|| {
+ EngineError::Capability("http_request config must be a JSON object".to_string())
+ })?;
+ let headers_entry = obj
+ .entry("headers")
+ .or_insert_with(|| Value::Object(serde_json::Map::new()));
+ // A flow author may leave `headers` unset (null) — coerce to an object so
+ // the credential still injects. A non-object, non-null `headers` is a
+ // malformed config we refuse rather than silently drop the credential.
+ if headers_entry.is_null() {
+ *headers_entry = Value::Object(serde_json::Map::new());
+ }
+ let headers_obj = headers_entry.as_object_mut().ok_or_else(|| {
+ EngineError::Capability("http_request `headers` must be a JSON object".to_string())
+ })?;
+ headers_obj.insert(header_name.clone(), Value::String(header_value));
+
+ tracing::info!(
+ target: "flows",
+ cred = %cred.name,
+ scheme = cred.scheme.as_str(),
+ header = %header_name,
+ "[flows] http_request: injected stored credential header (value redacted)"
+ );
+ Ok(header_name)
+}
+
+#[async_trait]
+impl HttpClient for OpenHumanHttp {
+ async fn request(&self, mut request: Value, conn: Option<&str>) -> Result<Value> {
+ const TOOL_NAME: &str = "flows_http_request";
+
+ // Autonomy-tier gate (Phase 2): an http_request node reaches the network,
+ // so it is Network-class. A read-only run `Block`s here and never
+ // dispatches; Supervised/Full fall through to the ApprovalGate below.
+ // `gate_call_for_tier` is what actually performs the `Prompt` round-trip
+ // — it escalates a Supervised `Prompt` decision into a forced approval
+ // regardless of the flow's own `require_approval` toggle (Codex P1).
+ let security =
+ Arc::new(current_tier_policy(&self.ctx, &self.config, &self.security).await?);
+ let tier_decision =
+ enforce_node_tier_gate(&security, CommandClass::Network, "http_request")?;
+
+ // The approval gate summarizes/redacts the request BEFORE any credential
+ // is injected, so a stored secret never lands in the approval UI or
+ // audit trail. Injection happens strictly after this point.
+ let summary = crate::security::approval::summarize_action(TOOL_NAME, &request);
+ let redacted = crate::security::approval::redact_args(&request);
+ let (outcome, audit_id) = gate_call_for_tier(
+ &self.ctx,
+ &self.approval,
+ tier_decision,
+ TOOL_NAME,
+ &summary,
+ redacted,
+ )
+ .await;
+ if let crate::security::approval::GateOutcome::Deny { reason } = outcome {
+ return Err(EngineError::Capability(reason));
+ }
+
+ // Resolve `http_cred:<name>` to a stored credential and inject its auth
+ // header server-side. An unknown name fails the request closed (see
+ // `resolve_http_credential`) — we never send it unauthenticated.
+ if let Some(cred) = resolve_http_credential(&self.http_creds, conn)? {
+ inject_http_credential(&mut request, &cred)?;
+ }
+
+ let tool = http_request_tool(
+ &self.ctx,
+ security,
+ self.http_config.allowed_domains.clone(),
+ self.http_config.max_response_size,
+ self.http_config.timeout_secs,
+ );
+
+ tracing::debug!(
+ target: "flows",
+ method = ?request.get("method"),
+ url = ?request.get("url"),
+ "[flows] http_request: dispatching outbound request"
+ );
+
+ // `request` is already `{ method, url, headers?, body? }` — the node's
+ // config is the request descriptor; `HttpRequestTool::execute` reads
+ // only those keys and ignores the rest (e.g. `connection_ref`,
+ // `on_error`), so passing the whole config through is safe.
+ let result = tool.execute(request).await;
+
+ let outcome: Result<Value> = match result {
+ Ok(result) if result.is_error => {
+ // `HttpRequestTool::execute` always returns `Ok`, using
+ // `is_error` to signal a failed request (non-2xx, DNS/allowlist
+ // rejection, timeout, …) — surface that as a capability error
+ // so the engine's `on_error`/`retry` policy can act on it.
+ Err(EngineError::Capability(result.text()))
+ }
+ Ok(result) => Ok(json!({ "text": result.text() })),
+ Err(e) => Err(EngineError::Capability(e.to_string())),
+ };
+
+ if let Some(id) = audit_id {
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ let exec = if outcome.is_ok() {
+ crate::security::approval::ExecutionOutcome::Success
+ } else {
+ crate::security::approval::ExecutionOutcome::Failure
+ };
+ gate.record_execution(
+ &id,
+ exec,
+ outcome.as_ref().err().map(ToString::to_string).as_deref(),
+ );
+ }
+ }
+
+ outcome
+ }
+}
+
+#[cfg(test)]
+#[path = "http_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/http_tests.rs b/crates/openhuman-core/src/flows/tinyflows/caps/http_tests.rs
index e69de29bb2..cff79e191b 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/http_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/http_tests.rs
@@ -0,0 +1,25 @@
+use super::*;
+
+fn store(tmp: &tempfile::TempDir) -> HttpCredentialsStore {
+ HttpCredentialsStore::new(tmp.path(), false)
+}
+
+#[test]
+fn credential_resolution_ignores_absent_and_foreign_refs() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = store(&tmp);
+ assert!(resolve_http_credential(&store, None).unwrap().is_none());
+ assert!(
+ resolve_http_credential(&store, Some("composio:x:y"))
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[test]
+fn credential_resolution_fails_closed_for_malformed_or_unknown_refs() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = store(&tmp);
+ assert!(resolve_http_credential(&store, Some("http_cred:")).is_err());
+ assert!(resolve_http_credential(&store, Some("http_cred:missing")).is_err());
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/llm.rs b/crates/openhuman-core/src/flows/tinyflows/caps/llm.rs
index e69de29bb2..7ec03f8fcb 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/llm.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/llm.rs
@@ -0,0 +1,152 @@
+//! The `LlmProvider` capability, backed by OpenHuman's inference stack.
+//!
+//! What an `agent` node falls back to when no agent runner is installed, and
+//! what a raw completion node uses directly.
+
+#![allow(unused_imports)]
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::Config;
+use crate::inference::provider::{
+ create_chat_model_with_model_id_in, is_raw_passthrough_model, role_for_model_tier,
+};
+use tinyflows::nodes::integration::agent_prompt;
+use tinyinference_llm::model::ModelRequest;
+
+/// [`LlmProvider`] adapter over OpenHuman's inference stack
+/// (`crates/openhuman-core/src/inference/provider/`).
+///
+/// The `agent` node is single-completion in tinyflows 0.2 (no tool-calling
+/// loop, no sub-ports), so `complete` performs exactly one `provider.chat`
+/// call and returns its result — no agent loop is driven here.
+///
+/// **Structured output**: when the node requested it (an
+/// `output_parser.schema` or `response_format: "json"` in the config), the
+/// completion text is parsed as JSON and the **parsed object** is returned as
+/// the response value; otherwise the `{text: "..."}` shape is returned. Either
+/// way the tinyflows `agent` node wraps this in its stable output **envelope**
+/// `{ json, text, raw }`, so a downstream node binds `=item.json.<field>` for
+/// structured output or `=item.text` for prose (or
+/// `=nodes.<agent_id>.item.json.<field>` across nodes) — the parsed-vs-`{text}`
+/// shape is no longer visible to consumers. A completion that doesn't parse
+/// still lets the agent node's `output_parser` sub-port coerce it via the
+/// schema auto-fix path before enveloping.
+pub struct OpenHumanLlm {
+ pub ctx: crate::core::runtime::DispatchCtx,
+ pub config: Arc<Config>,
+}
+
+#[async_trait]
+impl LlmProvider for OpenHumanLlm {
+ async fn complete(&self, request: Value, conn: Option<&str>) -> Result<Value> {
+ if let Some(c) = conn {
+ // B1 does not resolve `connection_ref` to a specific BYOK account —
+ // `create_chat_provider` picks the configured provider for `role`.
+ tracing::debug!(target: "flows", conn = %c, "[flows] llm conn (not resolved in B1)");
+ }
+
+ let role = request
+ .get("role")
+ .and_then(Value::as_str)
+ .unwrap_or("summarization");
+
+ // Per-node model selection: an `agent` node may pin a **managed tier**
+ // (`config.model = "hint:reasoning"` / `"hint:chat"`, or a `hint:*` alias).
+ // Map that tier back to the workload role whose provider serves it so
+ // the completion routes to that tier on the managed backend (or the
+ // role's BYOK model) instead of the node's default `role`. Unknown /
+ // absent model strings leave the role untouched. `config.model` is
+ // trusted node config, never model output.
+ let node_model = request
+ .get("model")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+ let role = match node_model {
+ Some(model) => {
+ let mapped = role_for_model_tier(model);
+ tracing::debug!(
+ target: "flows",
+ node_model = model,
+ mapped_role = mapped,
+ "[flows] llm.complete: node pinned a model tier — routing by mapped role"
+ );
+ mapped
+ }
+ None => role,
+ };
+ let temperature = request
+ .get("temperature")
+ .and_then(Value::as_f64)
+ .unwrap_or(0.7);
+ let max_tokens = request
+ .get("max_tokens")
+ .and_then(Value::as_u64)
+ .and_then(|n| u32::try_from(n).ok());
+
+ let structured = structured_output_requested(&request);
+ let messages = build_completion_messages(&request);
+
+ tracing::debug!(
+ target: "flows",
+ role,
+ message_count = messages.len(),
+ structured,
+ "[flows] llm.complete: dispatching agent-node completion"
+ );
+
+ let (chat_model, model) =
+ create_chat_model_with_model_id_in(&self.ctx, role, &self.config, temperature)
+ .map_err(|e| EngineError::Capability(e.to_string()))?;
+ // `create_chat_provider` handed back the role's default model. If the node
+ // pinned a raw/BYOK id, forward it verbatim instead (issue #4598).
+ let model =
+ agent_prompt::resolve_completion_model(node_model, model, is_raw_passthrough_model);
+
+ let mut model_request = ModelRequest::new(
+ messages
+ .iter()
+ .map(crate::agent::tinyagents::chat_message_to_message)
+ .collect(),
+ )
+ .with_model(model.clone())
+ .with_temperature(temperature);
+ if let Some(max_tokens) = max_tokens {
+ model_request = model_request.with_max_tokens(max_tokens);
+ }
+ let response = chat_model
+ .invoke(&(), model_request)
+ .await
+ .map_err(|e| EngineError::Capability(e.to_string()))?;
+
+ // Structured mode: surface the parsed object itself so downstream
+ // `=item.<field>` / `=nodes.<id>.item.<field>` bindings work. The
+ // agent node's output_parser sub-port then validates it against the
+ // configured schema (and auto-fixes when it doesn't parse here).
+ if structured {
+ let text = response.text();
+ if let Some(parsed) = extract_structured_json(&text) {
+ tracing::debug!(
+ target: "flows",
+ "[flows] llm.complete: structured output extracted from completion text"
+ );
+ return Ok(parsed);
+ }
+ tracing::warn!(
+ target: "flows",
+ "[flows] llm.complete: structured output requested but no JSON extraction \
+ strategy succeeded — falling back to the {{text}} shape (the output_parser \
+ sub-port may still coerce it)"
+ );
+ }
+
+ Ok(model_response_to_completion_value(&response))
+ }
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs
index e69de29bb2..3162342e45 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs
@@ -0,0 +1,307 @@
+//! The capability seam: five adapters implementing `tinyflows::caps` traits
+//! over real OpenHuman services.
+//!
+//! Each tinyflows integration node hands its **whole** `node.config` to the
+//! matching trait method — the adapter interprets a free-form JSON value the
+//! flow author wrote, pulling a connection ref out of `config["connection_ref"]`
+//! where relevant. See `my_docs/ohxtf/b1-engine-seam-domain/04-capability-seam.md`
+//! for the source-verified node → trait contract this mirrors.
+//!
+//! All host errors are mapped to `tinyflows::error::EngineError::Capability`,
+//! per the crate's contract (`caps` traits return `tinyflows::error::Result`).
+
+#[cfg(test)]
+pub(crate) use crate::integrations::composio::flow_gate::composio_connection_id;
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::Value;
+#[cfg(test)]
+use serde_json::json;
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+#[cfg(test)]
+use tinyflows::model::WorkflowGraph;
+
+use crate::config::Config;
+#[cfg(test)]
+use crate::config::HttpRequestConfig;
+#[cfg(test)]
+use crate::flows;
+#[cfg(test)]
+use crate::security::GateDecision;
+use crate::security::SecurityPolicy;
+#[cfg(test)]
+use crate::security::credentials::HttpCredential;
+use crate::security::credentials::HttpCredentialsStore;
+use tinybox_bus::CommandClass;
+
+use super::*;
+
+/// Parses a `"http_cred:<name>"` `connection_ref` for [`OpenHumanHttp`],
+/// returning the trailing credential name. The host-side
+/// [`HttpCredentialsStore`] (encrypted-at-rest bearer/basic/header
+/// templates) is real and load-bearing — [`resolve_http_credential`] looks
+/// the extracted name up in it and injects the resolved auth header
+/// server-side. This function only does the parse; a malformed or missing
+/// name (`None`) is what lets the caller fail the request closed instead of
+/// silently sending it unauthenticated. See [`OpenHumanHttp::request`]'s doc
+/// and the "Phase 2" note on the [`OpenHumanHttp`] struct for the full
+/// resolution flow.
+pub(crate) fn http_cred_name(conn: &str) -> Option<&str> {
+ let name = conn.strip_prefix("http_cred:")?.trim();
+ (!name.is_empty()).then_some(name)
+}
+
+pub(crate) async fn classify_composio_action_for_tier(slug: &str) -> CommandClass {
+ crate::integrations::composio::flow_gate::classify_composio_action_for_tier(slug)
+}
+
+pub(crate) async fn is_curated_flow_tool(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ slug: &str,
+) -> bool {
+ crate::integrations::composio::flow_gate::is_curated_flow_tool(ctx, config, slug).await
+}
+
+/// [`ToolInvoker`] adapter over Composio (`crates/openhuman-core/src/integrations/composio/client.rs`).
+///
+/// **B2 (closes two B1 deviations, see
+/// `my_docs/ohxtf/b2-triggers-trust/01-triggers-and-trust.md` §4-5):**
+/// - **Curation + scope (hard allowlist)**: every call is checked against
+/// [`is_curated_flow_tool`] — a deny-by-default gate that only allows a
+/// slug resolving to a *known, curated* toolkit action, unlike the general
+/// agent tool-call path's more permissive
+/// `memory_sync::composio::providers::is_action_visible_with_pref` (see
+/// [`is_curated_flow_tool`]'s doc for why the two differ). A non-curated /
+/// unrecognized / out-of-scope slug is rejected with
+/// `EngineError::Capability("tool not permitted: <slug>")` before any
+/// Composio call. **As of tinyflows 0.3 this is load-bearing, not merely
+/// defense-in-depth**: integration-node config (including `slug`) is now
+/// `=`-expression evaluated against upstream/trigger data before `invoke`,
+/// so a trigger payload *can* influence which tool a `=`-derived slug
+/// resolves to. The curation gate runs on the **resolved** slug (verified:
+/// a `=item.tool`-derived unknown slug is rejected here before Composio),
+/// constraining any data-derived tool to the user's curated, in-scope,
+/// connected set — and it still closes the case where an author hand-types
+/// an arbitrary/typo'd slug.
+/// - **connection_ref**: `conn` (`"composio:<toolkit>:<connection_id>"`) is
+/// parsed and forwarded in both modes: Direct passes it to Composio's
+/// execute endpoint, while Backend includes it as `connectionId` in the
+/// authenticated `/agent-integrations/composio/execute` request. Omitting a
+/// ref deliberately keeps the ambient-account behavior. A supplied but
+/// stale/foreign id is still forwarded exactly so the provider rejects it;
+/// it must never degrade to the ambient account (fixes #5751 / E-m3).
+/// - **Trust gate**: invocation is also routed through the OpenHuman
+/// `ApprovalGate` (mirrors `tinyagents/middleware.rs::ApprovalSecurityMiddleware`)
+/// before dispatch, closing the Codex P1 finding that flow tool nodes
+/// bypassed the Network/tool approval gate entirely. `ops::flows_run` /
+/// `flows_resume` scope a `TrustedAutomation { Workflow }` origin around
+/// the whole run, so the gate either auto-allows (pre-declared trust root)
+/// or — when the flow's `require_approval` is set — parks for a real
+/// decision. No gate installed (unit tests, some hosts) means no gating,
+/// same as the existing agent tool-loop middleware.
+///
+/// // SECURITY NOTE (tinyflows 0.3, now the pinned version): integration nodes
+/// // `=`-resolve config from upstream/trigger data, so a trigger-driven flow
+/// // whose `slug`/`url` is `=`-derived lets untrusted trigger data pick *which*
+/// // curated + in-scope + connected tool/endpoint runs (blast radius bounded by
+/// // the curation + scope + connection checks above and the approval gate).
+/// // For such flows authors should set `require_approval`. FOLLOW-UP: auto-force
+/// // approval when a trigger-driven run's tool/http config contains `=`-exprs.
+pub struct OpenHumanTools {
+ /// The context the run acts under: the scope-pref reads of the curation
+ /// gate resolve against it rather than the calling task's own scope.
+ pub ctx: crate::core::runtime::DispatchCtx,
+ pub config: Arc<Config>,
+ pub security: Arc<SecurityPolicy>,
+ /// The run's approval context (flow run correlation), handed to the gate
+ /// with every acting dispatch.
+ pub approval: crate::security::approval::ApprovalTurnContext,
+}
+
+pub(crate) async fn preflight_composio_args(
+ config: &Config,
+ slug: &str,
+ args: &Value,
+) -> Result<()> {
+ crate::integrations::composio::flow_gate::preflight_composio_args(config, slug, args)
+ .await
+ .map_err(EngineError::Capability)
+}
+
+pub(crate) fn reject_unsuccessful_composio_response(
+ slug: &str,
+ response: crate::integrations::composio::ComposioExecuteResponse,
+) -> Result<crate::integrations::composio::ComposioExecuteResponse> {
+ crate::integrations::composio::flow_gate::reject_unsuccessful_composio_response(slug, response)
+ .map_err(EngineError::Capability)
+}
+
+/// A [`ToolInvoker`] decorator that runs the host's Composio required-arg
+/// preflight before delegating to `inner`.
+///
+/// Used by `dry_run_workflow`: the dry-run path executes against tinyflows'
+/// echo mocks, which would happily accept a `null` required arg — wrapping
+/// the mock invoker with this makes the wiring check actually check wiring,
+/// so an unwired required arg fails the dry run with the same actionable
+/// message a real run would produce.
+pub struct PreflightToolInvoker {
+ /// Host config, for the Composio schema lookup.
+ pub config: Arc<Config>,
+ /// The delegate that performs the actual invocation (e.g. the mock).
+ pub inner: Arc<dyn ToolInvoker>,
+}
+
+#[async_trait]
+impl ToolInvoker for PreflightToolInvoker {
+ async fn invoke(&self, slug: &str, args: Value, conn: Option<&str>) -> Result<Value> {
+ // Ask the backend that owns this slug to validate the args. Previously
+ // this called the Composio preflight directly behind a
+ // `!slug.starts_with("oh:")` test, which duplicated the dispatch rule
+ // and hard-wired one namespace's knowledge into a generic wrapper.
+ if let Some(backend) = tools::backend_for(slug) {
+ backend.preflight(&self.config, slug, &args).await?;
+ }
+ self.inner.invoke(slug, args, conn).await
+ }
+}
+
+#[async_trait]
+impl ToolInvoker for OpenHumanTools {
+ async fn invoke(&self, slug: &str, args: Value, conn: Option<&str>) -> Result<Value> {
+ let ctx = tools::ToolCallCtx {
+ dispatch: &self.ctx,
+ config: &self.config,
+ security: &self.security,
+ approval: &self.approval,
+ };
+ match tools::backend_for(slug) {
+ Some(backend) => backend.invoke(&ctx, slug, args, conn).await,
+ None => Err(tools::unclaimed_slug_error(slug)),
+ }
+ }
+}
+
+/// Builds the [`Capabilities`] bundle for one run, wiring each supported
+/// host-injected traits to a real OpenHuman adapter (see each adapter above,
+/// and [`super::memory_adapter::OpenHumanMemory`] for `memory`, for its
+/// contract).
+///
+/// `state_namespace` scopes the flow state KV ([`crate::flows::tinyflows::state::FlowState`]:
+/// `flows.db`, or the storage backend when one is configured) so two saved flows that
+/// use the same state key never read or overwrite each other — callers pass a
+/// per-flow namespace (e.g. `"flow:<id>"`). This KV namespace is unrelated to
+/// flow-scoped memory: `OpenHumanMemory` tags memory items with
+/// `flows::flow_tag`, derived independently from the run's trusted origin.
+///
+/// `ctx` is the context the run acts under: the agent, code and HTTP adapters
+/// act for it instead of reading the calling task's own scope.
+///
+/// `flow_run` is the run the capabilities serve: every acting dispatch hands it
+/// to the approval gate (with the tool call), so a parked approval is stamped
+/// with the exact flow and run. `None` for a run with no flow identity (a dry
+/// run, a preview).
+pub fn build_capabilities(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: Arc<Config>,
+ state_namespace: impl Into<String>,
+ flow_run: Option<crate::security::approval::FlowRunContext>,
+) -> Capabilities {
+ let approval = crate::security::approval::ApprovalTurnContext {
+ flow_run,
+ ..Default::default()
+ };
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let http_config = config.http_request.clone();
+ let http_creds = Arc::new(HttpCredentialsStore::from_config(&config));
+
+ Capabilities {
+ llm: Arc::new(OpenHumanLlm {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ }),
+ tools: Arc::new(OpenHumanTools {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ security: security.clone(),
+ approval: approval.clone(),
+ }),
+ http: Arc::new(OpenHumanHttp {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ security: security.clone(),
+ http_config,
+ http_creds,
+ approval: approval.clone(),
+ }),
+ code: Arc::new(OpenHumanCode {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ security: security.clone(),
+ approval: approval.clone(),
+ }),
+ state: crate::flows::tinyflows::state::FlowState::open(&config, state_namespace)
+ .into_state_store(),
+ agent: Some(Arc::new(OpenHumanAgentRunner {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ approval: approval.clone(),
+ })),
+ // Shell execution needs a dedicated OpenHuman adapter that applies the
+ // host's autonomy and sandbox policy. Keep the capability unavailable
+ // until that boundary exists rather than inheriting ambient process
+ // access from the workflow engine.
+ shell: None,
+ // `spawn`/`gate` overlap only when a TaskRunner is injected. With
+ // `None` the engine still produces the right answer — `spawn` runs its
+ // work inline and hands back a settled ticket — so the failure mode is
+ // a silent loss of concurrency rather than an error, which is exactly
+ // the kind that survives a smoke test. Flow runs are already on tokio,
+ // so take the crate's tokio-backed runner. It is in-process only:
+ // tickets do not survive a restart, which is the right bound for work
+ // a single run collects at its own gate.
+ tasks: Some(Arc::new(TokioTaskRunner::new())),
+ // OpenHuman already persists `RunOutcome::pending_approvals` and
+ // resumes named gates through `flows_resume`. Leaving the optional
+ // provider unset deliberately selects Tinyflows' compatible fallback
+ // instead of creating a second review store beside that surface.
+ approvals: None,
+ memory: Some(Arc::new(
+ crate::flows::tinyflows::memory_adapter::OpenHumanMemory {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ security,
+ approval,
+ },
+ )),
+ resolver: Arc::new(OpenHumanWorkflowResolver { config }),
+ }
+}
+
+/// Opens the durable, cross-process checkpointer a `flows_run` uses via
+/// `tinyflows::engine::run_with_checkpointer`:
+/// `tinyflows_drivers::DriverCheckpointer` over the flow catalog's storage
+/// ([`crate::flows::store`]) in the acting agent's scope.
+///
+/// tinyflows no longer has a SQLite checkpointer; the `checkpoints.db` it wrote
+/// is imported once, so a run interrupted before the upgrade still resumes.
+pub fn open_flow_checkpointer(
+ config: &Config,
+) -> anyhow::Result<Arc<dyn tinyflows::engine::Checkpointer<serde_json::Value>>> {
+ let scoped = crate::flows::store::scoped(config)?;
+ tracing::debug!(target: "flows", "[flows] opening checkpointer on the flow storage");
+ Ok(Arc::new(tinyflows_drivers::DriverCheckpointer::<
+ serde_json::Value,
+ >::new(Arc::clone(scoped.documents()))))
+}
+
+#[cfg(test)]
+#[path = "ops_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
index e69de29bb2..8ffe8fa8d1 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
@@ -0,0 +1,580 @@
+use super::*;
+use tinyagents_harness::tool::response_fields_from_schema;
+use tinyflows::nodes::integration::agent_prompt::scale_timeout_for_iteration_cap;
+use tinytools::status::POLICY_BLOCKED_MARKER;
+
+/// The tier gate an `http_request` (Network-class) node calls: BLOCKED under
+/// a read-only tier, and passed through (to the ApprovalGate) under
+/// supervised/full.
+#[test]
+fn http_request_node_tier_gate_blocks_readonly_allows_higher() {
+ use crate::security::AutonomyLevel;
+
+ let err = enforce_node_tier_gate(
+ &policy(AutonomyLevel::ReadOnly),
+ CommandClass::Network,
+ "http_request",
+ )
+ .expect_err("read-only must block a Network-class http_request node");
+ if let EngineError::Capability(msg) = err {
+ assert!(
+ msg.contains(POLICY_BLOCKED_MARKER),
+ "read-only block must carry the policy-blocked marker: {msg}"
+ );
+ } else {
+ panic!("expected EngineError::Capability for a blocked node");
+ }
+
+ // Supervised/full do not hard-block — they fall through to the
+ // ApprovalGate (which performs the Prompt round-trip).
+ assert!(
+ enforce_node_tier_gate(
+ &policy(AutonomyLevel::Supervised),
+ CommandClass::Network,
+ "http_request"
+ )
+ .is_ok()
+ );
+ assert!(
+ enforce_node_tier_gate(
+ &policy(AutonomyLevel::Full),
+ CommandClass::Network,
+ "http_request"
+ )
+ .is_ok()
+ );
+}
+
+/// The tier gate a `code` (Write-class) node calls: BLOCKED under read-only,
+/// allowed under full, prompt-able (not blocked) under supervised.
+#[test]
+fn code_node_tier_gate_blocks_readonly_allows_full() {
+ use crate::security::AutonomyLevel;
+
+ assert!(
+ enforce_node_tier_gate(
+ &policy(AutonomyLevel::ReadOnly),
+ CommandClass::Write,
+ "code"
+ )
+ .is_err()
+ );
+ assert!(
+ enforce_node_tier_gate(
+ &policy(AutonomyLevel::Supervised),
+ CommandClass::Write,
+ "code"
+ )
+ .is_ok()
+ );
+ assert!(
+ enforce_node_tier_gate(&policy(AutonomyLevel::Full), CommandClass::Write, "code").is_ok()
+ );
+}
+
+/// A long-lived code capability must observe a tier downgrade at the same
+/// config path before it reaches code staging or sandbox execution.
+/// End-to-end at the adapter: an `http_request` node under a read-only tier
+/// is refused BEFORE any network egress (the tier gate fires ahead of the
+/// approval gate, credential resolution, and dispatch).
+#[tokio::test]
+async fn http_adapter_blocks_under_readonly_tier() {
+ use crate::security::AutonomyLevel;
+
+ let (_dir, creds) = http_cred_store();
+ let mut config = Config::default();
+ config.autonomy.enabled = true;
+ config.autonomy.level = AutonomyLevel::ReadOnly;
+ let http = OpenHumanHttp {
+ ctx: crate::core::runtime::DispatchCtx::unbound(),
+ config: Arc::new(config),
+ security: Arc::new(policy(AutonomyLevel::ReadOnly)),
+ http_config: HttpRequestConfig::default(),
+ http_creds: Arc::new(creds),
+ approval: Default::default(),
+ };
+
+ let request = json!({ "method": "GET", "url": "https://example.com" });
+ let err = http
+ .request(request, None)
+ .await
+ .expect_err("read-only http_request node must be blocked");
+ if let EngineError::Capability(msg) = err {
+ assert!(
+ msg.contains(POLICY_BLOCKED_MARKER),
+ "expected a policy-blocked refusal, got: {msg}"
+ );
+ } else {
+ panic!("expected EngineError::Capability");
+ }
+}
+
+/// End-to-end at the adapter: a Composio `tool_call` node under a
+/// read-only tier is refused BEFORE it ever reaches the curation gate or
+/// any Composio dispatch — closes the compound bypass where the Composio
+/// branch of `OpenHumanTools::invoke` reached `intercept_audited` without
+/// ever consulting the autonomy tier, unlike the native `oh:`,
+/// `http_request`, and `code` node paths, which all gate on tier first.
+#[tokio::test]
+async fn composio_tool_call_blocks_under_readonly_tier() {
+ use crate::security::AutonomyLevel;
+
+ let tools = OpenHumanTools {
+ ctx: crate::core::runtime::DispatchCtx::unbound(),
+ config: Arc::new(Config::default()),
+ security: Arc::new(policy(AutonomyLevel::ReadOnly)),
+ approval: Default::default(),
+ };
+
+ let err = tools
+ .invoke("SLACK_SEND_MESSAGE", json!({}), None)
+ .await
+ .expect_err("read-only tier must block a Composio tool_call node before dispatch");
+ if let EngineError::Capability(msg) = err {
+ assert!(
+ msg.contains(POLICY_BLOCKED_MARKER),
+ "expected a policy-blocked refusal, got: {msg}"
+ );
+ } else {
+ panic!("expected EngineError::Capability");
+ }
+}
+
+// ── Effect-aware Composio tier gating (fixes reads parking as pending
+// approvals): the tier gate must classify a Composio action by its
+// curated [`ToolScope`], not blanket-treat every action as `Network`.
+// Only a curated `Read` entry skips the prompt; curated `Write`/`Admin`,
+// an uncurated toolkit, or an unparseable slug all still classify as
+// `Network` (fail-safe — same class `http_request` uses).
+
+/// A genuinely curated read (`TWITTER_RECENT_SEARCH`) must resolve to
+/// `CommandClass::Read`, which `ReadOnly`'s gate matrix allows — closing
+/// the bug where every Composio action (reads included) hard-blocked
+/// under a read-only tier.
+#[tokio::test]
+async fn composio_read_action_allowed_under_readonly_tier() {
+ use crate::security::AutonomyLevel;
+
+ let class = classify_composio_action_for_tier("TWITTER_RECENT_SEARCH").await;
+ assert_eq!(class, CommandClass::Read);
+ assert_eq!(
+ enforce_node_tier_gate(&policy(AutonomyLevel::ReadOnly), class, "tool_call")
+ .expect("a curated Read action must not be blocked under ReadOnly"),
+ GateDecision::Allow
+ );
+
+ // End-to-end: the adapter itself must not refuse before dispatch —
+ // it may still fail downstream (no Composio session configured in
+ // this test), but never with the policy-blocked marker.
+ let tools = OpenHumanTools {
+ ctx: crate::core::runtime::DispatchCtx::unbound(),
+ config: Arc::new(Config::default()),
+ security: Arc::new(policy(AutonomyLevel::ReadOnly)),
+ approval: Default::default(),
+ };
+ let err = tools
+ .invoke("TWITTER_RECENT_SEARCH", json!({}), None)
+ .await
+ .expect_err("no live Composio session is configured in this test");
+ if let EngineError::Capability(msg) = err {
+ assert!(
+ !msg.contains(POLICY_BLOCKED_MARKER),
+ "a curated read must never be refused by the autonomy-tier gate, got: {msg}"
+ );
+ } else {
+ panic!("expected EngineError::Capability");
+ }
+}
+
+/// A curated read under Supervised classifies as `CommandClass::Read`,
+/// which the gate matrix always `Allow`s — so it can never trigger the
+/// Supervised `Prompt` round-trip (the actual pending-approval bug: a
+/// blanket `Network` classification prompted for every Composio call,
+/// reads included).
+#[tokio::test]
+async fn composio_read_action_does_not_prompt_under_supervised_tier() {
+ use crate::security::AutonomyLevel;
+
+ let class = classify_composio_action_for_tier("TWITTER_RECENT_SEARCH").await;
+ assert_eq!(class, CommandClass::Read);
+ assert_eq!(
+ enforce_node_tier_gate(&policy(AutonomyLevel::Supervised), class, "tool_call")
+ .expect("a curated Read action must not be blocked under Supervised"),
+ GateDecision::Allow,
+ "a curated read must resolve to Allow, never Prompt, under Supervised"
+ );
+
+ let tools = OpenHumanTools {
+ ctx: crate::core::runtime::DispatchCtx::unbound(),
+ config: Arc::new(Config::default()),
+ security: Arc::new(policy(AutonomyLevel::Supervised)),
+ approval: Default::default(),
+ };
+ let err = tools
+ .invoke("TWITTER_RECENT_SEARCH", json!({}), None)
+ .await
+ .expect_err("no live Composio session is configured in this test");
+ if let EngineError::Capability(msg) = err {
+ assert!(
+ !msg.contains(POLICY_BLOCKED_MARKER),
+ "a curated read must pass the tier gate under Supervised, got: {msg}"
+ );
+ } else {
+ panic!("expected EngineError::Capability");
+ }
+}
+
+/// Guard: a curated *write* action must still resolve to a
+/// `Network`-class decision that `Prompt`s under Supervised — the
+/// effect-aware classification must never widen who skips approval
+/// beyond curated reads.
+#[tokio::test]
+async fn composio_write_action_still_prompts_under_supervised_tier() {
+ use crate::security::AutonomyLevel;
+
+ for slug in ["TWITTER_CREATION_OF_A_POST", "GMAIL_SEND_EMAIL"] {
+ let class = classify_composio_action_for_tier(slug).await;
+ assert_eq!(
+ class,
+ CommandClass::Network,
+ "slug {slug} must classify as Network"
+ );
+ assert_eq!(
+ enforce_node_tier_gate(&policy(AutonomyLevel::Supervised), class, "tool_call")
+ .expect("a Network-class action is not blocked (only prompted) under Supervised"),
+ GateDecision::Prompt,
+ "slug {slug} must still require a Supervised-tier approval prompt"
+ );
+ }
+}
+
+/// Guard: an uncurated / unrecognized slug must fail safe to
+/// `Network` (never `Read`) so it still prompts under Supervised and
+/// blocks under ReadOnly — an agent can't dodge approval just by
+/// calling a toolkit action OpenHuman hasn't curated yet.
+#[tokio::test]
+async fn composio_unknown_slug_prompts_under_supervised_tier() {
+ use crate::security::AutonomyLevel;
+
+ let class = classify_composio_action_for_tier("UNKNOWN_SERVICE_DO_THING").await;
+ assert_eq!(class, CommandClass::Network);
+ assert_eq!(
+ enforce_node_tier_gate(&policy(AutonomyLevel::Supervised), class, "tool_call")
+ .expect("Network-class is prompted, not blocked, under Supervised"),
+ GateDecision::Prompt
+ );
+ assert!(enforce_node_tier_gate(&policy(AutonomyLevel::ReadOnly), class, "tool_call").is_err());
+}
+
+/// A `Prompt` tier decision on a default (`require_approval: false`)
+/// workflow trust root escalates to `require_approval: true` — the forced
+/// human-in-the-loop round trip that closes the Codex P1 finding.
+#[test]
+fn prompt_decision_escalates_default_workflow_origin() {
+ let escalated =
+ escalated_origin_for_prompt(GateDecision::Prompt, Some(workflow_origin("flow-1", false)))
+ .expect("a Prompt decision on require_approval=false must escalate");
+ assert!(matches!(
+ escalated,
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Workflow {
+ require_approval: true
+ },
+ ..
+ }
+ ));
+}
+
+/// A flow that already opted into `require_approval: true` needs no
+/// escalation — it's already forced through the parking flow.
+#[test]
+fn prompt_decision_does_not_re_escalate_already_gated_workflow() {
+ assert!(
+ escalated_origin_for_prompt(GateDecision::Prompt, Some(workflow_origin("flow-1", true)))
+ .is_none()
+ );
+}
+
+/// An `Allow` tier decision never escalates, regardless of the workflow's
+/// `require_approval` toggle — Full-tier runs keep running unattended.
+#[test]
+fn allow_decision_never_escalates() {
+ assert!(
+ escalated_origin_for_prompt(GateDecision::Allow, Some(workflow_origin("flow-1", false)))
+ .is_none()
+ );
+}
+
+/// No scoped origin (or a non-Workflow origin) never escalates — there is
+/// nothing to force through the workflow-specific parking flow.
+#[test]
+fn prompt_decision_does_not_escalate_without_a_workflow_origin() {
+ assert!(escalated_origin_for_prompt(GateDecision::Prompt, None).is_none());
+}
+
+// ── Nested agent-node harness escalation (issue #4595) ─────────────────
+//
+// The `agent` node's harness turn runs the full agent tool loop, and the
+// flow author never pre-declared the tool selection (only the `agent_ref`).
+// So `escalated_origin_for_nested_harness` must escalate a default
+// `Workflow { require_approval: false }` origin so
+// `ApprovalGate::intercept_audited` can't apply its
+// pre-declared-action `Allow` shortcut to tools the nested LLM picks at
+// runtime.
+
+/// A default `require_approval: false` workflow origin unconditionally
+/// escalates: the nested harness's tool selection was not pre-declared, so
+/// the trust-root shortcut in `ApprovalGate` must not apply. `job_id` is
+/// preserved so the parked approval is still attributable to the flow run.
+#[test]
+fn nested_harness_escalates_default_workflow_origin_and_preserves_job_id() {
+ let escalated = escalated_origin_for_nested_harness(Some(workflow_origin("flow-42", false)))
+ .expect("a default require_approval=false workflow must escalate");
+ match escalated {
+ AgentTurnOrigin::TrustedAutomation {
+ job_id,
+ source:
+ TrustedAutomationSource::Workflow {
+ require_approval: true,
+ },
+ } => assert_eq!(job_id, "flow-42"),
+ other => panic!("expected escalated Workflow origin, got {other:?}"),
+ }
+}
+
+/// A flow that already opted into `require_approval: true` needs no
+/// escalation — the parking branch already applies.
+#[test]
+fn nested_harness_does_not_re_escalate_already_gated_workflow() {
+ assert!(escalated_origin_for_nested_harness(Some(workflow_origin("flow-42", true,))).is_none());
+}
+
+/// A non-Workflow origin (Cron, Cli, WebChat, Unknown, …) passes through
+/// unchanged: their own gate branches already make the right decision.
+#[test]
+fn nested_harness_does_not_escalate_non_workflow_origin() {
+ assert!(
+ escalated_origin_for_nested_harness(Some(AgentTurnOrigin::TrustedAutomation {
+ job_id: "cron-1".into(),
+ source: TrustedAutomationSource::Cron,
+ }))
+ .is_none()
+ );
+ assert!(escalated_origin_for_nested_harness(Some(AgentTurnOrigin::Cli)).is_none());
+}
+
+/// No scoped origin (unlabelled caller) passes through: the gate maps it
+/// to `Unknown` and fails closed on external_effect tools already, so we
+/// don't invent an escalation.
+#[test]
+fn nested_harness_does_not_escalate_without_an_origin() {
+ assert!(escalated_origin_for_nested_harness(None).is_none());
+}
+
+// ── Issue #4868 — agent-node iteration cap + timeout scaling ───────────
+
+/// Regression for issue #4868: the agent-node runtime path
+/// (`OpenHumanAgentRunner::run_via_harness`) must build an `Agent` that
+/// carries `agent_ref`'s definition's effective cap (50 for an
+/// extended-policy agent), not the global `config.agent.max_tool_iterations`
+/// default (10). This mirrors the exact build step `run_via_harness` takes
+/// before dispatching the turn (so it doesn't require a live model
+/// provider to exercise).
+#[test]
+fn agent_node_runtime_resolves_to_the_definitions_effective_iteration_cap() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = resolver_test_config(&tmp);
+ assert_eq!(config.agent.max_tool_iterations, 10);
+
+ crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global(
+ &config.workspace_dir,
+ )
+ .expect("agent registry init");
+ let def = crate::agent::harness::host_definition::AgentDefinitionRegistry::global()
+ .expect("registry initialised")
+ .get("planner")
+ .expect("planner definition registered")
+ .clone();
+ let expected = def.effective_max_iterations();
+ assert_eq!(expected, 50);
+
+ let agent = crate::agent::OpenHumanSessionHost::from_config_for_agent(
+ &crate::core::runtime::DispatchCtx::unbound(),
+ &config,
+ "planner",
+ )
+ .expect("build planner agent");
+ assert_eq!(agent.agent_config().max_tool_iterations, expected);
+
+ // And the timeout scaling this cap feeds into actually widens the
+ // default 240s bound for this node.
+ let base_timeout = clamp_run_timeout_secs(None);
+ assert_eq!(base_timeout, 240);
+ let scaled =
+ scale_timeout_for_iteration_cap(base_timeout, agent.agent_config().max_tool_iterations);
+ assert_eq!(scaled, 600);
+}
+
+/// The resolver loads a saved flow's graph by its id — the by-`workflow_id`
+/// sub_workflow path resolves against the real flows store.
+#[tokio::test]
+async fn resolver_loads_saved_flow_graph_by_id() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = Arc::new(resolver_test_config(&tmp));
+
+ let graph_json = serde_json::to_value(trigger_only_graph()).unwrap();
+ let flow = flows::ops::flows_create(&config, "child".to_string(), graph_json, false)
+ .await
+ .expect("create flow");
+ let flow_id = flow.value.id.clone();
+
+ let resolver = OpenHumanWorkflowResolver {
+ config: config.clone(),
+ };
+ let graph = resolver
+ .resolve(&flow_id)
+ .await
+ .expect("resolver should load the saved flow graph");
+ assert_eq!(graph.nodes.len(), 1);
+ assert_eq!(graph.nodes[0].id, "t");
+}
+
+/// An unknown workflow_id surfaces a capability error naming the id, rather
+/// than silently resolving to nothing.
+#[tokio::test]
+async fn resolver_unknown_id_is_a_capability_error() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = Arc::new(resolver_test_config(&tmp));
+ let resolver = OpenHumanWorkflowResolver { config };
+
+ let err = resolver
+ .resolve("does-not-exist")
+ .await
+ .expect_err("unknown workflow_id must error");
+ match err {
+ EngineError::Capability(msg) => assert!(
+ msg.contains("does-not-exist"),
+ "error should name the missing id: {msg}"
+ ),
+ other => panic!("expected a capability error, got: {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn resolver_rejects_an_engine_incompatible_saved_graph() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = Arc::new(resolver_test_config(&tmp));
+ let flow = flows::ops::flows_create(
+ &config,
+ "legacy child".to_string(),
+ serde_json::to_value(trigger_only_graph()).unwrap(),
+ false,
+ )
+ .await
+ .unwrap()
+ .value;
+ let unsafe_graph = json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Trigger" },
+ { "id": "outer", "kind": "condition", "name": "Outer", "config": { "field": "outer" } },
+ { "id": "inner", "kind": "condition", "name": "Inner", "config": { "field": "inner" } },
+ { "id": "outer_else", "kind": "output_parser", "name": "Outer else" },
+ { "id": "inner_else", "kind": "output_parser", "name": "Inner else" },
+ { "id": "a", "kind": "output_parser", "name": "A" },
+ { "id": "c", "kind": "output_parser", "name": "C" },
+ { "id": "m", "kind": "merge", "name": "Merge" }
+ ],
+ "edges": [
+ { "from_node": "t", "from_port": "main", "to_node": "outer" },
+ { "from_node": "t", "from_port": "main", "to_node": "c" },
+ { "from_node": "outer", "from_port": "true", "to_node": "inner" },
+ { "from_node": "outer", "from_port": "false", "to_node": "outer_else" },
+ { "from_node": "inner", "from_port": "true", "to_node": "a" },
+ { "from_node": "inner", "from_port": "false", "to_node": "inner_else" },
+ { "from_node": "a", "from_port": "main", "to_node": "m" },
+ { "from_node": "c", "from_port": "main", "to_node": "m" }
+ ]
+ });
+ // Stage a stored graph no save path would accept: written raw, under the
+ // flow's id, as a legacy row would be.
+ crate::flows::store::force_corrupt_graph_json_for_test(
+ &config,
+ &flow.id,
+ &unsafe_graph.to_string(),
+ )
+ .unwrap();
+
+ let error = OpenHumanWorkflowResolver { config }
+ .resolve(&flow.id)
+ .await
+ .expect_err("resolver must reject an incompatible legacy child");
+ match error {
+ EngineError::Capability(message) => assert!(
+ message.contains("unsupported_nested_conditional_fan_in"),
+ "{message}"
+ ),
+ other => panic!("expected a capability error, got: {other:?}"),
+ }
+}
+
+// ── response_fields_from_schema ─────────────────────────────────────────
+// Direct unit tests for the pure schema-extraction step inside
+// `composio_response_fields`'s live-fetch loop — cheaper and more
+// targeted than exercising the whole `composio_list_tools` round trip,
+// and covers the schema shapes that loop actually has to handle.
+
+#[test]
+fn response_fields_from_schema_reads_standard_properties_object() {
+ let schema = json!({
+ "type": "object",
+ "properties": { "id": {"type": "string"}, "threadId": {"type": "string"} }
+ });
+ assert_eq!(
+ response_fields_from_schema(Some(&schema)),
+ vec!["id".to_string(), "threadId".to_string()]
+ );
+}
+
+#[test]
+fn response_fields_from_schema_reads_nested_data_error_wrapper_as_top_level_keys() {
+ // A `{data, error}` envelope has no special unwrapping — the function
+ // documents (and this test locks in) that it reports the schema's own
+ // top-level property names, not the fields nested inside `data`.
+ let schema = json!({
+ "type": "object",
+ "properties": {
+ "data": {"type": "object", "properties": {"id": {"type": "string"}}},
+ "error": {"type": "string"}
+ }
+ });
+ assert_eq!(
+ response_fields_from_schema(Some(&schema)),
+ vec!["data".to_string(), "error".to_string()]
+ );
+}
+
+#[test]
+fn response_fields_from_schema_falls_back_to_top_level_keys_minus_schema_keywords() {
+ // Legacy/loose shape with no `properties` wrapper: falls back to the
+ // schema object's own keys, filtering out JSON-Schema keywords.
+ let schema = json!({
+ "type": "object",
+ "description": "legacy shape",
+ "id": {"type": "string"},
+ "threadId": {"type": "string"}
+ });
+ assert_eq!(
+ response_fields_from_schema(Some(&schema)),
+ vec!["id".to_string(), "threadId".to_string()]
+ );
+}
+
+#[test]
+fn response_fields_from_schema_empty_for_none_or_non_object() {
+ assert!(response_fields_from_schema(None).is_empty());
+ assert!(response_fields_from_schema(Some(&json!("not an object"))).is_empty());
+ assert!(response_fields_from_schema(Some(&json!({}))).is_empty());
+}
+
+#[path = "ops_tier_live_config_tests.rs"]
+mod live_config_tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_live_config_tests.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_live_config_tests.rs
index e69de29bb2..e2ea1f61e9 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_live_config_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_live_config_tests.rs
@@ -0,0 +1,451 @@
+use super::*;
+
+fn live_tier_context(config: &Config) -> crate::core::runtime::DispatchCtx {
+ let parent = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(config.workspace_dir.clone()),
+ );
+ let context = parent.derive_with(crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::default(),
+ ));
+ crate::core::runtime::DispatchCtx::new(context)
+}
+
+fn persisted_tier_config(
+ dir: &std::path::Path,
+ enabled: bool,
+ level: crate::security::AutonomyLevel,
+) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.action_dir = dir.join("action");
+ config.autonomy.enabled = enabled;
+ config.autonomy.level = level;
+ config
+}
+
+async fn save_tier_config(config: &Config) {
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ std::fs::create_dir_all(&config.action_dir).unwrap();
+ config.save().await.unwrap();
+}
+
+fn has_issue48_workflow_origin(ctx: &crate::core::runtime::DispatchCtx) -> bool {
+ matches!(
+ ctx.turn_origin(),
+ Some(crate::agent::turn_origin::AgentTurnOrigin::TrustedAutomation {
+ job_id,
+ source: crate::agent::turn_origin::TrustedAutomationSource::Workflow {
+ require_approval: true,
+ },
+ }) if job_id == "issue48-flow-run"
+ )
+}
+
+#[tokio::test]
+async fn one_live_capability_observes_full_readonly_full_updates() {
+ use crate::security::AutonomyLevel;
+
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = persisted_tier_config(dir.path(), true, AutonomyLevel::Full);
+ save_tier_config(&config).await;
+ let decoy = persisted_tier_config(
+ &dir.path().join("decoy-profile"),
+ true,
+ AutonomyLevel::ReadOnly,
+ );
+ save_tier_config(&decoy).await;
+ let origin = crate::agent::turn_origin::AgentTurnOrigin::TrustedAutomation {
+ job_id: "issue48-flow-run".to_string(),
+ source: crate::agent::turn_origin::TrustedAutomationSource::Workflow {
+ require_approval: true,
+ },
+ };
+ let ctx = live_tier_context(&config).with_turn_origin(origin.clone());
+ assert!(has_issue48_workflow_origin(&ctx));
+ let mut baseline =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ baseline.trusted_roots.push(crate::security::TrustedRoot {
+ path: dir.path().join("trusted").display().to_string(),
+ access: crate::security::TrustedAccess::ReadWrite,
+ });
+ baseline.max_actions_per_hour = 2;
+ baseline.tracker.record();
+ let fresh = current_tier_policy(&ctx, &config, &baseline).await.unwrap();
+ assert_eq!(fresh.workspace_dir, baseline.workspace_dir);
+ assert_eq!(fresh.action_dir, baseline.action_dir);
+ assert_eq!(fresh.trusted_roots, baseline.trusted_roots);
+ assert_eq!(fresh.tracker.count(), baseline.tracker.count());
+ assert!(fresh.record_action());
+ assert_eq!(baseline.tracker.count(), 2);
+ let next_refresh = current_tier_policy(&ctx, &config, &baseline).await.unwrap();
+ assert!(next_refresh.is_rate_limited());
+ assert_eq!(next_refresh.tracker.count(), 2);
+
+ assert_eq!(
+ enforce_current_node_tier_gate(&ctx, &config, &baseline, CommandClass::Write, "code")
+ .await
+ .unwrap(),
+ GateDecision::Allow
+ );
+ assert!(
+ has_issue48_workflow_origin(&ctx),
+ "refreshing the policy must retain the dispatch's workflow origin"
+ );
+ config.autonomy.level = AutonomyLevel::ReadOnly;
+ save_tier_config(&config).await;
+ assert!(
+ enforce_current_node_tier_gate(&ctx, &config, &baseline, CommandClass::Write, "code")
+ .await
+ .is_err()
+ );
+
+ config.autonomy.level = AutonomyLevel::Full;
+ save_tier_config(&config).await;
+ assert_eq!(
+ enforce_current_node_tier_gate(&ctx, &config, &baseline, CommandClass::Write, "code")
+ .await
+ .unwrap(),
+ GateDecision::Allow,
+ "a config-derived tier must be allowed to upgrade again"
+ );
+ assert!(has_issue48_workflow_origin(&ctx));
+}
+
+#[tokio::test]
+async fn live_tier_reload_failure_fails_closed() {
+ use crate::security::AutonomyLevel;
+
+ let dir = tempfile::tempdir().unwrap();
+ let config = persisted_tier_config(dir.path(), true, AutonomyLevel::Full);
+ std::fs::create_dir_all(&config.config_path).unwrap();
+ let ctx = live_tier_context(&config);
+ let baseline =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ let error =
+ enforce_current_node_tier_gate(&ctx, &config, &baseline, CommandClass::Write, "code")
+ .await
+ .expect_err("a directory at config_path must not fall back to captured Full");
+ assert!(matches!(
+ error,
+ EngineError::Capability(ref message) if message.contains(POLICY_BLOCKED_MARKER)
+ ));
+}
+
+#[tokio::test]
+async fn malformed_live_config_is_denied_without_echoing_its_contents() {
+ use crate::security::AutonomyLevel;
+
+ let dir = tempfile::tempdir().unwrap();
+ let config = persisted_tier_config(dir.path(), true, AutonomyLevel::Full);
+ let canary = "private-config-canary-issue48";
+ std::fs::write(
+ &config.config_path,
+ format!("[autonomy\nlevel = \"{canary}\"\n"),
+ )
+ .unwrap();
+ let ctx = live_tier_context(&config);
+ let baseline =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ let error =
+ enforce_current_node_tier_gate(&ctx, &config, &baseline, CommandClass::Write, "code")
+ .await
+ .expect_err("malformed persisted policy must deny rather than reuse Full");
+ let message = match error {
+ EngineError::Capability(message) => message,
+ other => panic!("expected capability denial, got {other:?}"),
+ };
+ assert!(message.contains(POLICY_BLOCKED_MARKER));
+ assert!(!message.contains(canary), "config text leaked: {message}");
+}
+
+#[tokio::test]
+async fn captured_agent_and_config_fn_tiers_are_not_replaced_by_parent_file() {
+ use crate::security::AutonomyLevel;
+
+ let dir = tempfile::tempdir().unwrap();
+ let mut parent_file = persisted_tier_config(dir.path(), true, AutonomyLevel::Full);
+ save_tier_config(&parent_file).await;
+ let mut captured = parent_file.clone();
+ // This is the effective autonomy after AgentSpec's config_fn escape hatch;
+ // embed construction marks that final in-memory config as Captured.
+ captured.autonomy.level = AutonomyLevel::ReadOnly;
+ let parent = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(captured.workspace_dir.clone()),
+ );
+ let mut captured_overlay = crate::core::runtime::ContextOverlay::new(
+ captured.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::default(),
+ );
+ captured_overlay.autonomy_tier_source =
+ Some(crate::core::runtime::AutonomyTierSource::Captured);
+ let captured_ctx = crate::core::runtime::DispatchCtx::new(parent.derive_with(captured_overlay));
+ let captured_policy = SecurityPolicy::from_config(
+ &captured.autonomy,
+ &captured.workspace_dir,
+ &captured.action_dir,
+ );
+ assert!(
+ enforce_current_node_tier_gate(
+ &captured_ctx,
+ &captured,
+ &captured_policy,
+ CommandClass::Write,
+ "code"
+ )
+ .await
+ .is_err()
+ );
+
+ // A fixed ceiling contributes independently of a disabled file tier.
+ parent_file.autonomy.enabled = false;
+ parent_file.autonomy.level = AutonomyLevel::ReadOnly;
+ let mut capped_overlay = crate::core::runtime::ContextOverlay::new(
+ captured.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::default(),
+ );
+ capped_overlay.autonomy_tier_ceiling = Some(AutonomyLevel::Supervised);
+ let capped_ctx =
+ crate::core::runtime::DispatchCtx::new(parent.derive_with(capped_overlay.clone()));
+ let baseline = SecurityPolicy::from_config(
+ &captured.autonomy,
+ &captured.workspace_dir,
+ &captured.action_dir,
+ );
+ let effective =
+ tier_policy_from_config(&capped_ctx, &captured, Some(&parent_file), &baseline).unwrap();
+ assert_eq!(effective.autonomy, AutonomyLevel::Supervised);
+ assert_eq!(
+ effective.gate_decision(CommandClass::Write),
+ GateDecision::Prompt
+ );
+
+ capped_overlay.autonomy_tier_ceiling = Some(AutonomyLevel::Full);
+ let full_ceiling_ctx =
+ crate::core::runtime::DispatchCtx::new(parent.derive_with(capped_overlay));
+ let disabled_full_ceiling =
+ tier_policy_from_config(&full_ceiling_ctx, &captured, Some(&parent_file), &baseline)
+ .unwrap();
+ assert!(!disabled_full_ceiling.enabled);
+ assert_eq!(disabled_full_ceiling.autonomy, AutonomyLevel::Full);
+ assert_eq!(
+ disabled_full_ceiling.gate_decision(CommandClass::Write),
+ GateDecision::Allow,
+ "a disabled file tier must not contribute its stale ReadOnly level"
+ );
+
+ parent_file.autonomy.level = AutonomyLevel::Full;
+ let mut host_only_overlay = crate::core::runtime::ContextOverlay::new(
+ captured.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::default(),
+ );
+ host_only_overlay.autonomy_tier_ceiling = Some(AutonomyLevel::ReadOnly);
+ let host_only_ctx =
+ crate::core::runtime::DispatchCtx::new(parent.derive_with(host_only_overlay));
+ let host_only =
+ tier_policy_from_config(&host_only_ctx, &captured, Some(&parent_file), &baseline).unwrap();
+ assert_eq!(host_only.autonomy, AutonomyLevel::ReadOnly);
+ assert_eq!(
+ host_only.gate_decision(CommandClass::Write),
+ GateDecision::Block
+ );
+}
+
+#[tokio::test]
+async fn code_adapter_observes_file_backed_tier_changes_between_calls() {
+ use crate::config::AutonomyConfig;
+ use crate::security::{AutonomyLevel, SecurityPolicy};
+
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.config_path = dir.path().join("config.toml");
+ config.workspace_dir = dir.path().join("workspace");
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config.action_dir = dir.path().join("action-is-a-file");
+ std::fs::write(
+ &config.action_dir,
+ "blocks code staging after the tier gate",
+ )
+ .unwrap();
+ config.autonomy = AutonomyConfig {
+ enabled: true,
+ level: AutonomyLevel::Full,
+ ..AutonomyConfig::default()
+ };
+ config.save().await.unwrap();
+ let context = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(config.workspace_dir.clone()),
+ )
+ .derive_with(crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::default(),
+ ));
+
+ let code = OpenHumanCode {
+ ctx: crate::core::runtime::DispatchCtx::new(context),
+ security: Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ )),
+ config: Arc::new(config.clone()),
+ approval: Default::default(),
+ };
+
+ // Simulate Settings changing the same persisted config after the run has
+ // already captured Full. No global policy hooks or timing are involved.
+ let mut changed = config;
+ changed.autonomy.level = AutonomyLevel::ReadOnly;
+ changed.save().await.unwrap();
+
+ let err = code
+ .run(
+ tinyflows::caps::CodeLanguage::JavaScript,
+ "return 1;",
+ json!([]),
+ )
+ .await
+ .expect_err("the next call must observe the persisted ReadOnly tier");
+ assert!(
+ matches!(err, EngineError::Capability(ref message) if message.contains(POLICY_BLOCKED_MARKER)),
+ "tier downgrade must block before staging or execution; got {err:?}"
+ );
+}
+
+#[tokio::test]
+async fn native_adapter_uses_live_upgrade_for_filesystem_write() {
+ use crate::security::{AutonomyLevel, SecurityPolicy};
+
+ let dir = tempfile::tempdir().unwrap();
+ let captured = persisted_tier_config(dir.path(), true, AutonomyLevel::ReadOnly);
+ save_tier_config(&captured).await;
+ let mut live = captured.clone();
+ live.autonomy.level = AutonomyLevel::Full;
+ save_tier_config(&live).await;
+
+ let tools = OpenHumanTools {
+ ctx: live_tier_context(&captured),
+ config: Arc::new(captured.clone()),
+ security: Arc::new(SecurityPolicy::from_config(
+ &captured.autonomy,
+ &captured.workspace_dir,
+ &captured.action_dir,
+ )),
+ approval: Default::default(),
+ };
+ tools
+ .invoke(
+ "oh:file_write",
+ json!({ "path": "tier-upgrade.txt", "content": "written" }),
+ None,
+ )
+ .await
+ .expect("live Full tier and downstream filesystem gate must allow the write");
+ assert_eq!(
+ std::fs::read_to_string(captured.action_dir.join("tier-upgrade.txt")).unwrap(),
+ "written"
+ );
+}
+
+#[tokio::test]
+async fn native_adapter_downgrade_blocks_a_write_on_the_same_capability() {
+ use crate::security::{AutonomyLevel, SecurityPolicy};
+
+ let dir = tempfile::tempdir().unwrap();
+ let mut captured = persisted_tier_config(dir.path(), true, AutonomyLevel::Full);
+ save_tier_config(&captured).await;
+ let ctx = live_tier_context(&captured);
+ let tools = OpenHumanTools {
+ ctx,
+ config: Arc::new(captured.clone()),
+ security: Arc::new(SecurityPolicy::from_config(
+ &captured.autonomy,
+ &captured.workspace_dir,
+ &captured.action_dir,
+ )),
+ approval: Default::default(),
+ };
+
+ tools
+ .invoke(
+ "oh:file_write",
+ json!({ "path": "tier-downgrade.txt", "content": "before" }),
+ None,
+ )
+ .await
+ .expect("Full permits the initial write");
+ let path = captured.action_dir.join("tier-downgrade.txt");
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "before");
+
+ captured.autonomy.level = AutonomyLevel::ReadOnly;
+ save_tier_config(&captured).await;
+ let error = tools
+ .invoke(
+ "oh:file_write",
+ json!({ "path": "tier-downgrade.txt", "content": "after" }),
+ None,
+ )
+ .await
+ .expect_err("the same long-lived capability must observe ReadOnly");
+ assert!(matches!(
+ error,
+ EngineError::Capability(ref message) if message.contains(POLICY_BLOCKED_MARKER)
+ ));
+ assert_eq!(
+ std::fs::read_to_string(path).unwrap(),
+ "before",
+ "the denied call must not modify the existing file"
+ );
+}
+
+#[tokio::test]
+async fn http_adapter_passes_its_live_upgrade_to_the_http_gate_without_egress() {
+ use crate::security::{AutonomyLevel, SecurityPolicy};
+
+ let dir = tempfile::tempdir().unwrap();
+ let captured = persisted_tier_config(dir.path(), true, AutonomyLevel::ReadOnly);
+ save_tier_config(&captured).await;
+ let mut live = captured.clone();
+ live.autonomy.level = AutonomyLevel::Full;
+ save_tier_config(&live).await;
+ let http = OpenHumanHttp {
+ ctx: live_tier_context(&captured),
+ config: Arc::new(captured.clone()),
+ security: Arc::new(SecurityPolicy::from_config(
+ &captured.autonomy,
+ &captured.workspace_dir,
+ &captured.action_dir,
+ )),
+ http_config: HttpRequestConfig {
+ allowed_domains: vec!["example.com".to_string()],
+ ..Default::default()
+ },
+ http_creds: Arc::new(HttpCredentialsStore::from_config(&captured)),
+ approval: Default::default(),
+ };
+
+ // The URL is syntactically invalid, so the inner HTTP tool rejects it
+ // before DNS or network access. Reaching that validation proves its
+ // NetGate received the same live Full policy as the outer tier decision.
+ let error = http
+ .request(json!({ "method": "GET", "url": "not-a-url" }), None)
+ .await
+ .expect_err("invalid URL must fail before network access");
+ let message = match error {
+ EngineError::Capability(message) => message,
+ other => panic!("expected capability error, got {other:?}"),
+ };
+ assert_eq!(
+ message, "Only http:// and https:// URLs are allowed",
+ "the refreshed policy must pass the inner NetGate and reach URL validation"
+ );
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/prompt.rs b/crates/openhuman-core/src/flows/tinyflows/caps/prompt.rs
index e69de29bb2..f67b0b08d4 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/prompt.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/prompt.rs
@@ -0,0 +1,78 @@
+//! Turning a node's request into a completion, and a completion back into a
+//! node result.
+//!
+//! The pure request/reply handling (the `input_context` carrier, structured
+//! output steering, tolerant JSON extraction) lives in
+//! `tinyflows::nodes::integration::agent_prompt`; this file keeps the host
+//! mapping of its neutral messages onto [`TranscriptMessage`], usage projection and
+//! model pinning.
+
+#![allow(unused_imports)]
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::Config;
+use crate::inference::provider::{BilledUsage, is_raw_passthrough_model};
+use tinyagents_session::transcript::TranscriptMessage;
+use tinyflows::nodes::integration::agent_prompt;
+
+/// [`agent_prompt::build_completion_messages`] mapped onto the host's
+/// [`TranscriptMessage`] type.
+pub(crate) fn build_completion_messages(request: &Value) -> Vec<TranscriptMessage> {
+ agent_prompt::build_completion_messages(request)
+ .into_iter()
+ .map(|m| match m.role {
+ "system" => TranscriptMessage::system(m.content),
+ "assistant" => TranscriptMessage::assistant(m.content),
+ "tool" => TranscriptMessage::tool(m.content),
+ _ => TranscriptMessage::user(m.content),
+ })
+ .collect()
+}
+
+/// Maps a `BilledUsage` (not `Serialize`) into a JSON value field-by-field, so
+/// [`OpenHumanLlm::complete`] can surface it in its response `Value` without
+/// requiring an upstream `Serialize` impl change.
+pub(crate) fn usage_to_json(usage: &Option<BilledUsage>) -> Value {
+ match usage {
+ None => Value::Null,
+ Some(u) => json!({
+ "input_tokens": u.input_tokens,
+ "output_tokens": u.output_tokens,
+ "context_window": u.context_window(),
+ "cached_input_tokens": u.cached_input_tokens(),
+ "cache_creation_tokens": u.cache_creation_tokens,
+ "reasoning_tokens": u.reasoning_tokens,
+ "charged_amount_usd": u.charged_amount_usd,
+ }),
+ }
+}
+
+pub(crate) fn model_response_to_completion_value(
+ response: &tinyinference_llm::model::ModelResponse,
+) -> Value {
+ json!({
+ "text": response.text(),
+ "tool_calls": response
+ .tool_calls()
+ .iter()
+ .map(crate::agent::tinyagents::ta_call_to_oh_call)
+ .collect::<Vec<_>>(),
+ "usage": usage_to_json(
+ &crate::agent::tinyagents::model::usage_info_from_response(response)
+ ),
+ "reasoning_content": tinyagents_runtime::transcript::reasoning_from_content(
+ &response.message.content
+ ),
+ })
+}
+
+#[cfg(test)]
+#[path = "prompt_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/resolver.rs b/crates/openhuman-core/src/flows/tinyflows/caps/resolver.rs
index e69de29bb2..35bd09d23e 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/resolver.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/resolver.rs
@@ -0,0 +1,77 @@
+//! The `WorkflowResolver` capability — resolving a `sub_workflow` node's id.
+//!
+//! The engine knows a workflow id; only the host knows where workflows live.
+
+#![allow(unused_imports)]
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::*;
+use tinyflows::error::{EngineError, Result};
+
+use super::*;
+use crate::config::Config;
+use crate::flows;
+use tinyflows::model::WorkflowGraph;
+
+/// [`WorkflowResolver`] adapter over the `flows::` domain's saved-flow store.
+///
+/// A `sub_workflow` node that references a child by `workflow_id` (rather than
+/// embedding it inline) resolves through this adapter: the id is a saved flow's
+/// id, and [`flows::ops::load_engine_compatible_flow_graph`] loads that flow's portable
+/// [`WorkflowGraph`] from the SQLite store. An unknown id maps to
+/// [`EngineError::Capability`], so the referencing node fails with a clear "no
+/// such workflow" error rather than silently no-op'ing.
+///
+/// The engine bounds recursion (its `MAX_SUB_WORKFLOW_DEPTH` depth counter) and
+/// rejects direct self-references before a child runs, so this adapter does not
+/// itself need cycle detection — it is a pure id → graph lookup.
+pub struct OpenHumanWorkflowResolver {
+ pub config: Arc<Config>,
+}
+
+#[async_trait]
+impl WorkflowResolver for OpenHumanWorkflowResolver {
+ async fn resolve(&self, workflow_id: &str) -> Result<WorkflowGraph> {
+ tracing::debug!(
+ target: "flows",
+ %workflow_id,
+ "[flows] sub_workflow resolver: resolving workflow_id to a saved flow graph"
+ );
+ let loaded = flows::ops::load_engine_compatible_flow_graph(&self.config, workflow_id).await;
+ match loaded {
+ Ok(Some(graph)) => {
+ tracing::debug!(
+ target: "flows",
+ %workflow_id,
+ node_count = graph.nodes.len(),
+ "[flows] sub_workflow resolver: resolved saved flow graph"
+ );
+ Ok(graph)
+ }
+ Ok(None) => {
+ tracing::warn!(
+ target: "flows",
+ %workflow_id,
+ "[flows] sub_workflow resolver: no saved flow with that workflow_id"
+ );
+ Err(EngineError::Capability(format!(
+ "sub_workflow: no saved flow found for workflow_id '{workflow_id}'"
+ )))
+ }
+ Err(e) => {
+ tracing::error!(
+ target: "flows",
+ %workflow_id,
+ error = %e,
+ "[flows] sub_workflow resolver: failed to load saved flow graph"
+ );
+ Err(EngineError::Capability(format!(
+ "sub_workflow: failed to load workflow_id '{workflow_id}': {e}"
+ )))
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs b/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs
index e69de29bb2..31f52bb4da 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs
@@ -0,0 +1,116 @@
+//! Thin TinyFlows registration and error adapter for native OpenHuman tools.
+
+use async_trait::async_trait;
+use serde_json::Value;
+use tinybox_bus::CommandClass;
+use tinyflows::error::{EngineError, Result};
+
+use super::{NATIVE_TOOL_PREFIX, ToolBackend, ToolCallCtx};
+
+pub(crate) struct NativeToolBackend;
+
+#[async_trait]
+impl ToolBackend for NativeToolBackend {
+ fn name(&self) -> &'static str {
+ "native"
+ }
+
+ fn prefix(&self) -> &'static str {
+ NATIVE_TOOL_PREFIX
+ }
+
+ async fn invoke(
+ &self,
+ ctx: &ToolCallCtx<'_>,
+ slug: &str,
+ args: Value,
+ _conn: Option<&str>,
+ ) -> Result<Value> {
+ crate::tools::native_ops::flow_backend::invoke(
+ ctx.config,
+ slug,
+ args,
+ &NativeFlowPolicyHooks { ctx },
+ )
+ .await
+ .map_err(EngineError::Capability)
+ }
+}
+
+struct NativeFlowPolicyHooks<'a, 'ctx> {
+ ctx: &'a ToolCallCtx<'ctx>,
+}
+
+#[async_trait]
+impl crate::tools::native_ops::flow_backend::FlowPolicyHooks for NativeFlowPolicyHooks<'_, '_> {
+ async fn resolve_policy(
+ &self,
+ config: &crate::config::Config,
+ ) -> std::result::Result<std::sync::Arc<crate::security::SecurityPolicy>, String> {
+ super::super::current_tier_policy(self.ctx.dispatch, config, self.ctx.security)
+ .await
+ .map(std::sync::Arc::new)
+ .map_err(|error| match error {
+ EngineError::Capability(body) => body,
+ other => other.to_string(),
+ })
+ }
+
+ async fn authorize(
+ &self,
+ policy: &crate::security::SecurityPolicy,
+ class: CommandClass,
+ tool_name: &str,
+ args: &Value,
+ ) -> std::result::Result<Option<String>, String> {
+ let tier_decision = super::super::enforce_node_tier_gate(policy, class, "tool_call")
+ .map_err(|error| match error {
+ EngineError::Capability(body) => body,
+ other => other.to_string(),
+ })?;
+ let summary = crate::security::approval::summarize_action(tool_name, args);
+ let redacted = crate::security::approval::redact_args(args);
+ let (outcome, audit_id) = super::super::gate_call_for_tier(
+ self.ctx.dispatch,
+ self.ctx.approval,
+ tier_decision,
+ tool_name,
+ &summary,
+ redacted,
+ )
+ .await;
+ match outcome {
+ crate::security::approval::GateOutcome::Deny { reason } => Err(reason),
+ crate::security::approval::GateOutcome::Allow => Ok(audit_id),
+ }
+ }
+
+ fn record_execution(
+ &self,
+ audit_id: Option<&str>,
+ result: &std::result::Result<Value, String>,
+ ) {
+ let Some(id) = audit_id else {
+ return;
+ };
+ let Some(gate) = crate::security::approval::ApprovalGate::try_global() else {
+ return;
+ };
+ let execution = if result.is_ok() {
+ crate::security::approval::ExecutionOutcome::Success
+ } else {
+ crate::security::approval::ExecutionOutcome::Failure
+ };
+ let error = result
+ .as_ref()
+ .err()
+ .map(|body| EngineError::Capability(body.clone()).to_string());
+ tracing::debug!(
+ target: "flows",
+ audit_id = %id,
+ success = result.is_ok(),
+ "[flows] recording native tool execution outcome on the approval audit trail"
+ );
+ gate.record_execution(id, execution, error.as_deref());
+ }
+}
diff --git a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
index e69de29bb2..e3670167e5 100644
--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
@@ -0,0 +1,508 @@
+//! `OpenHumanMemory`: the host adapter backing the tinyflows `memory` node's
+//! `tinyflows::caps::MemoryProvider` capability, over memory v2.
+//!
+//! **No new permission path.** Every operation routes through the same
+//! [`enforce_node_tier_gate`] / [`gate_call_for_tier`] pair every other acting
+//! adapter in [`super::caps`] uses — `CommandClass::Read` for `recall`/
+//! `search`/`flavour`/`people`, `CommandClass::Write` for `remember`/`forget`.
+//!
+//! **Scopes map onto tag filters.** `scope: "user"` reads the whole store
+//! (no filter); `scope: "flow"` reads the running flow's own items
+//! ([`crate::flows::flow_filter`], tag `flow:<id>`); `scope: "flows"` reads
+//! every flow's items ([`crate::flows::cross_flow_filter`], tag `flows`).
+//! `recall` asks the engine for a synthesised answer with citations
+//! (`memory::ops::recall`); `search` returns raw ranked hits
+//! (`memory::ops::fetch`). These are the same tags `flow_memory_recall`/
+//! `flow_memory_remember` and the post-run digest use, so all three read and
+//! write one consistent slice of memory.
+//!
+//! **Keys.** `remember(key, value)` stores a learning tagged
+//! [`crate::flows::flow_meta`] plus the per-key tag, replacing an earlier
+//! value under the same key ([`crate::flows::remember_keyed`]); `forget(key)`
+//! forgets by that per-key tag filter. Forgetting an absent key forgets
+//! nothing and is not an error.
+//!
+//! **`flavour` and `people`.** Memory v2 has neither flavoured profiles nor a
+//! people store: `flavour` reports every slug as unknown (the trait's error
+//! case) and `people` returns an empty listing marked `supported: false`.
+//!
+//! **Defense-in-depth on writes.** The engine's own `validate_all` already
+//! rejects `remember`/`forget` nodes authored with `scope: "user"` before a
+//! run starts; this adapter separately hard-refuses anything other than
+//! `scope: "flow"`, and takes the flow id only from the run's trusted origin.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{Value, json};
+use tinyflows::caps::MemoryProvider;
+use tinyflows::error::{EngineError, Result};
+
+#[cfg(test)]
+use crate::agent::turn_origin;
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
+use crate::config::Config;
+use crate::flows::{
+ FLOWS_TAG, cross_flow_filter, flow_filter, flow_key_of, flow_key_tag, forget_matching,
+ remember_keyed,
+};
+use crate::memory::MemoryError;
+use crate::memory::types::{FetchParams, RecallParams};
+use crate::security::SecurityPolicy;
+use crate::security::approval::{
+ ApprovalGate, ExecutionOutcome, GateOutcome, redact_args, summarize_action,
+};
+use tinybox_bus::CommandClass;
+use tinymemory_api::wrap_untrusted_for_agent;
+use tinymemory_api::{Hit, LearningKind, MemoryMeta, MetaFilter, SourceKind};
+
+use super::caps::{enforce_current_node_tier_gate, gate_call_for_tier};
+
+/// Stable `tracing` grep prefix for every log line this adapter emits. Never
+/// logs memory *content* or PII — only operation names, scopes, resolved
+/// namespaces, tier-gate decisions, hit/miss, and result sizes.
+const LOG_PREFIX: &str = "[memory-node-host]";
+
+/// Host-injected memory access for `memory` nodes. See the module doc for the
+/// security contract; see [`super::caps::OpenHumanAgentRunner`] for the
+/// sibling adapter this one's tier-gate wiring mirrors.
+pub struct OpenHumanMemory {
+ /// The context the run acts under; carries the run's trusted turn origin.
+ pub(crate) ctx: crate::core::runtime::DispatchCtx,
+ pub(crate) config: Arc<Config>,
+ pub(crate) security: Arc<SecurityPolicy>,
+ /// The run's approval context (flow run correlation).
+ pub(crate) approval: crate::security::approval::ApprovalTurnContext,
+}
+
+impl OpenHumanMemory {
+ /// The running flow's own id, from the run's trusted
+ /// `TrustedAutomation { Workflow }` turn origin — the ONLY authoritative
+ /// source. Mirrors `flows::memory_tools::trusted_flow_id`'s security
+ /// invariant exactly: this adapter's `scope` argument is a fixed
+ /// three-value enum (never a caller-supplied namespace string), but the
+ /// *flow id* half of the namespace must still come from the trusted run
+ /// context, not be re-derivable from anything model- or config-supplied,
+ /// so a `scope: "flow"` node can never be pointed at another flow's
+ /// namespace by a crafted `=`-binding.
+ fn trusted_flow_id(&self) -> Result<String> {
+ match self.ctx.turn_origin() {
+ Some(AgentTurnOrigin::TrustedAutomation {
+ job_id,
+ source: TrustedAutomationSource::Workflow { .. },
+ }) => Ok(job_id),
+ _ => Err(EngineError::Capability(
+ "memory node: scope \"flow\"/\"flows\" requires the node to run inside a saved \
+ flow's own run (no trusted Workflow-scoped origin found)"
+ .to_string(),
+ )),
+ }
+ }
+
+ /// The tag filter a read in `scope` applies; `None` reads everything.
+ fn scope_filter(&self, scope: &str) -> Result<Option<MetaFilter>> {
+ match scope {
+ "user" => Ok(None),
+ "flow" => self.trusted_flow_id().map(|id| Some(flow_filter(&id))),
+ "flows" => Ok(Some(cross_flow_filter())),
+ other => Err(EngineError::Capability(format!(
+ "memory node: unknown scope \"{other}\" (expected \"user\", \"flow\", or \"flows\")"
+ ))),
+ }
+ }
+
+ /// Read-side tier gate: `CommandClass::Read` is `Allow` at every autonomy
+ /// tier (`SecurityPolicy::gate_decision`), so this can only ever succeed
+ /// or `Block` outright (`ReadOnly`/`Supervised`/`Full` all `Allow` Read).
+ /// Still routed through [`enforce_node_tier_gate`] — rather than skipped
+ /// — so the tier-gate debug log line and the `Block` floor stay uniform
+ /// across every acting/reading adapter in this module. No
+ /// [`gate_call_for_tier`] round-trip: unlike `remember`/`forget`, a read
+ /// never needs the HITL escalation that function exists for, and — like
+ /// the curated-Read short-circuit in `OpenHumanTools::invoke` — routing
+ /// a guaranteed-`Allow` decision through `intercept_audited` anyway would
+ /// only reintroduce the "reads wait for approval" bug that short-circuit
+ /// was added to close.
+ async fn tier_gate_read(&self, op: &str) -> Result<()> {
+ enforce_current_node_tier_gate(
+ &self.ctx,
+ &self.config,
+ &self.security,
+ CommandClass::Read,
+ op,
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Write-side tier gate: `CommandClass::Write` is `Block` under
+ /// `ReadOnly` (returns `Err` from [`enforce_node_tier_gate`] before this
+ /// function is even entered — see call sites), `Prompt` under
+ /// `Supervised`, and `Allow` under `Full`. Unlike [`Self::tier_gate_read`]
+ /// this ALWAYS calls [`gate_call_for_tier`] — never short-circuits on
+ /// `Allow` — because a `Full`-tier run can still have the *flow's own*
+ /// `require_approval: true` toggle set, and only `intercept_audited`
+ /// (reached via `gate_call_for_tier`) consults that. Mirrors
+ /// `OpenHumanCode::run`'s gating exactly.
+ ///
+ /// Returns the approval audit request id (`None` when no
+ /// [`ApprovalGate`] is installed, or the tier decision never went
+ /// through a `Prompt` round-trip). Callers MUST thread it into
+ /// [`Self::record_write_execution`] once the actual write resolves —
+ /// see that function's doc for why (E-m1).
+ async fn tier_gate_write(&self, op: &str, action: &Value) -> Result<Option<String>> {
+ let tool_name = format!("flows_memory_{op}");
+ let tier_decision = enforce_current_node_tier_gate(
+ &self.ctx,
+ &self.config,
+ &self.security,
+ CommandClass::Write,
+ op,
+ )
+ .await?;
+ let summary = summarize_action(&tool_name, action);
+ let redacted = redact_args(action);
+ let (outcome, audit_id) = gate_call_for_tier(
+ &self.ctx,
+ &self.approval,
+ tier_decision,
+ &tool_name,
+ &summary,
+ redacted,
+ )
+ .await;
+ if let GateOutcome::Deny { reason } = outcome {
+ tracing::warn!(target: "flows", op, "{LOG_PREFIX} write: approval gate denied");
+ return Err(EngineError::Capability(reason));
+ }
+ Ok(audit_id)
+ }
+
+ /// Closes out the approval audit row opened by [`Self::tier_gate_write`]
+ /// (E-m1): unlike the http/code/Composio node paths, this used to
+ /// discard the request id (`_audit_id`) and never call
+ /// `record_execution`, so an approved `remember`/`forget` left its audit
+ /// row stuck open with no terminal Success/Failure outcome. A no-op when
+ /// `audit_id` is `None` (no gate installed, or the decision never
+ /// prompted). Takes `success`/`error` rather than a `Result` so callers
+ /// don't need `EngineError: Clone` to both record the outcome and
+ /// propagate the original error.
+ fn record_write_execution(
+ op: &str,
+ audit_id: Option<&str>,
+ success: bool,
+ error: Option<&str>,
+ ) {
+ let Some(id) = audit_id else { return };
+ let Some(gate) = ApprovalGate::try_global() else {
+ return;
+ };
+ let exec = if success {
+ ExecutionOutcome::Success
+ } else {
+ ExecutionOutcome::Failure
+ };
+ tracing::debug!(
+ target: "flows",
+ op,
+ audit_id = %id,
+ success,
+ "{LOG_PREFIX} write: recording execution outcome on the approval audit trail"
+ );
+ gate.record_execution(id, exec, error);
+ }
+
+ /// Shapes one result row. Text that did not come from a plain agent
+ /// learning (a synced source, a conversation, or any flow's own
+ /// automation output) passes through [`wrap_untrusted_for_agent`], so it
+ /// reaches downstream `agent`/`condition` bindings marked as data.
+ fn shape_row(id: &str, text: &str, meta: &MemoryMeta, score: Option<f32>) -> Value {
+ let text = if is_untrusted(meta) {
+ wrap_untrusted_for_agent(text, meta.source.kind.as_str())
+ } else {
+ text.to_string()
+ };
+ json!({
+ "id": id,
+ "key": flow_key_of(meta),
+ "text": text,
+ "score": score,
+ "source": meta.source.kind.as_str(),
+ })
+ }
+}
+
+/// Whether an item's text must be marked untrusted before it reaches an
+/// agent: anything but a plain (non-flow) agent learning.
+fn is_untrusted(meta: &MemoryMeta) -> bool {
+ meta.source.kind != SourceKind::Agent || meta.tags.iter().any(|tag| tag == FLOWS_TAG)
+}
+
+/// Maps a memory failure onto the node's capability error.
+fn capability_error(op: &str, error: &MemoryError) -> EngineError {
+ EngineError::Capability(format!("memory node: {op} failed: {error}"))
+}
+
+#[async_trait]
+impl MemoryProvider for OpenHumanMemory {
+ /// Backs both `recall` and `search`. `recall` returns the engine's
+ /// synthesised `answer` plus its citations as `results`; `search` returns
+ /// raw ranked hits as `results`. Each row is `{ id, key, text, score,
+ /// source }`; rows under the node's `min_score` are dropped.
+ async fn recall(&self, scope: &str, query: &str, opts: Value) -> Result<Value> {
+ let operation: &str = opts
+ .get("operation")
+ .and_then(Value::as_str)
+ .unwrap_or("recall");
+ #[allow(clippy::cast_possible_truncation)]
+ let limit = opts
+ .get("limit")
+ .and_then(Value::as_u64)
+ .map_or(5, |v| v as usize);
+ let min_score = opts.get("min_score").and_then(Value::as_f64);
+
+ tracing::debug!(
+ target: "flows",
+ operation,
+ scope,
+ query_chars = query.chars().count(),
+ limit,
+ ?min_score,
+ "{LOG_PREFIX} recall: entry"
+ );
+
+ self.tier_gate_read(operation).await?;
+ let filter = self.scope_filter(scope)?;
+
+ let (answer, results): (Option<String>, Vec<Value>) = if operation == "search" {
+ let page = crate::memory::ops::fetch(
+ &self.config,
+ FetchParams {
+ refers_to: None,
+ query: query.to_string(),
+ mode: None,
+ filter,
+ limit: Some(limit),
+ cursor: None,
+ },
+ )
+ .await
+ .map_err(|e| capability_error(operation, &e))?;
+ let rows = page
+ .hits
+ .iter()
+ .filter(|hit| passes_min_score(Some(hit.score), min_score))
+ .map(|hit: &Hit| Self::shape_row(&hit.id.0, &hit.text, &hit.meta, Some(hit.score)))
+ .collect();
+ (None, rows)
+ } else {
+ let view = crate::memory::ops::recall(
+ &self.config,
+ RecallParams {
+ refers_to: None,
+ question: query.to_string(),
+ filter,
+ limit: Some(limit),
+ },
+ )
+ .await
+ .map_err(|e| capability_error(operation, &e))?;
+ let rows = view
+ .citations
+ .iter()
+ .filter(|c| passes_min_score(c.score, min_score))
+ .map(|c| Self::shape_row(&c.id.0, &c.snippet, &c.meta, c.score))
+ .collect();
+ (Some(view.answer), rows)
+ };
+
+ tracing::debug!(
+ target: "flows",
+ operation,
+ scope,
+ hit_count = results.len(),
+ "{LOG_PREFIX} recall: engine returned"
+ );
+
+ let mut out = json!({ "scope": scope, "query": query, "results": results });
+ if let Some(answer) = answer {
+ out["answer"] = Value::String(answer);
+ }
+ Ok(out)
+ }
+
+ /// Memory v2 keeps no flavoured profiles, so every slug is unknown.
+ async fn flavour(&self, slug: &str) -> Result<Value> {
+ tracing::debug!(target: "flows", flavour = slug, "{LOG_PREFIX} flavour: unsupported");
+ self.tier_gate_read("flavour").await?;
+ Err(EngineError::Capability(format!(
+ "memory node: unknown flavour \"{slug}\" (this host's memory keeps no flavour profiles)"
+ )))
+ }
+
+ /// Memory v2 keeps no people store: an empty listing marked unsupported.
+ async fn people(&self, query: Option<&str>) -> Result<Value> {
+ tracing::debug!(
+ target: "flows",
+ has_query = query.is_some_and(|q| !q.trim().is_empty()),
+ "{LOG_PREFIX} people: unsupported, empty listing"
+ );
+ self.tier_gate_read("people").await?;
+ Ok(json!({ "people": [], "supported": false }))
+ }
+
+ /// Writes `value` under `key` into this flow's own memory — see the module doc's defense-in-depth note. Never
+ /// reachable for `scope != "flow"`, regardless of what the caller
+ /// passes: this is checked here independently of the engine's own
+ /// `validate_all` rejection of `scope: "user"` writes.
+ async fn remember(&self, scope: &str, key: &str, value: Value) -> Result<()> {
+ if scope != "flow" {
+ tracing::warn!(
+ target: "flows",
+ scope,
+ "{LOG_PREFIX} remember: REFUSED — scope must be \"flow\" (defense-in-depth; a \
+ remember/forget node targeting scope \"user\" is already a hard reject in \
+ tinyflows' own validate_all, but this adapter never trusts that alone)"
+ );
+ return Err(EngineError::Capability(format!(
+ "memory node: remember only supports scope \"flow\" (got \"{scope}\") — writing \
+ to the user's personal memory, or to the read-only \"flows\" scope, is never \
+ permitted from a memory node"
+ )));
+ }
+ let key = key.trim();
+ if key.is_empty() {
+ return Err(EngineError::Capability(
+ "memory node: remember requires a non-empty key".to_string(),
+ ));
+ }
+
+ // Secret check MUST run before the tier gate / HITL approval prompt
+ // below: `tier_gate_write` can park the run for human approval
+ // (`gate_call_for_tier`), and a likely-secret value must be refused
+ // up front rather than spend that approval round-trip on a write
+ // that was always going to be rejected (review fix — see #5227).
+ let content = value_to_content(&value);
+ if tinyredact::has_likely_secret(&content) {
+ tracing::warn!(
+ target: "flows",
+ key_chars = key.chars().count(),
+ content_chars = content.chars().count(),
+ "{LOG_PREFIX} remember: REFUSED — content looks like a secret"
+ );
+ return Err(EngineError::Capability(
+ "memory node: refusing to store content that looks like a secret".to_string(),
+ ));
+ }
+
+ let action = json!({ "operation": "remember", "scope": scope, "key": key });
+ let audit_id = self.tier_gate_write("remember", &action).await?;
+
+ let flow_id = self.trusted_flow_id()?;
+ let store_result =
+ remember_keyed(&self.config, &flow_id, key, &content, LearningKind::Fact)
+ .await
+ .map_err(|e| capability_error("remember", &e));
+ Self::record_write_execution(
+ "remember",
+ audit_id.as_deref(),
+ store_result.is_ok(),
+ store_result
+ .as_ref()
+ .err()
+ .map(ToString::to_string)
+ .as_deref(),
+ );
+ store_result?;
+
+ tracing::debug!(
+ target: "flows",
+ flow_id = %flow_id,
+ key_chars = key.chars().count(),
+ content_chars = content.chars().count(),
+ "{LOG_PREFIX} remember: stored"
+ );
+ Ok(())
+ }
+
+ /// Forgets this flow's value for `key` (by its per-key tag) — same
+ /// `scope`-lockdown as [`Self::remember`].
+ async fn forget(&self, scope: &str, key: &str) -> Result<()> {
+ if scope != "flow" {
+ tracing::warn!(
+ target: "flows",
+ scope,
+ "{LOG_PREFIX} forget: REFUSED — scope must be \"flow\" (defense-in-depth)"
+ );
+ return Err(EngineError::Capability(format!(
+ "memory node: forget only supports scope \"flow\" (got \"{scope}\") — the \
+ user's personal memory and the read-only \"flows\" scope are never reachable \
+ from a memory node"
+ )));
+ }
+ let key = key.trim();
+ if key.is_empty() {
+ return Err(EngineError::Capability(
+ "memory node: forget requires a non-empty key".to_string(),
+ ));
+ }
+
+ let action = json!({ "operation": "forget", "scope": scope, "key": key });
+ let audit_id = self.tier_gate_write("forget", &action).await?;
+
+ let flow_id = self.trusted_flow_id()?;
+ let filter = MetaFilter {
+ tags_any: vec![flow_key_tag(&flow_id, key)],
+ ..MetaFilter::default()
+ };
+ let forget_result = forget_matching(&self.config, filter)
+ .await
+ .map_err(|e| capability_error("forget", &e));
+ Self::record_write_execution(
+ "forget",
+ audit_id.as_deref(),
+ forget_result.is_ok(),
+ forget_result
+ .as_ref()
+ .err()
+ .map(ToString::to_string)
+ .as_deref(),
+ );
+ let removed = forget_result?;
+
+ tracing::debug!(
+ target: "flows",
+ flow_id = %flow_id,
+ key_chars = key.chars().count(),
+ removed,
+ "{LOG_PREFIX} forget: done"
+ );
+ Ok(())
+ }
+}
+
+/// Renders a `remember` node's `value` (arbitrary JSON — a plain string when
+/// the author wrote a literal, or any resolved `=`-expression result
+/// otherwise) into the learning text it is stored as.
+/// A JSON string is stored verbatim (not re-quoted); anything else is
+/// serialized to its compact JSON form so structured values round-trip
+/// losslessly through recall.
+fn value_to_content(value: &Value) -> String {
+ match value {
+ Value::String(s) => s.clone(),
+ other => other.to_string(),
+ }
+}
+
+/// Whether a row's score clears the node's optional `min_score`. A row the
+/// engine did not score passes.
+fn passes_min_score(score: Option<f32>, min_score: Option<f64>) -> bool {
+ match (score, min_score) {
+ (Some(score), Some(min)) => f64::from(score) >= min,
+ _ => true,
+ }
+}
+
+#[cfg(test)]
+#[path = "memory_adapter_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/tinyflows/observability_tests.rs b/crates/openhuman-core/src/flows/tinyflows/observability_tests.rs
index e69de29bb2..8cce1f390e 100644
--- a/crates/openhuman-core/src/flows/tinyflows/observability_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/observability_tests.rs
@@ -0,0 +1,52 @@
+use super::*;
+
+/// The canvas's `.flow-node-running` pulse is bound to a `running` status
+/// that only `on_step_start` can produce. Before it was implemented the
+/// socket carried nothing but `success`/`failed`, so the pulse was
+/// unreachable and the "live" overlay was really a completion trail.
+/// Assert the trait method is actually overridden — a default no-op here
+/// silently returns the UI to that state with every other test still green.
+#[test]
+fn on_step_start_is_implemented_so_the_running_status_can_reach_the_canvas() {
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ // A probe observer whose `on_step_start` records that the *trait's*
+ // dispatch reached an override rather than the blanket default.
+ struct Probe {
+ started: Arc<AtomicBool>,
+ }
+ impl RunObserver for Probe {
+ fn on_step_start(&self, _node_id: &str) {
+ self.started.store(true, Ordering::SeqCst);
+ }
+ }
+ let started = Arc::new(AtomicBool::new(false));
+ let probe: Box<dyn RunObserver> = Box::new(Probe {
+ started: started.clone(),
+ });
+ probe.on_step_start("n1");
+ assert!(
+ started.load(Ordering::SeqCst),
+ "the engine dispatches on_step_start through the trait object — if this ever \
+ stops holding, FlowRunObserver's override cannot fire either"
+ );
+
+ // And the real observer must override it, not inherit the no-op.
+ let src = include_str!("observability.rs");
+ assert!(
+ src.contains("fn on_step_start(&self, node_id: &str)"),
+ "FlowRunObserver must implement on_step_start — without it no `running` \
+ status is ever published and the canvas pulse is dead code"
+ );
+ assert!(
+ src.contains("status: \"running\".to_string()"),
+ "on_step_start must publish FlowRunProgress with status=running"
+ );
+}
+
+// The end-to-end proof that `FlowRunObserver::on_step_finish` persists each
+// step into the `flow_runs` row lives in `flows::ops_tests`
+// (`observer_persists_each_step_incrementally` and the run-driven
+// `flows_run_persists_live_steps_with_status_and_timing`), where the flows
+// `store` internals are in scope for seeding/asserting rows.
diff --git a/crates/openhuman-core/src/flows/tinyflows/tinyflows_capabilities_tests.rs b/crates/openhuman-core/src/flows/tinyflows/tinyflows_capabilities_tests.rs
index e69de29bb2..935abc8fe7 100644
--- a/crates/openhuman-core/src/flows/tinyflows/tinyflows_capabilities_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/tinyflows_capabilities_tests.rs
@@ -0,0 +1,460 @@
+use super::*;
+use crate::flows::agent_route::{
+ AgentRoute, harness_model_default_override, route_custom_entry_lookup, route_for_agent_ref,
+};
+use crate::flows::tinyflows::caps::OpenHumanCode;
+
+// ── build_capabilities smoke ────────────────────────────────────────────
+
+#[test]
+fn build_capabilities_constructs_every_slot_without_panicking() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let caps = build_capabilities(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ "test:build",
+ None,
+ );
+ assert!(caps.tasks.is_some(), "Tinyflows task nodes need a runner");
+ assert!(
+ caps.approvals.is_none(),
+ "OpenHuman resumes approvals through its existing flow-run surface"
+ );
+}
+
+#[tokio::test]
+async fn http_adapter_blocks_loopback_host_as_capability_error() {
+ let adapter = http_adapter(vec![]); // open allowlist mode
+ let err = adapter
+ .request(
+ json!({ "method": "GET", "url": "http://127.0.0.1:1/" }),
+ None,
+ )
+ .await
+ .expect_err("loopback host must be blocked by the SSRF guard");
+ let msg = err.to_string();
+ assert!(
+ msg.to_lowercase().contains("private") || msg.to_lowercase().contains("local"),
+ "expected an SSRF-guard message, got: {msg}"
+ );
+}
+
+#[tokio::test]
+async fn http_adapter_rejects_host_outside_strict_allowlist() {
+ let adapter = http_adapter(vec!["example.com".to_string()]);
+ let err = adapter
+ .request(
+ json!({ "method": "GET", "url": "https://not-allowed.test/" }),
+ None,
+ )
+ .await
+ .expect_err("host outside the strict allowlist must be rejected");
+ assert!(
+ err.to_string().contains("not-allowed.test")
+ || err.to_string().to_lowercase().contains("allowed"),
+ "expected an allowlist rejection message, got: {err}"
+ );
+}
+
+// ── Engine smoke: real seam end to end ───────────────────────────────────
+
+#[tokio::test]
+async fn engine_run_drives_trigger_to_http_request_through_the_real_seam() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let caps = build_capabilities(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ "test:smoke",
+ None,
+ );
+
+ // A deterministically-blocked loopback URL with `on_error: continue` so
+ // the run completes even though the (real, SSRF-guarded) HTTP adapter
+ // necessarily rejects it — see the module doc for why a real network
+ // round-trip isn't testable here.
+ let graph = WorkflowGraph {
+ nodes: vec![
+ node("t", NodeKind::Trigger, serde_json::Value::Null),
+ node(
+ "http",
+ NodeKind::HttpRequest,
+ json!({ "method": "GET", "url": "http://127.0.0.1:1/", "on_error": "continue" }),
+ ),
+ ],
+ edges: vec![edge("t", "http")],
+ ..Default::default()
+ };
+ let compiled = tinyflows::compiler::compile(&graph).expect("compile");
+
+ let outcome = tinyflows::engine::run(&compiled, json!({ "seed": 1 }), &caps)
+ .await
+ .expect("run should complete (on_error: continue)");
+
+ assert!(outcome.pending_approvals.is_empty());
+ assert_eq!(
+ outcome.output["nodes"]["http"]["items"][0]["json"]["error"]["node"],
+ json!("http")
+ );
+}
+
+// ── Code adapter ──────────────────────────────────────────────────────────
+
+/// Requires `node` on `PATH` (the code node runs the host's Node under the
+/// sandbox). TinyBox's native backend only provides the required isolation on
+/// Linux; macOS Seatbelt and other fallback backends deliberately do not meet
+/// the untrusted-code floor.
+#[cfg(target_os = "linux")]
+#[tokio::test]
+async fn code_adapter_javascript_runs_when_isolated_and_refuses_when_isolation_is_unavailable() {
+ if std::process::Command::new("node")
+ .arg("--version")
+ .output()
+ .is_err()
+ {
+ eprintln!("SKIPPED (not run, not asserted): no `node` binary on PATH");
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let runner = OpenHumanCode {
+ ctx: crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ security,
+ approval: Default::default(),
+ };
+
+ let input = json!([{ "json": { "n": 7 } }]);
+ match runner
+ .run(CodeLanguage::JavaScript, "return input;", input.clone())
+ .await
+ {
+ Ok(result) => assert_eq!(result, input),
+ Err(error) => assert!(
+ error
+ .to_string()
+ .contains("TinyBox native jail cannot meet the required isolation floor"),
+ "unexpected JavaScript code-runner failure: {error}"
+ ),
+ }
+}
+
+#[tokio::test]
+async fn tools_invoke_rejects_a_non_curated_slug_for_a_known_toolkit() {
+ let tmp = TempDir::new().unwrap();
+ let tools = tools_adapter(test_config(&tmp));
+
+ // "gmail" has a curated catalog; this action is not in it, so curation
+ // must reject regardless of the user's read/write/admin scope prefs.
+ let err = tools
+ .invoke("GMAIL_NOT_A_REAL_CURATED_ACTION", json!({}), None)
+ .await
+ .expect_err("a non-curated action for a curated toolkit must be rejected");
+ let msg = err.to_string();
+ assert!(
+ msg.contains("tool not permitted"),
+ "expected a curation rejection message, got: {msg}"
+ );
+ assert!(msg.contains("GMAIL_NOT_A_REAL_CURATED_ACTION"));
+}
+
+#[tokio::test]
+async fn tools_invoke_rejects_an_unrecognized_toolkit_slug() {
+ // Issue B2 finding #2 (deny-by-default): a made-up toolkit prefix that
+ // isn't in any curated catalog must be rejected — not passed through on
+ // a permissive "unknown toolkit" heuristic. Live testing confirmed this
+ // used to reach Composio (and only failed there for lack of a signed-in
+ // session), which is not a hard allowlist.
+ let tmp = TempDir::new().unwrap();
+ let tools = tools_adapter(test_config(&tmp));
+
+ let err = tools
+ .invoke("madeupkit_dostuff", json!({}), None)
+ .await
+ .expect_err("an unrecognized toolkit slug must be rejected by curation");
+ let msg = err.to_string();
+ assert!(
+ msg.contains("tool not permitted"),
+ "expected a curation rejection message, got: {msg}"
+ );
+ assert!(msg.contains("madeupkit_dostuff"));
+}
+
+#[tokio::test]
+async fn tools_invoke_rejects_a_prefix_less_slug() {
+ // "noop" has no curated catalog (`catalog_for_toolkit` returns `None`
+ // for the single-segment "toolkit" `toolkit_from_slug` degrades it to),
+ // so the hard allowlist in `is_curated_flow_tool` rejects it outright —
+ // unlike the general agent tool-call path's `is_action_visible_with_pref`,
+ // which falls back to the permissive `classify_unknown` heuristic and
+ // would let this slug through.
+ let tmp = TempDir::new().unwrap();
+ let tools = tools_adapter(test_config(&tmp));
+
+ let err = tools
+ .invoke("noop", json!({}), None)
+ .await
+ .expect_err("a prefix-less/unrecognized slug must be rejected by curation");
+ assert!(
+ err.to_string().contains("tool not permitted"),
+ "expected a curation rejection message, got: {err}"
+ );
+}
+
+#[tokio::test]
+async fn tools_invoke_does_not_reject_a_known_curated_slug_at_the_curation_gate() {
+ // A real curated action for a known toolkit must clear the curation
+ // gate — it may still fail further downstream (no composio client
+ // configured in this test environment), but that failure must NOT be
+ // the "tool not permitted" curation-rejection message.
+ let tmp = TempDir::new().unwrap();
+ let tools = tools_adapter(test_config(&tmp));
+
+ let err = tools
+ .invoke("GMAIL_SEND_EMAIL", json!({}), None)
+ .await
+ .expect_err("no composio client is configured in the test environment");
+ assert!(
+ !err.to_string().contains("tool not permitted"),
+ "a known curated slug must not be rejected by curation, got: {err}"
+ );
+}
+
+#[test]
+fn composio_connection_id_parses_toolkit_prefixed_ref() {
+ assert_eq!(
+ super::super::caps::composio_connection_id("composio:slack:acct_123"),
+ Some("acct_123")
+ );
+ // Trailing segment only — works even without a toolkit segment present.
+ assert_eq!(
+ super::super::caps::composio_connection_id("composio::acct_1"),
+ Some("acct_1")
+ );
+}
+
+#[test]
+fn composio_connection_id_returns_none_for_non_composio_ref_or_empty_id() {
+ assert_eq!(
+ super::super::caps::composio_connection_id("http_cred:my-secret"),
+ None
+ );
+ assert_eq!(
+ super::super::caps::composio_connection_id("composio:"),
+ None
+ );
+ assert_eq!(
+ super::super::caps::composio_connection_id("composio:slack:"),
+ None
+ );
+}
+
+#[test]
+fn http_cred_name_parses_and_trims() {
+ assert_eq!(
+ super::super::caps::http_cred_name("http_cred:my-secret"),
+ Some("my-secret")
+ );
+ assert_eq!(
+ super::super::caps::http_cred_name("http_cred: spaced "),
+ Some("spaced")
+ );
+}
+
+#[test]
+fn http_cred_name_returns_none_for_non_http_cred_ref_or_empty_name() {
+ assert_eq!(
+ super::super::caps::http_cred_name("composio:slack:acct_1"),
+ None
+ );
+ assert_eq!(super::super::caps::http_cred_name("http_cred:"), None);
+}
+
+// ── structured agent output (parse_llm_json) ────────────────────────────
+
+#[tokio::test]
+async fn preflight_invoker_gates_the_mock_tool_path() {
+ use tinyflows::caps::ToolInvoker as _;
+
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ // Own toolkit/slug (never `"gmail"`) — Composio cache tests share a
+ // process-global catalog, so this adapter test uses a distinct key from
+ // the owner-side preflight tests as well as other flow tests.
+ crate::integrations::composio::catalog::seed_live_catalog_cache(
+ "preflightgatetest",
+ vec![seeded_required_args_contract(
+ "PREFLIGHTGATETEST_SEND_EMAIL",
+ "preflightgatetest",
+ &["to"],
+ )],
+ );
+
+ let mock = tinyflows::caps::mock::mock_capabilities();
+ let invoker = super::super::caps::PreflightToolInvoker {
+ config,
+ inner: mock.tools.clone(),
+ };
+
+ // Unwired required arg: fails with the named field even though the inner
+ // mock would echo anything.
+ let err = invoker
+ .invoke("PREFLIGHTGATETEST_SEND_EMAIL", json!({ "to": null }), None)
+ .await
+ .expect_err("dry-run preflight must catch the unwired arg");
+ assert!(err.to_string().contains("`to`"));
+
+ // Wired arg: delegates to the mock echo.
+ let ok = invoker
+ .invoke(
+ "PREFLIGHTGATETEST_SEND_EMAIL",
+ json!({ "to": "[email protected]" }),
+ None,
+ )
+ .await
+ .expect("wired arg passes through to the mock");
+ assert_eq!(ok["tool"], "PREFLIGHTGATETEST_SEND_EMAIL");
+
+ // Native `oh:` slugs bypass the Composio preflight (no Composio schema).
+ // The mock echoes them unchecked.
+ let ok = invoker
+ .invoke("oh:web_search", json!({}), None)
+ .await
+ .expect("native slug bypasses composio preflight");
+ assert_eq!(ok["tool"], "oh:web_search");
+}
+
+#[test]
+fn harness_model_default_override_normalises_tiers_to_hint_roles() {
+ // Bare managed tiers → the `hint:<role>` form the session builder routes on
+ // (a bare tier would otherwise fall through to the chat workload).
+ assert_eq!(
+ harness_model_default_override("reasoning-v1"),
+ "hint:reasoning"
+ );
+ assert_eq!(harness_model_default_override("chat-v1"), "hint:chat");
+ // `hint:*` aliases pass through their role.
+ assert_eq!(
+ harness_model_default_override("hint:reasoning"),
+ "hint:reasoning"
+ );
+}
+
+#[test]
+fn harness_model_default_override_forwards_raw_byok_models_verbatim() {
+ // Raw/BYOK ids a user pins on an agent node are forwarded verbatim (issue
+ // #4598) — normalising them to `hint:chat` would collapse the explicit
+ // per-node model onto the managed chat tier. They reach the harness `chat`
+ // role, which inherits `config.default_model`, and `make_openhuman_backend`
+ // forwards the non-tier id to the backend unchanged.
+ assert_eq!(
+ harness_model_default_override("claude-opus-4"),
+ "claude-opus-4"
+ );
+ assert_eq!(
+ harness_model_default_override("openai:gpt-4o"),
+ "openai:gpt-4o"
+ );
+ // Empty / whitespace is not a raw id — falls back to the chat workload.
+ assert_eq!(harness_model_default_override(" "), "hint:chat");
+}
+
+#[test]
+fn route_for_agent_ref_selects_harness_for_definitions_else_fallback() {
+ // Ensure the global registry is populated (idempotent no-op if another test
+ // already initialised it; builtins are always present either way).
+ let _ = crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global_builtins();
+
+ // A shipped harness definition → full-loop harness path.
+ assert_eq!(route_for_agent_ref("workflow_builder"), AgentRoute::Harness);
+ assert_eq!(route_for_agent_ref("planner"), AgentRoute::Harness);
+
+ // An id with no harness definition → the custom-registry completion fallback.
+ assert_eq!(
+ route_for_agent_ref("totally_unknown_custom_agent_xyz"),
+ AgentRoute::RegistryFallback
+ );
+}
+
+#[test]
+fn route_custom_entry_lookup_routes_enabled_custom_entry_to_harness() {
+ let entry = custom_registry_entry(true);
+ assert_eq!(
+ route_custom_entry_lookup(Some(&entry)),
+ AgentRoute::Harness,
+ "a known, enabled custom-registry agent must run through the harness (real tools), \
+ not the persona-only completion fallback"
+ );
+}
+
+#[test]
+fn route_custom_entry_lookup_falls_back_for_disabled_custom_entry() {
+ let entry = custom_registry_entry(false);
+ assert_eq!(
+ route_custom_entry_lookup(Some(&entry)),
+ AgentRoute::RegistryFallback,
+ "a disabled custom entry must still go through run_via_registry_fallback, which \
+ rejects it with a clear \"is disabled\" error"
+ );
+}
+
+#[test]
+fn route_custom_entry_lookup_falls_back_when_no_entry_exists() {
+ assert_eq!(
+ route_custom_entry_lookup(None),
+ AgentRoute::RegistryFallback,
+ "an agent_ref unknown to both the harness registry and the custom config registry \
+ must still resolve through the fallback (which reports \"unknown agent_ref\")"
+ );
+}
+
+// ── Handed context ───────────────────────────────────────────────────────
+
+/// An adapter acts for the context its run was started with, never for the
+/// scope of whichever task happens to poll it: two runs under two contexts do
+/// not cross, even when a third context is ambient.
+#[tokio::test]
+async fn adapters_act_for_the_context_they_were_handed_not_the_ambient_one() {
+ use crate::core::runtime::{ComponentSet, DispatchCtx, DomainSet, context::CoreContext};
+
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let sandbox_off = ComponentSet {
+ sandbox: false,
+ ..ComponentSet::default()
+ };
+ let handed_off = DispatchCtx::new(CoreContext::for_test_with_components(sandbox_off));
+ let handed_on = DispatchCtx::new(CoreContext::for_test_with_components(
+ ComponentSet::default(),
+ ));
+ let ambient = CoreContext::for_test(DomainSet::full(), None);
+
+ let build = |ctx: &DispatchCtx| OpenHumanCode {
+ ctx: ctx.clone(),
+ config: config.clone(),
+ security: security.clone(),
+ approval: Default::default(),
+ };
+ let (off, on) = (build(&handed_off), build(&handed_on));
+
+ CoreContext::scope(ambient, async {
+ assert!(!off.ctx.components().sandbox, "the run's own switch wins");
+ assert!(on.ctx.components().sandbox, "two runs do not cross");
+ assert!(
+ DispatchCtx::ambient().components().sandbox,
+ "the ambient scope is a third, unrelated context"
+ );
+ })
+ .await;
+}
diff --git a/crates/openhuman-core/src/modules/tinyflows.rs b/crates/openhuman-core/src/modules/tinyflows.rs
index e69de29bb2..5ee74430ca 100644
--- a/crates/openhuman-core/src/modules/tinyflows.rs
+++ b/crates/openhuman-core/src/modules/tinyflows.rs
@@ -0,0 +1,382 @@
+//! Calling the `tinyflows` module over the bus, and serving its host objects.
+//!
+//! The module owns the scheduler runtime (poll loop, claims, retry, completion),
+//! the cron job and run store, and the schedule maths behind
+//! `tinyflows_bus::schedule` (contract v6). This host file is the whole
+//! transport story for it:
+//!
+//! - [`proxy`] loads the module lazily and returns a proxy for its `Schedule`
+//! object. A registry `ModuleClient` cannot be used here because it reaches
+//! a module's *primary* interface (the authoring one), and the scheduler is a
+//! second interface on a second object path.
+//! - [`serve`] / [`unserve`] export a host object (the `ScheduleHost` callbacks
+//! or the document port) on the module bus, on the module runtime. Objects
+//! must outlive whichever short-lived runtime asked first, so they are never
+//! served from the caller's runtime.
+//!
+//! Hosts reach the module through nothing else; `cron::client` wraps these in
+//! the typed calls the rest of the core uses.
+//!
+//! With the `[components] tinyflows` switch off nothing here loads the module
+//! and every call answers `COMPONENT_DISABLED:tinyflows`. A build without the
+//! `modules` feature has no loader at all and answers that cron is unavailable.
+
+use crate::config::Config;
+
+/// Registry id of the module these calls go to.
+pub(crate) const MODULE_ID: &str = "tinyflows";
+
+/// The bus name the host's callback and document objects are served under.
+///
+/// The module addresses every callback by `(destination, object path)`; one
+/// name serves them all, and the object path names the scope.
+pub(crate) const HOST_BUS_NAME: &str = "ai.tinyhumans.openhuman.CronHost";
+
+/// Owns the interfaces served at one module-bus object path.
+pub(crate) struct ServedObjectRegistration(String);
+
+impl Drop for ServedObjectRegistration {
+ fn drop(&mut self) {
+ unserve(std::mem::take(&mut self.0));
+ }
+}
+
+/// The switched-off message callers surface verbatim.
+pub(crate) fn disabled_message() -> String {
+ format!(
+ "{}:{MODULE_ID} (set [components] {MODULE_ID} = true to enable)",
+ crate::core::runtime::components::COMPONENT_DISABLED
+ )
+}
+
+#[cfg(feature = "modules")]
+mod imp {
+ #[cfg(not(test))]
+ use super::MODULE_ID;
+ use super::{HOST_BUS_NAME, ServedObjectRegistration, disabled_message};
+ use crate::config::Config;
+ #[cfg(not(test))]
+ use crate::modules::ops;
+ use crate::modules::runtime;
+ use tinybus::{ObjectPath, Proxy};
+ use tinyflows_bus::schedule;
+
+ /// Longest a store or maths call waits. Job execution is not a call to the
+ /// module's `Schedule` object that returns quickly, so [`run_proxy`] has its
+ /// own bound.
+ const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
+
+ /// Longest `ExecuteJob` (Run Now) waits: the host runs the job's real work
+ /// (an agent turn, a shell command) inside the call.
+ const RUN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2 * 60 * 60);
+
+ /// Make sure the module serves. In unit tests this attaches the linked
+ /// module built into the test binary; everywhere else it goes through the
+ /// registry resolver (release, `source` or `linked` per configuration).
+ async fn ensure(config: &Config) -> Result<(), String> {
+ if !config.components.tinyflows {
+ return Err(disabled_message());
+ }
+ #[cfg(test)]
+ {
+ let _ = config;
+ super::fixture::attach().await
+ }
+ #[cfg(not(test))]
+ {
+ ops::ensure_loaded(config, MODULE_ID).await
+ }
+ }
+
+ async fn schedule_proxy(
+ config: &Config,
+ timeout: std::time::Duration,
+ ) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ schedule::BUS_NAME,
+ schedule::OBJECT_PATH,
+ schedule::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(timeout))
+ .map_err(|error| format!("the tinyflows schedule object is unreachable: {error}"))
+ }
+
+ async fn copilot_interface_proxy(config: &Config) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ tinyflows_bus::BUS_NAME,
+ tinyflows_bus::OBJECT_PATH,
+ tinyflows_bus::copilot::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(CALL_TIMEOUT))
+ .map_err(|error| format!("the tinyflows copilot object is unreachable: {error}"))
+ }
+
+ /// Proxy to the module-owned Authoring contract.
+ pub(crate) async fn authoring_proxy(config: &Config) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ tinyflows_bus::BUS_NAME,
+ tinyflows_bus::OBJECT_PATH,
+ tinyflows_bus::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(CALL_TIMEOUT))
+ .map_err(|error| format!("the tinyflows authoring object is unreachable: {error}"))
+ }
+
+ /// Proxy to the module-owned Catalog contract.
+ pub(crate) async fn catalog_proxy(config: &Config) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ tinyflows_bus::BUS_NAME,
+ tinyflows_bus::OBJECT_PATH,
+ tinyflows_bus::catalog::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(CALL_TIMEOUT))
+ .map_err(|error| format!("the tinyflows catalog object is unreachable: {error}"))
+ }
+
+ async fn copilot_invoke_interface_proxy(config: &Config) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ tinyflows_bus::BUS_NAME,
+ tinyflows_bus::OBJECT_PATH,
+ tinyflows_bus::copilot::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(RUN_TIMEOUT))
+ .map_err(|error| format!("the tinyflows copilot object is unreachable: {error}"))
+ }
+
+ /// A proxy for the module's `Schedule` object (store, maths and
+ /// validation members, which answer quickly).
+ pub(crate) async fn proxy(config: &Config) -> Result<Proxy, String> {
+ schedule_proxy(config, CALL_TIMEOUT).await
+ }
+
+ /// A proxy whose deadline fits a call that runs a whole job (`ExecuteJob`).
+ pub(crate) async fn run_proxy(config: &Config) -> Result<Proxy, String> {
+ schedule_proxy(config, RUN_TIMEOUT).await
+ }
+
+ /// A proxy for the module's Copilot tool, prompt and fallback services.
+ pub(crate) async fn copilot_proxy(config: &Config) -> Result<Proxy, String> {
+ copilot_interface_proxy(config).await
+ }
+
+ /// A long-deadline Copilot proxy for module-owned tool execution.
+ pub(crate) async fn copilot_invoke_proxy(config: &Config) -> Result<Proxy, String> {
+ copilot_invoke_interface_proxy(config).await
+ }
+
+ /// Serve `object` at `path` on the module bus, on the module runtime, and
+ /// own the host bus name. Idempotent per path only if `path` is unserved
+ /// first ([`unserve`]).
+ pub(crate) async fn serve(
+ path: String,
+ object: impl tinybus::service::Interface + 'static,
+ ) -> Result<(), String> {
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ let connection = runtime.connection().clone();
+ let served = runtime
+ .spawn(async move {
+ let path = ObjectPath::new(&path).map_err(|e| e.to_string())?;
+ connection
+ .request_name(HOST_BUS_NAME)
+ .await
+ .map_err(|e| e.to_string())?;
+ connection
+ .serve_at(path, object)
+ .await
+ .map_err(|e| e.to_string())
+ })
+ .await
+ .map_err(|error| format!("serving the host object did not finish: {error}"))?;
+ served
+ }
+
+ /// Serve two interfaces at one object path and return an RAII token for
+ /// their shared registration. The token is created on the module runtime
+ /// task, so if the caller is cancelled while this operation is in flight,
+ /// the detached task's output drops the token and unregisters the object.
+ pub(crate) async fn serve_pair(
+ path: String,
+ first: impl tinybus::service::Interface + 'static,
+ second: impl tinybus::service::Interface + 'static,
+ ) -> Result<ServedObjectRegistration, String> {
+ serve_pair_after_first(path, first, second, async {}).await
+ }
+
+ pub(crate) async fn serve_pair_after_first<F>(
+ path: String,
+ first: impl tinybus::service::Interface + 'static,
+ second: impl tinybus::service::Interface + 'static,
+ after_first: F,
+ ) -> Result<ServedObjectRegistration, String>
+ where
+ F: std::future::Future<Output = ()> + Send + 'static,
+ {
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ let connection = runtime.connection().clone();
+ runtime
+ .spawn(async move {
+ let object_path = ObjectPath::new(&path).map_err(|error| error.to_string())?;
+ connection
+ .request_name(HOST_BUS_NAME)
+ .await
+ .map_err(|error| error.to_string())?;
+ connection
+ .serve_at(object_path.clone(), first)
+ .await
+ .map_err(|error| error.to_string())?;
+ after_first.await;
+ if let Err(error) = connection.serve_at(object_path.clone(), second).await {
+ let _ = connection.unserve(&object_path).await;
+ return Err(error.to_string());
+ }
+ Ok(ServedObjectRegistration(path))
+ })
+ .await
+ .map_err(|error| format!("serving the host object did not finish: {error}"))?
+ }
+
+ /// Stop serving `path`. Fire and forget: a call already admitted finishes.
+ /// Without a runtime to run on (a sync drop at exit) the object is left;
+ /// the process is ending anyway.
+ pub(crate) fn unserve(path: String) {
+ if !runtime::is_started() {
+ return;
+ }
+ let Ok(handle) = tokio::runtime::Handle::try_current() else {
+ return;
+ };
+ handle.spawn(async move {
+ let Ok(runtime) = runtime::runtime().await else {
+ return;
+ };
+ let connection = runtime.connection().clone();
+ let _ = runtime
+ .spawn(async move {
+ if let Ok(object) = ObjectPath::new(&path) {
+ let removed = connection.unserve(&object).await;
+ tracing::trace!(path = %path, removed, "[cron:bus] host object unserved");
+ }
+ })
+ .await;
+ });
+ }
+}
+
+#[cfg(all(test, feature = "modules"))]
+#[path = "tinyflows_fixture.rs"]
+mod fixture;
+
+#[cfg(all(test, feature = "modules"))]
+pub(crate) use imp::serve_pair_after_first;
+#[cfg(feature = "modules")]
+pub(crate) use imp::{
+ authoring_proxy, catalog_proxy, copilot_invoke_proxy, copilot_proxy, proxy, run_proxy, serve,
+ serve_pair, unserve,
+};
+
+#[cfg(not(feature = "modules"))]
+mod imp {
+ use super::{ServedObjectRegistration, disabled_message};
+ use crate::config::Config;
+
+ fn unavailable(config: &Config) -> String {
+ if config.components.tinyflows {
+ "scheduled jobs are unavailable: this build has no module loader (build with the `modules` feature)"
+ .to_string()
+ } else {
+ disabled_message()
+ }
+ }
+
+ pub(crate) async fn proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn run_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn copilot_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn authoring_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn catalog_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn copilot_invoke_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
+ pub(crate) async fn serve(
+ _path: String,
+ _object: impl tinybus::service::Interface + 'static,
+ ) -> Result<(), String> {
+ Err("scheduled jobs are unavailable: this build has no module loader".to_string())
+ }
+
+ pub(crate) async fn serve_pair(
+ _path: String,
+ _first: impl tinybus::service::Interface + 'static,
+ _second: impl tinybus::service::Interface + 'static,
+ ) -> Result<ServedObjectRegistration, String> {
+ Err("scheduled jobs are unavailable: this build has no module loader".to_string())
+ }
+
+ pub(crate) fn unserve(_path: String) {}
+}
+
+#[cfg(not(feature = "modules"))]
+pub(crate) use imp::{
+ authoring_proxy, catalog_proxy, copilot_invoke_proxy, copilot_proxy, proxy, run_proxy, serve,
+ serve_pair, unserve,
+};
+
+/// Whether the module can serve in this build and configuration (the switch
+/// is on and the loader exists). Does not load anything.
+#[must_use]
+pub(crate) fn available(config: &Config) -> bool {
+ config.components.tinyflows && cfg!(feature = "modules")
+}
+
+#[cfg(test)]
+#[path = "tinyflows_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/tinyflows_fixture.rs b/crates/openhuman-core/src/modules/tinyflows_fixture.rs
index e69de29bb2..ab94e8cf2d 100644
--- a/crates/openhuman-core/src/modules/tinyflows_fixture.rs
+++ b/crates/openhuman-core/src/modules/tinyflows_fixture.rs
@@ -0,0 +1,23 @@
+//! The tinyflows module linked into the test binary: the `static-link` build of
+//! `tinyflows-module`, attached once to the process-wide module host.
+
+use crate::config::Config;
+use crate::config::schema::ModuleSourceMode;
+use crate::modules::{linked::register_linked, ops};
+use tokio::sync::OnceCell;
+
+static ATTACHED: OnceCell<Result<(), String>> = OnceCell::const_new();
+
+/// Attach the linked module to the process-wide module host, once.
+pub(crate) async fn attach() -> Result<(), String> {
+ ATTACHED
+ .get_or_init(|| async {
+ register_linked(super::MODULE_ID, tinyflows_module::linked_module);
+ let mut config = Config::default();
+ config.modules.allow_download = false;
+ config.modules.source = ModuleSourceMode::Linked;
+ ops::ensure_loaded(&config, super::MODULE_ID).await
+ })
+ .await
+ .clone()
+}