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_tests.rs,crates/openhuman-core/s

Steven Enamakel5bcbdc32f6e1
diff --git a/crates/openhuman-core/src/flows/authoring_host_tests.rs b/crates/openhuman-core/src/flows/authoring_host_tests.rs
index 5a58e9e502..72c3d0b40a 100644
--- a/crates/openhuman-core/src/flows/authoring_host_tests.rs
+++ b/crates/openhuman-core/src/flows/authoring_host_tests.rs
@@ -72,7 +72,7 @@ async fn saved_workflow_callback_uses_its_captured_profile_over_the_bus() {
)
.unwrap();
flow.id = shared_id.into();
- crate::flows::store::upsert_flow(&config, &flow).unwrap();
+ crate::flows::test_support::seed_flow(&config, &flow).unwrap();
})
.await;
}
diff --git a/crates/openhuman-core/src/flows/bus.rs b/crates/openhuman-core/src/flows/bus.rs
index aa70a0e291..1350be39fd 100644
--- a/crates/openhuman-core/src/flows/bus.rs
+++ b/crates/openhuman-core/src/flows/bus.rs
@@ -4,11 +4,8 @@
//! [`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.
+//! `WebhookIncomingRequest`), asks TinyFlows to match their graph metadata, and
+//! spawns `flows::ops::flows_run` for each match.
#[cfg(test)]
#[path = "bus_tests.rs"]
@@ -20,7 +17,7 @@ mod trigger;
pub use run_digest::FlowRunDigestSubscriber;
pub use trigger::FlowTriggerSubscriber;
-pub(crate) use trigger::{extract_trigger_config, extract_trigger_kind};
+pub(crate) use trigger::describe_trigger;
// Private helpers and shared imports the colocated tests reach through
// `use super::*`.
@@ -29,8 +26,6 @@ use crate::config::Config;
#[cfg(test)]
use crate::core::events::DomainEvent;
#[cfg(test)]
-use crate::flows::store;
-#[cfg(test)]
use run_digest::{
digest_filter, enforce_retention_cap, render_run_digest, truncate_chars, DIGEST_MAX_CHARS,
};
@@ -40,5 +35,3 @@ use serde_json::Value;
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_tests.rs b/crates/openhuman-core/src/flows/bus/owner_tests.rs
index 22c03fb828..512c484fca 100644
--- a/crates/openhuman-core/src/flows/bus/owner_tests.rs
+++ b/crates/openhuman-core/src/flows/bus/owner_tests.rs
@@ -51,7 +51,7 @@ async fn a_cached_owner_is_dropped_once_its_scope_loses_the_flow() {
workspace_dir: dir.path().to_path_buf(),
..Config::default()
};
- crate::flows::store::upsert_flow(&config, &local_flow("owner-test-revalidate")).unwrap();
+ crate::flows::test_support::seed_flow(&config, &local_flow("owner-test-revalidate")).unwrap();
// Found in `local`, and remembered there.
assert_eq!(
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index 026cef6122..1831288768 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -6,7 +6,9 @@
use crate::config::Config;
use crate::core::events::DomainEvent;
use crate::flows::store;
+use crate::modules::tinyflows as module;
use async_trait::async_trait;
+use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
@@ -14,65 +16,76 @@ 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::{mpsc, Mutex as AsyncMutex};
-/// 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()
+fn portability_call<T, A>(config: &Config, member: &'static str, request: A) -> Result<T, String>
+where
+ T: DeserializeOwned + Send + 'static,
+ A: Serialize + Send + Sync + 'static,
+{
+ let config = config.clone();
+ crate::storage::block_on_anyhow(async move {
+ let proxy = module::portability_proxy(&config)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ proxy
+ .call(member, &(request,))
+ .await
+ .map_err(anyhow::Error::msg)
+ })
+ .map_err(|error| error.to_string())
}
-/// 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)
+/// Ask TinyFlows for normalized trigger metadata used by host bindings.
+pub(crate) fn describe_trigger(
+ config: &Config,
+ flow: &Flow,
+) -> Result<tinyflows_bus::portability::TriggerDetails, String> {
+ let graph = serde_json::to_value(&flow.graph).map_err(|error| error.to_string())?;
+ portability_call(
+ config,
+ tinyflows_bus::portability::methods::DESCRIBE_TRIGGER,
+ tinyflows_bus::portability::DescribeTrigger { graph },
+ )
}
-/// 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)
+/// Return author-pinned literal inputs for an unattended trigger run.
+pub(super) fn pinned_trigger_inputs(
+ config: &Config,
+ flow: &Flow,
+) -> Result<serde_json::Map<String, Value>, String> {
+ let graph = serde_json::to_value(&flow.graph).map_err(|error| error.to_string())?;
+ let value: Value = portability_call(
+ config,
+ tinyflows_bus::portability::methods::PINNED_INPUTS,
+ tinyflows_bus::portability::PinnedInputs { graph },
+ )?;
+ value
+ .as_object()
.cloned()
- .unwrap_or_default()
+ .ok_or_else(|| "TinyFlows returned pinned inputs in an invalid shape".to_string())
}
/// 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)
+pub(super) fn matches_app_event(
+ config: &Config,
+ flow: &Flow,
+ toolkit: &str,
+ trigger_slug: &str,
+) -> Result<bool, String> {
+ let graph = serde_json::to_value(&flow.graph).map_err(|error| error.to_string())?;
+ portability_call(
+ config,
+ tinyflows_bus::portability::methods::APP_EVENT_BINDING,
+ tinyflows_bus::portability::AppEventBinding {
+ graph,
+ toolkit: toolkit.to_string(),
+ trigger_slug: trigger_slug.to_string(),
+ },
+ )
}
/// Listens for normalized trigger events and starts runs for matching
@@ -503,11 +516,24 @@ impl FlowTriggerSubscriber {
tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick for disabled flow — ignoring");
return;
}
- if !matches!(extract_trigger_kind(&flow), Some(TriggerKind::Schedule)) {
+ let details = match describe_trigger(&config, &flow) {
+ Ok(details) => details,
+ Err(error) => {
+ tracing::warn!(target: "flows", %flow_id, %error, "[flows] failed to describe trigger for schedule tick");
+ return;
+ }
+ };
+ if details.kind.as_deref() != Some("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);
+ let inputs = match pinned_trigger_inputs(&config, &flow) {
+ Ok(inputs) => inputs,
+ Err(error) => {
+ tracing::warn!(target: "flows", %flow_id, %error, "[flows] failed to read pinned inputs for schedule trigger");
+ return;
+ }
+ };
self.enqueue_schedule(&ctx, flow_id.to_string(), inputs)
.await;
}
@@ -539,9 +565,22 @@ impl FlowTriggerSubscriber {
let mut matched = 0usize;
for flow in flows {
- if matches_app_event(&flow, toolkit, trigger_slug) {
+ let matches = match matches_app_event(&config, &flow, toolkit, trigger_slug) {
+ Ok(matches) => matches,
+ Err(error) => {
+ tracing::warn!(target: "flows", flow_id = %flow.id, %toolkit, %trigger_slug, %error, "[flows] failed to match app_event trigger");
+ continue;
+ }
+ };
+ if matches {
matched += 1;
- let inputs = pinned_trigger_inputs(&flow);
+ let inputs = match pinned_trigger_inputs(&config, &flow) {
+ Ok(inputs) => inputs,
+ Err(error) => {
+ tracing::warn!(target: "flows", flow_id = %flow.id, %error, "[flows] failed to read pinned inputs for app_event trigger");
+ continue;
+ }
+ };
self.dispatch_app_event(&ctx, flow.id.clone(), payload.clone(), inputs)
.await;
}
diff --git a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
index eda403b666..69e2b46c58 100644
--- a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
@@ -1,58 +1,63 @@
use super::*;
-use tinyflows::model::TriggerKind;
use tinyflows_catalog::types::{FlowRun, FlowRunTrigger};
#[test]
-fn pinned_trigger_inputs_reads_values_an_author_fixed_for_unattended_runs() {
- let flow = flow_with_trigger_config(
- "f1",
+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 portability_proxy_describes_bindings_and_returns_pinned_inputs() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let schedule_flow = flow_with_trigger_config(
+ "schedule-flow",
true,
json!({
"trigger_kind": "schedule",
"schedule": "0 9 * * *",
- "inputs": { "repo": "acme/api", "depth": 3 }
+ "inputs": {"repo": "acme/api", "depth": 3}
}),
);
- let inputs = pinned_trigger_inputs(&flow);
+
+ let details = describe_trigger(&config, &schedule_flow).unwrap();
+ assert_eq!(details.kind.as_deref(), Some("schedule"));
+ assert!(details.schedule.is_some(), "schedule is returned as a typed value");
+ let inputs = trigger::pinned_trigger_inputs(&config, &schedule_flow).unwrap();
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());
-}
+ let event_flow = flow_with_trigger_config(
+ "event-flow",
+ true,
+ json!({
+ "trigger_kind": "app_event",
+ "toolkit": "gmail",
+ "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE"
+ }),
+ );
+ assert!(trigger::matches_app_event(
+ &config,
+ &event_flow,
+ "Gmail",
+ "gmail_new_gmail_message"
+ )
+ .unwrap());
+ assert!(!trigger::matches_app_event(&config, &event_flow, "slack", "GMAIL_NEW_GMAIL_MESSAGE")
+ .unwrap());
-#[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"][..])
+ let malformed = flow_with_trigger_config(
+ "malformed-flow",
+ true,
+ json!({"trigger_kind": "schedule", "schedule": {"invalid": true}}),
);
+ assert!(describe_trigger(&config, &malformed).is_err());
}
#[tokio::test]
@@ -72,64 +77,6 @@ async fn handle_does_not_panic_on_arbitrary_events() {
.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();
@@ -139,7 +86,7 @@ async fn handle_app_event_ignores_disabled_flows() {
false,
json!({ "trigger_kind": "app_event", "toolkit": "gmail", "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE" }),
);
- crate::flows::store::upsert_flow(&config, &flow).unwrap();
+ crate::flows::test_support::seed_flow(&config, &flow).unwrap();
// `list_enabled_flows` must not surface the disabled flow at all —
// proves the subscriber's dispatch source already excludes it,
@@ -158,7 +105,7 @@ async fn handle_schedule_tick_ignores_disabled_flow() {
false,
json!({ "trigger_kind": "schedule", "schedule": "0 9 * * *" }),
);
- crate::flows::store::upsert_flow(&config, &flow).unwrap();
+ crate::flows::test_support::seed_flow(&config, &flow).unwrap();
let sub = FlowTriggerSubscriber::new(config.clone());
// Must not panic and must not spawn a run for a disabled flow — we
@@ -286,7 +233,7 @@ async fn digest_treats_completed_with_warnings_as_success() {
let _engine = digest_test_engine(&config);
let flow = flow_with_trigger_config("f-warn", true, json!({}));
- store::upsert_flow(&config, &flow).unwrap();
+ crate::flows::test_support::seed_flow(&config, &flow).unwrap();
let run = crate::flows::ops::flows_run(
&crate::core::runtime::DispatchCtx::ambient(),
&config,
@@ -332,7 +279,7 @@ async fn digest_is_skipped_quietly_when_memory_is_off() {
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();
+ crate::flows::test_support::seed_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)
diff --git a/crates/openhuman-core/src/flows/mod.rs b/crates/openhuman-core/src/flows/mod.rs
index 80193e1f68..1a21986001 100644
--- a/crates/openhuman-core/src/flows/mod.rs
+++ b/crates/openhuman-core/src/flows/mod.rs
@@ -1,6 +1,7 @@
-//! 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.
+//! The `flows::` domain: saved automation workflows (TinyFlows graphs) —
+//! create/get/list/update/delete/enable/run through the TinyFlows module and
+//! its CatalogStorage callback. Mirrors `crates/openhuman-core/src/cron/`'s
+//! module shape.
//!
//! Business logic lives in [`ops`]; workflow definitions in `store`; the RPC/CLI
//! controller surface in `schemas` (private, re-exported below).
@@ -41,7 +42,9 @@ pub(crate) mod registration;
pub(crate) mod runs_adapter;
mod schemas;
mod store;
-/// The tinyflows engine seam (formerly `crate::tinyflows`).
+#[cfg(test)]
+pub(crate) mod test_support;
+/// Generic graph model and legacy migration re-exports retained for host APIs.
pub mod tinyflows;
// Portable catalog vocabulary is imported directly from `tinyflows-catalog`.
diff --git a/crates/openhuman-core/src/flows/ops.rs b/crates/openhuman-core/src/flows/ops.rs
index 49c6500ac4..eaebe50f8c 100644
--- a/crates/openhuman-core/src/flows/ops.rs
+++ b/crates/openhuman-core/src/flows/ops.rs
@@ -3,9 +3,8 @@
//! `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:
+//! The module is split by responsibility; host-owned operations used by RPC,
+//! tools, and sibling flow modules are re-exported from here:
//!
//! | Submodule | Responsibility |
//! | --- | --- |
@@ -35,14 +34,12 @@ use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{json, Value};
-use tinyflows::model::{NodeKind, TriggerKind, WorkflowGraph};
+use tinyflows::model::{NodeKind, WorkflowGraph};
// Generic graph analysis used for UI notes and authoring summaries comes from
// the TinyFlows bus. OpenHuman-specific save and dispatch policy stays here.
// 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.
+// fires unattended, whether it can act on the world, and whether it has work
+// are graph properties. Import them only at their host policy call sites.
use crate::config::Config;
use crate::core::Outcome;
use crate::flows::bus;
@@ -51,9 +48,6 @@ use crate::flows::store;
use crate::security::approval::{ApprovalChatContext, ApprovalTurnContext};
use crate::security::turn_origin::{with_origin, AgentTurnOrigin};
use tinyflows_catalog::build_registry;
-pub(crate) use tinyflows_catalog::graph_policy::{
- enforce_side_effect_approval, trigger_is_automatic,
-};
use tinyflows_catalog::types::{FlowConnection, FlowRunTrigger, FlowSuggestion, SuggestionStatus};
use tokio_util::sync::CancellationToken;
use {tinyflows_catalog::Flow, tinyflows_catalog::FlowRun};
@@ -63,17 +57,6 @@ use {tinyflows_catalog::Flow, tinyflows_catalog::FlowRun};
/// call must never let the RPC block indefinitely — this caps the whole run.
const FLOW_RUN_TIMEOUT_SECS: u64 = crate::flows::runs_adapter::RUN_TIMEOUT_SECS;
-/// 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.
-#[cfg(test)]
-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
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rs
index fc6480b208..2d62d8345a 100644
--- a/crates/openhuman-core/src/flows/ops/builder.rs
+++ b/crates/openhuman-core/src/flows/ops/builder.rs
@@ -20,22 +20,6 @@ pub async fn flows_build(
config: &Config,
req: tinyflows_bus::copilot::BuilderPromptRequest,
stream: Option<FlowStreamTarget>,
-) -> Result<Outcome<Value>, String> {
- flows_build_with_extra_hidden_tools(ctx, config, req, stream, &[]).await
-}
-
-/// [`flows_build`] with caller-specific tools removed in addition to the
-/// standard streaming/headless safety lists.
-///
-/// This is intentionally crate-private: product surfaces use [`flows_build`]'s
-/// normal builder belt. Host integrations that add their own persistence
-/// boundary can hide tools that would bypass that boundary.
-pub(crate) async fn flows_build_with_extra_hidden_tools(
- ctx: &DispatchCtx,
- config: &Config,
- req: tinyflows_bus::copilot::BuilderPromptRequest,
- stream: Option<FlowStreamTarget>,
- extra_hidden_tools: &[&str],
) -> Result<Outcome<Value>, String> {
use crate::agent::OpenHumanSessionHost;
let prompt = crate::flows::copilot_bus::call::<tinyflows_bus::copilot::TextResponse, _>(
@@ -120,15 +104,6 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
}
restrict_builder_toolset(&mut agent);
}
- if !extra_hidden_tools.is_empty() {
- tracing::debug!(
- target: "flows",
- hidden = ?extra_hidden_tools,
- "[flows] flows_build: applying caller-specific hidden tools"
- );
- agent.hide_tools(extra_hidden_tools);
- }
-
// When a chat thread is attached (the copilot pane), stream the builder turn
// into it exactly like an interactive turn — text/tool deltas and the
// `propose_workflow` tool result the frontend renders as a proposal card.
diff --git a/crates/openhuman-core/src/flows/ops/definitions.rs b/crates/openhuman-core/src/flows/ops/definitions.rs
index 78bcb8e730..582ff95ae7 100644
--- a/crates/openhuman-core/src/flows/ops/definitions.rs
+++ b/crates/openhuman-core/src/flows/ops/definitions.rs
@@ -1,4 +1,5 @@
use super::*;
+use tinyflows_catalog::graph_policy::{enforce_side_effect_approval, trigger_is_automatic};
/// Publishes a [`DomainEvent::FlowChanged`](crate::core::events::DomainEvent::FlowChanged)
/// so an open Workflows list/canvas refetches (bridged to a `flow:changed`
diff --git a/crates/openhuman-core/src/flows/ops/triggers.rs b/crates/openhuman-core/src/flows/ops/triggers.rs
index 89778f3e12..80bfb4f08c 100644
--- a/crates/openhuman-core/src/flows/ops/triggers.rs
+++ b/crates/openhuman-core/src/flows/ops/triggers.rs
@@ -82,13 +82,22 @@ pub async fn flows_set_enabled(
/// won't fire automatically until the underlying issue (invalid schedule,
/// cron store error, …) is fixed.
pub(super) fn bind_trigger(config: &Config, flow: &Flow) {
- match bus::extract_trigger_kind(flow) {
- Some(TriggerKind::Schedule) => bind_schedule_trigger(config, flow),
- Some(TriggerKind::Webhook) => log_webhook_trigger_deferred(flow, true),
+ let details = match bus::describe_trigger(config, flow) {
+ Ok(details) => details,
+ Err(error) => {
+ tracing::warn!(target: "flows", flow_id = %flow.id, %error, "[flows] failed to describe trigger while binding");
+ return;
+ }
+ };
+ match details.kind.as_deref() {
+ Some("schedule") => match details.schedule {
+ Some(schedule) => bind_schedule_trigger(config, flow, schedule),
+ None => tracing::warn!(target: "flows", flow_id = %flow.id, "[flows] schedule trigger description omitted its schedule"),
+ },
+ Some("webhook") => log_webhook_trigger_deferred(flow, true),
_ => {
- // `app_event` needs no enable-time binding (matched at dispatch
- // time against `list_enabled_flows`); `manual`/`form`/others have
- // no automatic-dispatch concept at all.
+ // `app_event` is matched at dispatch time; other kinds have no
+ // enable-time automatic-dispatch binding.
}
}
}
@@ -96,9 +105,16 @@ pub(super) fn bind_trigger(config: &Config, flow: &Flow) {
/// Tears down the automatic-dispatch side effect for `flow`'s trigger kind,
/// mirroring [`bind_trigger`]. Best-effort, same rationale.
pub(super) fn unbind_trigger(config: &Config, flow: &Flow) {
- match bus::extract_trigger_kind(flow) {
- Some(TriggerKind::Schedule) => unbind_schedule_trigger(config, &flow.id),
- Some(TriggerKind::Webhook) => log_webhook_trigger_deferred(flow, false),
+ let details = match bus::describe_trigger(config, flow) {
+ Ok(details) => details,
+ Err(error) => {
+ tracing::warn!(target: "flows", flow_id = %flow.id, %error, "[flows] failed to describe trigger while unbinding");
+ return;
+ }
+ };
+ match details.kind.as_deref() {
+ Some("schedule") => unbind_schedule_trigger(config, &flow.id),
+ Some("webhook") => log_webhook_trigger_deferred(flow, false),
_ => {}
}
}
@@ -108,25 +124,11 @@ pub(super) fn unbind_trigger(config: &Config, flow: &Flow) {
/// `cron::find_flow_schedule_job` rather than creating a duplicate, so this
/// is safe to call both from `flows_set_enabled` and from boot
/// reconciliation ([`reconcile_schedule_triggers_on_boot`]).
-pub(super) fn bind_schedule_trigger(config: &Config, flow: &Flow) {
- let Some(trigger_config) = bus::extract_trigger_config(flow) else {
- tracing::warn!(target: "flows", flow_id = %flow.id, "[flows] schedule trigger: flow has no single trigger node — cannot bind cron job");
- return;
- };
- let Some(schedule_raw) = trigger_config.get("schedule").cloned() else {
- tracing::warn!(target: "flows", flow_id = %flow.id, "[flows] schedule trigger config is missing `schedule` — cannot bind cron job");
- return;
- };
- let schedule: tinyflows_bus::schedule::types::Schedule = match serde_json::from_value(
- schedule_raw,
- ) {
- Ok(s) => s,
- Err(e) => {
- tracing::warn!(target: "flows", flow_id = %flow.id, error = %e, "[flows] invalid schedule trigger config — cannot bind cron job");
- return;
- }
- };
-
+pub(super) fn bind_schedule_trigger(
+ config: &Config,
+ flow: &Flow,
+ schedule: tinyflows_bus::schedule::types::Schedule,
+) {
match crate::cron::find_flow_schedule_job(config, &flow.id) {
Ok(Some(existing)) => {
let patch = tinyflows_bus::schedule::types::CronJobPatch {
@@ -233,9 +235,17 @@ async fn reconcile_schedule_triggers_in_scope(config: &Config) -> Result<(), Str
}
let mut reconciled = 0usize;
for flow in &flows {
- if matches!(bus::extract_trigger_kind(flow), Some(TriggerKind::Schedule)) {
- bind_schedule_trigger(config, flow);
- reconciled += 1;
+ match bus::describe_trigger(config, flow) {
+ Ok(details) if details.kind.as_deref() == Some("schedule") => {
+ if let Some(schedule) = details.schedule {
+ bind_schedule_trigger(config, flow, schedule);
+ reconciled += 1;
+ } else {
+ tracing::warn!(target: "flows", flow_id = %flow.id, "[flows] schedule trigger description omitted its schedule during boot reconcile");
+ }
+ }
+ Ok(_) => {}
+ Err(error) => tracing::warn!(target: "flows", flow_id = %flow.id, %error, "[flows] failed to describe trigger during boot reconcile"),
}
}
tracing::debug!(target: "flows", scanned = flows.len(), reconciled, skipped, "[flows] boot reconciliation of schedule-trigger cron jobs complete");
diff --git a/crates/openhuman-core/src/flows/ops/updates.rs b/crates/openhuman-core/src/flows/ops/updates.rs
index e5c403f2d3..1be6107c29 100644
--- a/crates/openhuman-core/src/flows/ops/updates.rs
+++ b/crates/openhuman-core/src/flows/ops/updates.rs
@@ -1,4 +1,5 @@
use super::*;
+use tinyflows_catalog::graph_policy::{enforce_side_effect_approval, trigger_is_automatic};
/// Maps the Catalog bus [`FlowUpdateError`](tinyflows_bus::catalog::FlowUpdateError) to the RPC
/// error string. A concurrency conflict is encoded as a JSON object the UI can
@@ -227,9 +228,8 @@ async fn flows_update_inner(
}
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);
+ let trigger_unchanged = existing.graph.trigger().map(|trigger| &trigger.config)
+ == updated.graph.trigger().map(|trigger| &trigger.config);
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);
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 0319800102..d7ae1a40ad 100644
--- a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
@@ -3,7 +3,7 @@ use super::*;
use crate::core::runtime::DispatchCtx;
use crate::{
config::Config,
- flows::ops::{flows_build_with_extra_hidden_tools, FlowStreamTarget},
+ flows::ops::{flows_build, FlowStreamTarget},
};
#[tokio::test]
@@ -85,12 +85,11 @@ fn repair_backend_failure_returns_no_proposal_before_starting_the_builder() {
failing_node_ids: vec!["fetch".to_string()],
};
- let outcome = flows_build_with_extra_hidden_tools(
+ let outcome = flows_build(
&DispatchCtx::process_default(),
&Config::default(),
req.clone(),
None,
- &[],
)
.await
.expect("backend failure should short-circuit before the builder starts");
@@ -109,12 +108,11 @@ fn repair_backend_failure_returns_no_proposal_before_starting_the_builder() {
};
let mut events = crate::web_chat::subscribe_web_channel_events();
- flows_build_with_extra_hidden_tools(
+ flows_build(
&DispatchCtx::process_default(),
&Config::default(),
req,
Some(stream),
- &[],
)
.await
.expect("streamed backend failure should short-circuit before the builder starts");
diff --git a/crates/openhuman-core/src/flows/ops_triggers_and_resume_tests.rs b/crates/openhuman-core/src/flows/ops_triggers_and_resume_tests.rs
index c6bafd7550..56e91a1112 100644
--- a/crates/openhuman-core/src/flows/ops_triggers_and_resume_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_triggers_and_resume_tests.rs
@@ -223,6 +223,38 @@ async fn flows_update_rebinds_schedule_cron_job_when_trigger_schedule_changes()
assert_eq!(flow_jobs.len(), 1);
}
+#[tokio::test]
+async fn flows_update_does_not_rebind_schedule_for_pinned_input_changes() {
+ 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();
+ flows_set_enabled(&config, &created.value.id, true)
+ .await
+ .unwrap();
+ let original_job = crate::cron::find_flow_schedule_job(&config, &created.value.id)
+ .unwrap()
+ .expect("cron job bound on enable");
+
+ let mut graph = schedule_trigger_graph("0 9 * * *");
+ graph["nodes"][0]["config"]["inputs"] = json!({"team": "platform"});
+ flows_update(&config, &created.value.id, None, Some(graph), None, None)
+ .await
+ .unwrap();
+
+ let job = crate::cron::find_flow_schedule_job(&config, &created.value.id)
+ .unwrap()
+ .expect("schedule job remains bound after input-only edit");
+ assert_eq!(job.id, original_job.id, "input edits must preserve the binding");
+ assert_eq!(job.expression, original_job.expression);
+}
+
#[tokio::test]
async fn flows_update_does_not_rebind_when_graph_is_not_supplied() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/openhuman-core/src/flows/store.rs b/crates/openhuman-core/src/flows/store.rs
index bc325181c6..0b1f72275e 100644
--- a/crates/openhuman-core/src/flows/store.rs
+++ b/crates/openhuman-core/src/flows/store.rs
@@ -7,9 +7,6 @@
use anyhow::{anyhow, Result};
use serde::{de::DeserializeOwned, Serialize};
-#[cfg(test)]
-use serde_json::Value;
-use std::path::PathBuf;
use tinyflows_bus::catalog::{
self, DeleteWorkflowResult, FlowUpdateError as BusUpdateError, GetRevisionRequest,
ListRevisionsRequest, ListWorkflowsResult, PutWorkflowRequest, PutWorkflowResponse,
@@ -20,11 +17,6 @@ use tinyflows_catalog::{Flow, FlowRevision, FlowSuggestion, SuggestionStatus};
use crate::config::Config;
use crate::modules::tinyflows as module;
-/// Retained only for callers that display the legacy workflow folder path.
-pub fn dir(config: &Config) -> PathBuf {
- config.workspace_dir.join("flows")
-}
-
pub(crate) fn call_catalog<T, A>(config: &Config, member: &'static str, args: A) -> Result<T>
where
T: DeserializeOwned + Send + 'static,
@@ -76,64 +68,6 @@ fn put_result(response: PutWorkflowResponse) -> Result<Flow> {
}
}
-/// Seed a caller-chosen id through CatalogStorage for host tests.
-#[cfg(test)]
-pub fn upsert_flow(config: &Config, flow: &Flow) -> Result<()> {
- test_seed_flow(config, flow)
-}
-
-#[cfg(test)]
-fn test_seed_flow(config: &Config, flow: &Flow) -> Result<()> {
- let storage = super::catalog_storage::register_blocking(config)?;
- let _: ListWorkflowsResult =
- call_catalog(config, catalog::members::LIST_WORKFLOWS, (storage.clone(),))?;
- let created_ms = chrono::DateTime::parse_from_rfc3339(&flow.created_at)
- .map(|date| date.timestamp_millis())
- .unwrap_or(0);
- let updated_ms = chrono::DateTime::parse_from_rfc3339(&flow.updated_at)
- .map(|date| date.timestamp_millis())
- .unwrap_or(created_ms);
- let mut doc = serde_json::json!({
- "name": flow.name,
- "graph": flow.graph,
- "enabled": flow.enabled,
- "created_ms": created_ms,
- "updated_ms": updated_ms,
- "require_approval": flow.require_approval,
- "revision": 1,
- "incarnation": uuid::Uuid::new_v4().to_string(),
- });
- if let Some(status) = &flow.last_status {
- doc["last_status"] = Value::String(status.clone());
- }
- if let Some(last_run_at) = &flow.last_run_at {
- if let Ok(date) = chrono::DateTime::parse_from_rfc3339(last_run_at) {
- doc["last_run_ms"] = Value::from(date.timestamp_millis());
- }
- }
- let request = catalog::DocPutRequest {
- collection: "flows.definitions".into(),
- id: flow.id.clone(),
- doc,
- precondition: catalog::CatalogDocumentPrecondition::None,
- schema: 2,
- expires_ms: None,
- created_ms: Some(created_ms),
- };
- match super::catalog_storage::call_test_storage::<catalog::CatalogStorageReply, _>(
- config,
- catalog::storage::PUT,
- (request,),
- )? {
- catalog::CatalogStorageReply::Value { .. } => Ok(()),
- catalog::CatalogStorageReply::Error { error } => Err(anyhow!(
- "CatalogStorage fixture write failed ({}): {}",
- error.kind,
- error.message
- )),
- }
-}
-
/// Duplicate a workflow through the module's Catalog contract.
pub fn insert_duplicate_flow(config: &Config, source: &Flow, new_name: String) -> Result<Flow> {
let storage = super::catalog_storage::register_blocking(config)?;
diff --git a/crates/openhuman-core/src/flows/test_support.rs b/crates/openhuman-core/src/flows/test_support.rs
new file mode 100644
index 0000000000..0bced0d01c
--- /dev/null
+++ b/crates/openhuman-core/src/flows/test_support.rs
@@ -0,0 +1,62 @@
+//! Shared test fixtures for saved workflows.
+
+use anyhow::{anyhow, Result};
+use serde_json::Value;
+use tinyflows_bus::catalog::{
+ self, CatalogDocumentPrecondition, CatalogStorageReply, ListWorkflowsResult,
+};
+use tinyflows_catalog::Flow;
+
+use crate::{config::Config, flows::store};
+
+/// Seed a caller-chosen workflow id through the existing CatalogStorage port.
+pub(crate) fn seed_flow(config: &Config, flow: &Flow) -> Result<()> {
+ let storage = super::catalog_storage::register_blocking(config)?;
+ let _: ListWorkflowsResult =
+ store::call_catalog(config, catalog::members::LIST_WORKFLOWS, (storage.clone(),))?;
+ let created_ms = chrono::DateTime::parse_from_rfc3339(&flow.created_at)
+ .map(|date| date.timestamp_millis())
+ .unwrap_or(0);
+ let updated_ms = chrono::DateTime::parse_from_rfc3339(&flow.updated_at)
+ .map(|date| date.timestamp_millis())
+ .unwrap_or(created_ms);
+ let mut doc = serde_json::json!({
+ "name": flow.name,
+ "graph": flow.graph,
+ "enabled": flow.enabled,
+ "created_ms": created_ms,
+ "updated_ms": updated_ms,
+ "require_approval": flow.require_approval,
+ "revision": 1,
+ "incarnation": uuid::Uuid::new_v4().to_string(),
+ });
+ if let Some(status) = &flow.last_status {
+ doc["last_status"] = Value::String(status.clone());
+ }
+ if let Some(last_run_at) = &flow.last_run_at {
+ if let Ok(date) = chrono::DateTime::parse_from_rfc3339(last_run_at) {
+ doc["last_run_ms"] = Value::from(date.timestamp_millis());
+ }
+ }
+ let request = catalog::DocPutRequest {
+ collection: "flows.definitions".into(),
+ id: flow.id.clone(),
+ doc,
+ precondition: CatalogDocumentPrecondition::None,
+ schema: 2,
+ expires_ms: None,
+ created_ms: Some(created_ms),
+ };
+ match super::catalog_storage::call_test_storage::<CatalogStorageReply, _>(
+ config,
+ catalog::storage::PUT,
+ (request,),
+ )? {
+ CatalogStorageReply::Value { .. } => Ok(()),
+ CatalogStorageReply::Error { error } => Err(anyhow!(
+ "CatalogStorage fixture write failed ({}): {}",
+ error.kind,
+ error.message
+ )),
+ }
+}