Skip to content

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

refactor(orchestration): run workflows through tinyagents

Steven Enamakel9e014a0b50f5
diff --git a/.sdd-progress.md b/.sdd-progress.md
index abed657593..95880441a7 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -31,9 +31,17 @@ fan-out, cancellation, terminal persistence, resume skipping, upstream prompt
context, synthesis fallback and scheduler topology. Its 19 focused tests cover
the O3/O4 behavior matrix; fresh `cargo test -p tinyagents-orchestration` and
root `cargo check -p openhuman` pass. Focused OpenHuman lib tests are currently
-blocked by unrelated fixture migration diagnostics outside workflow runs. O5-O6
-remain: switch the host child-spawn lifecycle fully onto the executor seam,
-then parallel/worktree cleanup.
+blocked by unrelated fixture migration diagnostics outside workflow runs. O5 is
+complete locally: `tinyagents-session` gives workflow rows an atomic owner
+lease and revision/CAS transitions; `tinyagents-orchestration` registers every
+real child id before awaiting it, leases one driver across resume races, emits
+its supplied graph lifecycle sink, and preserves arbitrary JSON outputs.
+OpenHuman's production lifecycle constructs the neutral `WorkflowEngine` over
+`Config.workspace_dir`, enters it under `with_root_parent`, and uses the host
+adapter for policy-admitted `AgentOrchestrationSession` spawning, BUS/progress,
+origin and model override. The old host scheduler/state/phase graph and
+duplicate tests are deleted; topology imports the neutral graph directly. O6
+remains: parallel/worktree cleanup plus final cross-repo review/PR gates.
Session extraction S1-S4: in progress. `tinyagents-session::transcript` owns
the neutral append-only JSONL codec, paths, display/model readers, metadata,
diff --git a/Cargo.lock b/Cargo.lock
index 1af499530a..1b0c9bbd2a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6518,6 +6518,7 @@ dependencies = [
"anyhow",
"async-trait",
"chrono",
+ "parking_lot",
"serde",
"serde_json",
"tinyagents-graph",
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
index 6c02fc64c9..071d321583 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
@@ -51,21 +51,6 @@
mod cancel;
mod lifecycle;
-mod phase_exec;
-mod scheduler;
-mod state;
-
-#[cfg(test)]
-#[path = "engine_tests.rs"]
-mod engine_tests;
-
pub(super) const LOG_TARGET: &str = "workflow_run_engine";
pub use lifecycle::{resume_workflow_run, start_workflow_run, stop_workflow_run};
-pub(crate) use phase_exec::{execute_phase, PhaseExecOutcome};
-pub(crate) use scheduler::{select_next_phase, PhaseSelection};
-
-#[cfg(test)]
-pub(crate) use lifecycle::run_engine_loop;
-#[cfg(test)]
-pub(crate) use state::init_phase_states;
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
index 1767db35a2..9015ddcfc0 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
@@ -3,6 +3,8 @@
use anyhow::{anyhow, Context, Result};
use serde_json::Value;
+use std::sync::Arc;
+use tinyagents_orchestration::workflow::{SessionWorkflowStore, WorkflowEngine};
use crate::agent::orchestration::parent_context::with_root_parent;
use crate::config::Config;
@@ -11,8 +13,9 @@ use tinyagents_session::run_ledger::{
};
use super::super::ops::definition_by_id;
-use super::cancel::{clear_cancel_flag, lookup_cancel_flag, register_cancel_flag};
-use super::state::{init_phase_states, persist};
+use super::cancel::{
+ clear_cancel_flag, lookup_cancel_signal, register_cancel_flag, register_cancel_signal,
+};
use super::LOG_TARGET;
use tinyagents_orchestration::workflow::WorkflowDefinition;
@@ -37,24 +40,15 @@ pub async fn start_workflow_run(
.ok_or_else(|| anyhow!("unknown workflow definition: {definition_id}"))?;
let run_id = format!("wfrun-{}", uuid::Uuid::new_v4());
- let phase_states = init_phase_states(&definition);
-
- let run = upsert_workflow_run(
- &config.workspace_dir,
- WorkflowRunUpsert {
- id: run_id.clone(),
- definition_id: definition.id.clone(),
- parent_thread_id,
- input: input.clone(),
- phase_states,
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: None,
- completed_at: None,
- },
- )
- .context("persist initial workflow run")?;
+ let initial_engine = WorkflowEngine::new(
+ Arc::new(SessionWorkflowStore::new(config.workspace_dir.clone())),
+ Arc::new(super::super::host::OpenHumanWorkflowExecutor::new(
+ &run_id, None,
+ )),
+ );
+ let run = initial_engine
+ .initialise(run_id.clone(), &definition, input.clone(), parent_thread_id)
+ .context("persist initial workflow run")?;
register_cancel_flag(&run_id);
@@ -223,10 +217,36 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu
/// an owned [`Config`]. Errors are recorded on the run row (status `Failed`)
/// rather than propagated — there is no caller to receive them.
pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: WorkflowDefinition) {
- let cancel = lookup_cancel_flag(run_id).unwrap_or_else(|| register_cancel_flag(run_id));
+ let cancel = lookup_cancel_signal(run_id).unwrap_or_else(|| register_cancel_signal(run_id));
+
+ let model_override = get_workflow_run(&config.workspace_dir, run_id)
+ .ok()
+ .flatten()
+ .and_then(|run| {
+ run.input
+ .get("modelOverride")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ })
+ .filter(|model| !model.trim().is_empty());
+ let engine = WorkflowEngine::new(
+ Arc::new(SessionWorkflowStore::new(config.workspace_dir.clone())),
+ Arc::new(super::super::host::OpenHumanWorkflowExecutor::new(
+ run_id,
+ model_override,
+ )),
+ )
+ .with_event_sink(Arc::new(
+ crate::agent::tinyagents::observability::GraphTracingSink::new(format!(
+ "workflow:{run_id}"
+ )),
+ ));
let outcome = with_root_parent(config, "workflow_engine", "workflow", "workflow", async {
- super::super::graph::drive_phases(config, run_id, &definition, &cancel).await
+ engine
+ .drive(run_id, &definition, cancel.token.clone())
+ .await
+ .map_err(anyhow::Error::msg)
})
.await
// Flatten: outer Err = root-parent build failure, inner = drive_phases result.
@@ -246,14 +266,20 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W
| WorkflowRunStatus::Cancelled
| WorkflowRunStatus::Interrupted
) {
- let _ = persist(
- config,
- &run,
- run.phase_states.clone(),
- run.child_run_ids.clone(),
- WorkflowRunStatus::Failed,
- Some(format!("engine error: {err}")),
- true,
+ let _ = upsert_workflow_run(
+ &config.workspace_dir,
+ WorkflowRunUpsert {
+ id: run.id.clone(),
+ definition_id: run.definition_id.clone(),
+ parent_thread_id: run.parent_thread_id.clone(),
+ input: run.input.clone(),
+ phase_states: run.phase_states.clone(),
+ child_run_ids: run.child_run_ids.clone(),
+ status: WorkflowRunStatus::Failed,
+ summary: Some(format!("engine error: {err}")),
+ started_at: Some(run.started_at),
+ completed_at: Some(chrono::Utc::now()),
+ },
);
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/phase_exec.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/phase_exec.rs
deleted file mode 100644
index ec7e95dd1a..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/phase_exec.rs
+++ /dev/null
@@ -1,377 +0,0 @@
-//! `run_phase` step: fan a phase's agents out on the intra-phase tinyagents
-//! graph, aggregate outcomes, and persist the new phase state.
-
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-
-use anyhow::{anyhow, Result};
-use serde_json::{json, Value};
-use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};
-use tinyagents_harness::TinyAgentsError;
-
-use tinyagents_session::run_ledger::{get_workflow_run, WorkflowRunStatus};
-
-use super::cancel::lookup_cancel_token;
-use super::state::{persist, phase_prompt, set_phase_reason, set_phase_status, upstream_outputs};
-use super::state::{PHASE_COMPLETED, PHASE_FAILED, PHASE_RUNNING};
-use super::LOG_TARGET;
-use crate::config::Config;
-use tinyagents_orchestration::workflow::{WorkflowDefinition, WorkflowPhase};
-
-/// One worker's outcome from the intra-phase graph fan-out (see
-/// [`execute_phase`]). Rides in the fan-out graph's typed state, so it is `Clone`.
-#[derive(Clone)]
-struct PhaseWorkerOutcome {
- /// The spawned child's orchestration id, recorded in `child_run_ids`.
- /// `None` when the child was never spawned (cancelled / spawn error).
- orchestration_id: Option<String>,
- /// Completed child's output row appended to the phase outputs.
- output: Option<Value>,
- /// Failure reason when the worker did not complete successfully.
- error: Option<String>,
-}
-
-/// Outcome of executing one phase in the `run_phase` step.
-pub(crate) enum PhaseExecOutcome {
- /// The phase completed; `spawned` children were launched (added to the
- /// run-wide `max_children` tally). Route back to `dispatch`.
- Continue { spawned: u32 },
- /// The run reached a terminal status (already persisted) — route to `done`.
- Terminated,
-}
-
-/// `run_phase` step: mark the phase running, fan its agents out on the
-/// intra-phase tinyagents graph (bounded by `default_concurrency`, capped by the
-/// run-wide `max_children` budget), aggregate outcomes, and persist the new
-/// phase state. Returns [`PhaseExecOutcome::Continue`] with the number of
-/// children spawned, or [`PhaseExecOutcome::Terminated`] when the phase failed or
-/// cancellation landed mid-phase (the terminal status is persisted first).
-#[allow(clippy::too_many_arguments)]
-pub(crate) async fn execute_phase(
- config: &Config,
- run_id: &str,
- definition: &WorkflowDefinition,
- session: &crate::agent::orchestration::AgentOrchestrationSession,
- cancel: &Arc<AtomicBool>,
- model_override: Option<String>,
- phase: &WorkflowPhase,
- total_spawned: u32,
-) -> Result<PhaseExecOutcome> {
- use crate::agent::orchestration::{
- OrchestrationTaskStatus, SpawnAgentRequest, WaitAgentOptions,
- };
-
- // Reload so the phase state we mutate + persist is the latest projection.
- let run = get_workflow_run(&config.workspace_dir, run_id)?
- .ok_or_else(|| anyhow!("workflow run {run_id} vanished mid-phase"))?;
- let mut phase_states = run.phase_states.clone();
- let mut child_run_ids = run.child_run_ids.clone();
- // Children launched *this* phase (the reducer delta added to `total_spawned`).
- let mut spawned_this_phase: u32 = 0;
-
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] phase.start run={run_id} phase={} agents={} spawned_so_far={}",
- phase.name,
- phase.agent_ids.len(),
- total_spawned
- );
- set_phase_status(&mut phase_states, &phase.name, PHASE_RUNNING, None);
- persist(
- config,
- &run,
- phase_states.clone(),
- child_run_ids.clone(),
- WorkflowRunStatus::Running,
- None,
- false,
- )?;
-
- // Thread prior phases' outputs into this phase's prompt context.
- let upstream_context = upstream_outputs(definition, phase, &phase_states);
-
- // Run the phase's agents on a tinyagents graph fan-out (dispatch ->
- // parallel worker nodes bounded by `default_concurrency` -> collect
- // barrier), never exceeding the run-wide `max_children` cap. Each worker
- // spawns one child and waits for its terminal status; outcomes return in
- // phase order.
- let mut phase_outputs: Vec<Value> = Vec::new();
- let mut phase_failed: Option<String> = None;
-
- let concurrency = definition.default_concurrency.max(1) as usize;
- let budget_left = definition.max_children.saturating_sub(total_spawned);
-
- if budget_left == 0 {
- phase_failed = Some(format!(
- "max_children cap ({}) reached before phase '{}' completed",
- definition.max_children, phase.name
- ));
- } else {
- // Cap this phase to the run-wide `max_children` budget; if the phase
- // needs more workers than the budget allows we run as many as fit
- // and then fail with the cap message (matching the legacy loop).
- let capacity = budget_left as usize;
- let phase_agents = phase.agent_ids.to_vec();
- let capped = phase_agents.len() > capacity;
- let to_run: Vec<(usize, String)> = phase_agents
- .into_iter()
- .take(capacity)
- .enumerate()
- .collect();
-
- // Clones moved into the (`'static`) worker closure.
- let session_for_workers = session.clone();
- let cancel_for_workers = cancel.clone();
- let run_input = run.input.clone();
- let phase_owned = phase.clone();
- let upstream_owned = upstream_context.clone();
- let model_for_workers = model_override.clone();
-
- tracing::debug!(
- target: "orchestration",
- workers = to_run.len(),
- max_concurrency = concurrency,
- "[orchestration] running parallel fan-out on tinyagents map_reduce (workflow:{run_id}:{})",
- phase_owned.name
- );
- let expected_outcomes = to_run.len();
- let mut options = ParallelOptions::default()
- .with_max_concurrency(concurrency)
- .with_failure_policy(FailurePolicy::CollectAll);
- if let Some(token) = lookup_cancel_token(run_id) {
- options = options.with_cancellation(token);
- }
- let outcome = match map_reduce(to_run, options, move |_node, (agent_index, agent_id)| {
- let session = session_for_workers.clone();
- let cancel = cancel_for_workers.clone();
- let run_input = run_input.clone();
- let phase = phase_owned.clone();
- let upstream = upstream_owned.clone();
- let model = model_for_workers.clone();
- async move {
- // Don't launch new children once cancellation has landed.
- if cancel.load(Ordering::SeqCst) {
- return Ok(PhaseWorkerOutcome {
- orchestration_id: None,
- output: None,
- error: Some("cancelled before spawn".to_string()),
- });
- }
- let prompt = phase_prompt(&run_input, &phase, agent_index, &upstream);
- let resp = match session
- .spawn_agent(SpawnAgentRequest {
- agent_id: agent_id.clone(),
- prompt,
- model,
- ..Default::default()
- })
- .await
- {
- Ok(resp) => resp,
- Err(err) => {
- return Ok(PhaseWorkerOutcome {
- orchestration_id: None,
- output: None,
- error: Some(format!("spawn failed for agent '{agent_id}': {err}")),
- });
- }
- };
- let oid = resp.orchestration_id.clone();
- let wait = match session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![oid.clone()],
- timeout_ms: None,
- })
- .await
- {
- Ok(w) => w,
- Err(err) => {
- return Ok(PhaseWorkerOutcome {
- orchestration_id: Some(oid),
- output: None,
- error: Some(format!("wait_agents failed: {err}")),
- });
- }
- };
- Ok(match wait.agents.into_iter().next() {
- Some(s) => match s.status {
- OrchestrationTaskStatus::Completed => PhaseWorkerOutcome {
- orchestration_id: Some(oid),
- output: Some(json!({
- "orchestrationId": s.orchestration_id,
- "agentId": s.agent_id,
- "output": s.result_summary.clone().unwrap_or_default(),
- })),
- error: None,
- },
- OrchestrationTaskStatus::Failed
- | OrchestrationTaskStatus::Cancelled
- | OrchestrationTaskStatus::CancelRequested
- | OrchestrationTaskStatus::TimedOut
- | OrchestrationTaskStatus::Abandoned => PhaseWorkerOutcome {
- orchestration_id: Some(oid),
- output: None,
- error: Some(format!(
- "child '{}' (agent '{}') ended {}: {}",
- s.orchestration_id,
- s.agent_id,
- serde_json::to_value(s.status)
- .ok()
- .and_then(|v| v.as_str().map(str::to_string))
- .unwrap_or_else(|| "non-completed".to_string()),
- s.error.clone().unwrap_or_default()
- )),
- },
- OrchestrationTaskStatus::Pending
- | OrchestrationTaskStatus::Running
- | OrchestrationTaskStatus::Awaiting => PhaseWorkerOutcome {
- orchestration_id: Some(oid),
- output: None,
- error: Some(format!(
- "child '{}' returned non-terminal status",
- s.orchestration_id
- )),
- },
- },
- None => PhaseWorkerOutcome {
- orchestration_id: Some(oid),
- output: None,
- error: Some("child returned no snapshot".to_string()),
- },
- })
- }
- })
- .await
- {
- Ok(outcome) => outcome,
- Err(TinyAgentsError::Cancelled) => {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] phase.cancelled_by_sdk run={run_id} phase={}",
- phase.name
- );
- session.abort_all().await;
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Interrupted,
- None,
- false,
- )?;
- return Ok(PhaseExecOutcome::Terminated);
- }
- Err(err) => return Err(anyhow!("workflow fan-out failed: {err}")),
- };
-
- let mut outcomes = Vec::with_capacity(expected_outcomes);
- for item in outcome.outcomes {
- match item.result {
- Ok(value) => outcomes.push(value),
- Err(err) => {
- return Err(anyhow!(
- "workflow fan-out: worker {} failed: {err}",
- item.index
- ));
- }
- }
- }
- if outcomes.len() != expected_outcomes {
- return Err(anyhow!(
- "workflow fan-out: expected {expected_outcomes} result(s), got {}",
- outcomes.len()
- ));
- }
-
- // Aggregate worker outcomes in phase order: record every spawned
- // child id, collect completed outputs, and surface the first failure.
- for outcome in outcomes {
- if let Some(oid) = outcome.orchestration_id {
- spawned_this_phase += 1;
- child_run_ids.push(oid);
- }
- match outcome.output {
- Some(out) => phase_outputs.push(out),
- None => {
- if phase_failed.is_none() {
- phase_failed = outcome.error;
- }
- }
- }
- }
-
- // Cancellation landed mid-phase: abort stragglers and interrupt.
- if cancel.load(Ordering::SeqCst) {
- session.abort_all().await;
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Interrupted,
- None,
- false,
- )?;
- return Ok(PhaseExecOutcome::Terminated);
- }
-
- if capped && phase_failed.is_none() {
- phase_failed = Some(format!(
- "max_children cap ({}) reached before phase '{}' completed",
- definition.max_children, phase.name
- ));
- }
- }
-
- if let Some(reason) = phase_failed {
- log::warn!(
- target: LOG_TARGET,
- "[workflow_run_engine] phase.failed run={run_id} phase={} reason={reason}",
- phase.name
- );
- set_phase_status(
- &mut phase_states,
- &phase.name,
- PHASE_FAILED,
- Some(json!([])),
- );
- set_phase_reason(&mut phase_states, &phase.name, &reason);
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Failed,
- Some(reason),
- true,
- )?;
- return Ok(PhaseExecOutcome::Terminated);
- }
-
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] phase.done run={run_id} phase={} outputs={}",
- phase.name,
- phase_outputs.len()
- );
- set_phase_status(
- &mut phase_states,
- &phase.name,
- PHASE_COMPLETED,
- Some(Value::Array(phase_outputs)),
- );
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Running,
- None,
- false,
- )?;
-
- Ok(PhaseExecOutcome::Continue {
- spawned: spawned_this_phase,
- })
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/scheduler.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/scheduler.rs
deleted file mode 100644
index a798c331f3..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/scheduler.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-//! `dispatch` step of the phase loop: reload the run, honour cancellation,
-//! and pick the next runnable phase.
-
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-
-use anyhow::{anyhow, Result};
-
-use tinyagents_session::run_ledger::{get_workflow_run, WorkflowRunStatus};
-
-use super::state::{all_phases_completed, next_runnable_phase, persist, synthesize_summary};
-use super::LOG_TARGET;
-use crate::config::Config;
-use tinyagents_orchestration::workflow::{WorkflowDefinition, WorkflowPhase};
-
-/// What the scheduler's `dispatch` step decided.
-pub(crate) enum PhaseSelection {
- /// Execute this phase next.
- Run(WorkflowPhase),
- /// The run reached a terminal status (already persisted) — route to `done`.
- Terminated,
-}
-
-/// `dispatch` step: reload the run, honour cancellation, and pick the next
-/// runnable phase (pending, all deps `completed`). When none remains, persist the
-/// terminal status (Completed / Failed) and return [`PhaseSelection::Terminated`].
-pub(crate) async fn select_next_phase(
- config: &Config,
- run_id: &str,
- definition: &WorkflowDefinition,
- cancel: &Arc<AtomicBool>,
- session: &crate::agent::orchestration::AgentOrchestrationSession,
-) -> Result<PhaseSelection> {
- // Reload so we read the latest phase_states (and a resume picks up persisted
- // progress).
- let run = get_workflow_run(&config.workspace_dir, run_id)?
- .ok_or_else(|| anyhow!("workflow run {run_id} vanished mid-loop"))?;
- let phase_states = run.phase_states.clone();
- let child_run_ids = run.child_run_ids.clone();
-
- // Cancellation check between phases.
- if cancel.load(Ordering::SeqCst) {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] loop.cancelled run={run_id}"
- );
- session.abort_all().await;
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Interrupted,
- None,
- false,
- )?;
- return Ok(PhaseSelection::Terminated);
- }
-
- // Find the next runnable phase: pending, with all deps completed.
- let Some(phase) = next_runnable_phase(definition, &phase_states) else {
- // No runnable phase left. Either everything is done, or we're blocked
- // (which a validated DAG shouldn't be).
- if all_phases_completed(definition, &phase_states) {
- let summary = synthesize_summary(definition, &phase_states);
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] loop.completed run={run_id} summary_chars={}",
- summary.as_deref().map(str::len).unwrap_or(0)
- );
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Completed,
- summary,
- true,
- )?;
- } else {
- log::warn!(
- target: LOG_TARGET,
- "[workflow_run_engine] loop.stuck run={run_id} no_runnable_phase"
- );
- persist(
- config,
- &run,
- phase_states,
- child_run_ids,
- WorkflowRunStatus::Failed,
- Some("no runnable phase (dependency deadlock)".to_string()),
- true,
- )?;
- }
- return Ok(PhaseSelection::Terminated);
- };
-
- Ok(PhaseSelection::Run(phase.clone()))
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/state.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/state.rs
deleted file mode 100644
index 032d12e987..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/state.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-//! Phase-state helpers: the `phase_states` JSON column shape, the dependency
-//! walk that picks the next runnable phase, upstream-output threading into a
-//! child's prompt, run-summary synthesis, and the shared `persist` write.
-
-use anyhow::{Context, Result};
-use serde_json::{json, Value};
-
-use tinyagents_session::run_ledger::{
- upsert_workflow_run, WorkflowRun, WorkflowRunStatus, WorkflowRunUpsert,
-};
-
-use crate::config::Config;
-use tinyagents_orchestration::workflow::{WorkflowDefinition, WorkflowPhase};
-
-/// Per-phase status stored inside the run's `phase_states` JSON column.
-pub(super) const PHASE_PENDING: &str = "pending";
-pub(super) const PHASE_RUNNING: &str = "running";
-pub(super) const PHASE_COMPLETED: &str = "completed";
-pub(super) const PHASE_FAILED: &str = "failed";
-
-/// Initialise `phase_states` to one `pending` entry per phase, preserving
-/// declaration order via an object keyed by phase name.
-pub(crate) fn init_phase_states(definition: &WorkflowDefinition) -> Value {
- let mut map = serde_json::Map::new();
- for phase in &definition.phases {
- map.insert(
- phase.name.clone(),
- json!({ "status": PHASE_PENDING, "outputs": [] }),
- );
- }
- Value::Object(map)
-}
-
-pub(super) fn phase_status<'a>(phase_states: &'a Value, name: &str) -> Option<&'a str> {
- phase_states
- .get(name)
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str)
-}
-
-pub(super) fn set_phase_status(
- phase_states: &mut Value,
- name: &str,
- status: &str,
- outputs: Option<Value>,
-) {
- if let Some(obj) = phase_states.as_object_mut() {
- let entry = obj
- .entry(name.to_string())
- .or_insert_with(|| json!({ "status": PHASE_PENDING, "outputs": [] }));
- if let Some(entry_obj) = entry.as_object_mut() {
- entry_obj.insert("status".to_string(), json!(status));
- if let Some(out) = outputs {
- entry_obj.insert("outputs".to_string(), out);
- }
- }
- }
-}
-
-pub(super) fn set_phase_reason(phase_states: &mut Value, name: &str, reason: &str) {
- if let Some(obj) = phase_states.as_object_mut() {
- if let Some(entry) = obj.get_mut(name).and_then(Value::as_object_mut) {
- entry.insert("reason".to_string(), json!(reason));
- }
- }
-}
-
-/// The first phase that is `pending` (or missing) and whose every dependency is
-/// `completed`. Definition order breaks ties so the walk is deterministic.
-pub(super) fn next_runnable_phase<'a>(
- definition: &'a WorkflowDefinition,
- phase_states: &Value,
-) -> Option<&'a WorkflowPhase> {
- definition.phases.iter().find(|phase| {
- let status = phase_status(phase_states, &phase.name).unwrap_or(PHASE_PENDING);
- if status == PHASE_COMPLETED || status == PHASE_RUNNING {
- return false;
- }
- phase
- .depends_on
- .iter()
- .all(|dep| phase_status(phase_states, dep) == Some(PHASE_COMPLETED))
- })
-}
-
-pub(super) fn all_phases_completed(definition: &WorkflowDefinition, phase_states: &Value) -> bool {
- definition
- .phases
- .iter()
- .all(|phase| phase_status(phase_states, &phase.name) == Some(PHASE_COMPLETED))
-}
-
-/// Collect the outputs of every completed phase this phase depends on, so they
-/// can be threaded into the downstream prompt.
-pub(super) fn upstream_outputs(
- _definition: &WorkflowDefinition,
- phase: &WorkflowPhase,
- phase_states: &Value,
-) -> Vec<Value> {
- let mut out = Vec::new();
- for dep in &phase.depends_on {
- if let Some(outputs) = phase_states
- .get(dep)
- .and_then(|p| p.get("outputs"))
- .and_then(Value::as_array)
- {
- for item in outputs {
- if let Some(text) = item.get("output").and_then(Value::as_str) {
- if !text.trim().is_empty() {
- out.push(json!({ "phase": dep, "output": text }));
- }
- }
- }
- }
- }
- out
-}
-
-/// Build the prompt for one child in a phase: the run input + the phase's
-/// description + upstream outputs threaded in as context.
-pub(super) fn phase_prompt(
- input: &Value,
- phase: &WorkflowPhase,
- index_in_phase: usize,
- upstream: &[Value],
-) -> String {
- let question = input
- .get("question")
- .or_else(|| input.get("input"))
- .and_then(Value::as_str)
- .map(str::to_string)
- .unwrap_or_else(|| input.to_string());
-
- let mut prompt = format!(
- "Workflow phase: {}\n{}\n\nInput:\n{}\n",
- phase.name, phase.description, question
- );
- if phase.agent_ids.len() > 1 {
- prompt.push_str(&format!(
- "\n(You are worker #{} in this phase.)\n",
- index_in_phase + 1
- ));
- }
- if !upstream.is_empty() {
- prompt.push_str("\nContext from prior phases:\n");
- for item in upstream {
- if let (Some(p), Some(o)) = (
- item.get("phase").and_then(Value::as_str),
- item.get("output").and_then(Value::as_str),
- ) {
- prompt.push_str(&format!("- [{p}] {o}\n"));
- }
- }
- }
- prompt
-}
-
-/// The synthesize phase's combined output becomes the run summary. Falls back
-/// to the last completed phase's output if no phase is literally named
-/// `synthesize`.
-pub(super) fn synthesize_summary(
- definition: &WorkflowDefinition,
- phase_states: &Value,
-) -> Option<String> {
- let pick = |name: &str| -> Option<String> {
- let outputs = phase_states
- .get(name)
- .and_then(|p| p.get("outputs"))
- .and_then(Value::as_array)?;
- let joined = outputs
- .iter()
- .filter_map(|o| o.get("output").and_then(Value::as_str))
- .filter(|s| !s.trim().is_empty())
- .collect::<Vec<_>>()
- .join("\n");
- (!joined.trim().is_empty()).then_some(joined)
- };
-
- if let Some(summary) = pick("synthesize") {
- return Some(summary);
- }
- // Fall back to the last phase in declaration order with non-empty output.
- definition
- .phases
- .iter()
- .rev()
- .find_map(|phase| pick(&phase.name))
-}
-
-/// Persist a run-state update. `terminal` controls whether `completed_at` is
-/// stamped.
-#[allow(clippy::too_many_arguments)]
-pub(super) fn persist(
- config: &Config,
- run: &WorkflowRun,
- phase_states: Value,
- child_run_ids: Vec<String>,
- status: WorkflowRunStatus,
- summary: Option<String>,
- terminal: bool,
-) -> Result<WorkflowRun> {
- upsert_workflow_run(
- &config.workspace_dir,
- WorkflowRunUpsert {
- id: run.id.clone(),
- definition_id: run.definition_id.clone(),
- parent_thread_id: run.parent_thread_id.clone(),
- input: run.input.clone(),
- phase_states,
- child_run_ids,
- status,
- summary,
- started_at: Some(run.started_at),
- completed_at: terminal.then(chrono::Utc::now),
- },
- )
- .context("persist workflow run state")
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_tests.rs
deleted file mode 100644
index 79797e7afd..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_tests.rs
+++ /dev/null
@@ -1,555 +0,0 @@
-//! Engine unit tests (#3375 PR2).
-//!
-//! These exercise the phase scheduler ([`super::super::graph::drive_phases`]) directly with a
-//! mock `ChatModel` so child agents resolve deterministically and never touch the
-//! network. The full [`super::start_workflow_run`] entry point (which builds a
-//! real `Agent` from config) is covered by the JSON-RPC e2e test over the live
-//! core stack with the mock backend.
-//!
-//! Test strategy: install a mock [`ParentExecutionContext`] via
-//! [`with_parent_context`] (mirroring `agent_orchestration::ops_tests`), seed a
-//! `Running` workflow-run row in a tempdir-backed ledger, then drive a custom
-//! definition and assert on the persisted `phase_states` + run status.
-
-use std::collections::HashSet;
-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use parking_lot::Mutex;
-use serde_json::{json, Value};
-use tokio::time::{sleep, Duration};
-
-use super::*;
-// The phase scheduler moved to the tinyagents-backed `graph` submodule in #4249;
-// its signature is unchanged (`drive_phases(config, run_id, definition, cancel)`).
-use super::super::graph::drive_phases;
-use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext};
-use crate::agent::prompts::ToolCallFormat;
-use crate::config::{AgentConfig, Config};
-use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
-use tinyagents_session::run_ledger::WorkflowRunStatus;
-use tinyagents_session::run_ledger::{get_workflow_run, upsert_workflow_run, WorkflowRunUpsert};
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
-use tinytools::Tool;
-
-use std::collections::BTreeMap;
-use tinyagents_orchestration::workflow::{WorkflowDefinition, WorkflowPhase};
-
-// ── Mocks (mirrors agent_orchestration::ops_tests) ──────────────────────────
-
-#[derive(Default)]
-struct NoopMemory;
-
-#[async_trait]
-impl Memory for NoopMemory {
- async fn store(
- &self,
- _namespace: &str,
- _key: &str,
- _content: &str,
- _category: MemoryCategory,
- _session_id: Option<&str>,
- ) -> anyhow::Result<()> {
- Ok(())
- }
- async fn recall(
- &self,
- _query: &str,
- _limit: usize,
- _opts: RecallOpts<'_>,
- ) -> anyhow::Result<Vec<MemoryEntry>> {
- Ok(Vec::new())
- }
- async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result<Option<MemoryEntry>> {
- Ok(None)
- }
- async fn list(
- &self,
- _namespace: Option<&str>,
- _category: Option<&MemoryCategory>,
- _session_id: Option<&str>,
- ) -> anyhow::Result<Vec<MemoryEntry>> {
- Ok(Vec::new())
- }
- async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result<bool> {
- Ok(false)
- }
- async fn namespace_summaries(&self) -> anyhow::Result<Vec<NamespaceSummary>> {
- Ok(Vec::new())
- }
- async fn count(&self) -> anyhow::Result<usize> {
- Ok(0)
- }
- async fn health_check(&self) -> bool {
- true
- }
- fn name(&self) -> &str {
- "noop"
- }
-}
-
-fn text_response(text: impl Into<String>) -> ModelResponse {
- ModelResponse::assistant(text)
-}
-
-/// Mock model that records peak concurrency and answers each child with a
-/// short deterministic completion. Sleeps briefly so overlapping spawns are
-/// observable for the concurrency-cap assertions.
-#[derive(Clone, Default)]
-struct PeakModel {
- calls: Arc<AtomicUsize>,
- active: Arc<AtomicUsize>,
- max_active: Arc<AtomicUsize>,
- prompts: Arc<Mutex<Vec<String>>>,
- fail_on: Arc<Mutex<Option<String>>>,
-}
-
-impl PeakModel {
- fn calls(&self) -> usize {
- self.calls.load(Ordering::SeqCst)
- }
- fn max_active(&self) -> usize {
- self.max_active.load(Ordering::SeqCst)
- }
- fn fail_when_prompt_contains(&self, needle: &str) {
- *self.fail_on.lock() = Some(needle.to_string());
- }
- fn record_peak(&self, current: usize) {
- let mut observed = self.max_active.load(Ordering::SeqCst);
- while current > observed {
- match self.max_active.compare_exchange(
- observed,
- current,
- Ordering::SeqCst,
- Ordering::SeqCst,
- ) {
- Ok(_) => break,
- Err(next) => observed = next,
- }
- }
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for PeakModel {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- let current = self.active.fetch_add(1, Ordering::SeqCst) + 1;
- self.record_peak(current);
- sleep(Duration::from_millis(40)).await;
- let flattened = request
- .messages
- .iter()
- .map(|message| message.text())
- .collect::<Vec<_>>()
- .join("\n");
- self.prompts.lock().push(flattened.clone());
- self.active.fetch_sub(1, Ordering::SeqCst);
-
- if let Some(needle) = self.fail_on.lock().as_ref() {
- if flattened.contains(needle.as_str()) {
- return Err(tinyinference_llm::Error::Model(
- "mock model forced failure".to_string(),
- ));
- }
- }
- Ok(text_response("PHASE_OUTPUT_OK"))
- }
-}
-
-fn mock_parent(model: Arc<dyn ChatModel<()>>) -> ParentExecutionContext {
- ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "workflow_engine".to_string(),
- allowed_subagent_ids: HashSet::new(),
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model_with_profile(
- model,
- ModelProfile {
- tool_calling: true,
- parallel_tool_calls: true,
- ..ModelProfile::default()
- },
- ),
- all_tools: Arc::new(Vec::<Box<dyn Tool>>::new()),
- all_tool_specs: Arc::new(Vec::new()),
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".to_string(),
- temperature: 0.2,
- workspace_dir: std::env::temp_dir(),
- memory: Arc::new(NoopMemory),
- agent_config: AgentConfig::default(),
- workflows: Arc::new(Vec::new()),
- memory_context: Arc::new(None),
- session_id: "workflow-engine-test".to_string(),
- channel: "test".to_string(),
- connected_integrations: Vec::new(),
- tool_call_format: ToolCallFormat::PFormat,
- session_key: "0_workflow_engine".to_string(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- }
-}
-
-fn test_config() -> (tempfile::TempDir, Config) {
- let dir = tempfile::tempdir().expect("tempdir");
- let config = Config {
- workspace_dir: dir.path().to_path_buf(),
- ..Config::default()
- };
- (dir, config)
-}
-
-/// Seed a `Running` workflow run row for `definition`, returning its id.
-fn seed_run(config: &Config, definition: &WorkflowDefinition, input: Value) -> String {
- let id = format!("wfrun-test-{}", uuid::Uuid::new_v4());
- upsert_workflow_run(
- &config.workspace_dir,
- WorkflowRunUpsert {
- id: id.clone(),
- definition_id: definition.id.clone(),
- parent_thread_id: None,
- input,
- phase_states: init_phase_states(definition),
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: None,
- completed_at: None,
- },
- )
- .expect("seed run");
- id
-}
-
-/// A linear A→B→C definition using `code_executor` (a builtin leaf agent), with
-/// `concurrency` workers in phase B.
-fn linear_def(concurrency: u32, max_children: u32, parallel_in_b: usize) -> WorkflowDefinition {
- WorkflowDefinition {
- id: "test_linear".to_string(),
- name: "test linear".to_string(),
- description: "A then parallel B then C".to_string(),
- phases: vec![
- WorkflowPhase {
- name: "a".to_string(),
- description: "phase a".to_string(),
- agent_ids: vec!["code_executor".to_string()],
- depends_on: vec![],
- },
- WorkflowPhase {
- name: "b".to_string(),
- description: "phase b PARALLEL".to_string(),
- agent_ids: vec!["code_executor".to_string(); parallel_in_b],
- depends_on: vec!["a".to_string()],
- },
- WorkflowPhase {
- name: "c".to_string(),
- description: "phase c synthesize".to_string(),
- agent_ids: vec!["code_executor".to_string()],
- depends_on: vec!["b".to_string()],
- },
- ],
- default_concurrency: concurrency,
- max_children,
- extensions: BTreeMap::new(),
- }
-}
-
-fn status_of(config: &Config, id: &str) -> WorkflowRunStatus {
- get_workflow_run(&config.workspace_dir, id)
- .unwrap()
- .unwrap()
- .status
-}
-
-fn phase_states(config: &Config, id: &str) -> Value {
- get_workflow_run(&config.workspace_dir, id)
- .unwrap()
- .unwrap()
- .phase_states
-}
-
-// ── Tests ───────────────────────────────────────────────────────────────────
-
-#[tokio::test]
-async fn unit_phases_execute_in_dependency_order() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- let def = linear_def(2, 8, 2);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "what is X?", "modelOverride": "test-model" }),
- );
- let cancel = Arc::new(AtomicBool::new(false));
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases ok");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Completed);
- let states = phase_states(&config, &id);
- for phase in ["a", "b", "c"] {
- assert_eq!(
- states
- .get(phase)
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str),
- Some("completed"),
- "phase {phase} should be completed: {states}"
- );
- }
- // 1 (a) + 2 (b) + 1 (c) = 4 children executed.
- assert_eq!(provider.calls(), 4, "all four children should run");
-
- // Summary comes from the last phase's output (no phase literally named
- // 'synthesize', so the fallback picks phase c).
- let summary = get_workflow_run(&config.workspace_dir, &id)
- .unwrap()
- .unwrap()
- .summary;
- assert!(
- summary
- .as_deref()
- .unwrap_or_default()
- .contains("PHASE_OUTPUT_OK"),
- "summary should carry final phase output: {summary:?}"
- );
-}
-
-/// Covers `run_engine_loop` — the `with_root_parent` wrapper around
-/// `drive_phases`. With a mock parent installed, `with_root_parent` reuses it
-/// (rather than building a real root), so the engine loop drives the run to
-/// completion under the mock model. Mirrors the `drive_phases` happy path,
-/// but through the wrapper the live engine spawns on its background task.
-#[tokio::test]
-async fn run_engine_loop_completes_run_under_ambient_parent() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- let def = linear_def(2, 8, 2);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "what is X?", "modelOverride": "test-model" }),
- );
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- run_engine_loop(&config, &id, def).await
- })
- .await;
-
- assert_eq!(
- status_of(&config, &id),
- WorkflowRunStatus::Completed,
- "run_engine_loop drove the run to completion through with_root_parent"
- );
-}
-
-#[tokio::test]
-async fn unit_concurrency_cap_is_respected() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- // 4 parallel workers in phase b, but concurrency capped at 2.
- let def = linear_def(2, 16, 4);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "q", "modelOverride": "test-model" }),
- );
- let cancel = Arc::new(AtomicBool::new(false));
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases ok");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Completed);
- assert!(
- provider.max_active() <= 2,
- "concurrency cap of 2 exceeded: peak={}",
- provider.max_active()
- );
-}
-
-#[tokio::test]
-async fn unit_max_children_hard_cap_fails_run() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- // a(1) + b(4) = 5 needed, but max_children = 3 → run fails in phase b.
- let def = linear_def(2, 3, 4);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "q", "modelOverride": "test-model" }),
- );
- let cancel = Arc::new(AtomicBool::new(false));
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases returns Ok with terminal Failed state");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Failed);
- let summary = get_workflow_run(&config.workspace_dir, &id)
- .unwrap()
- .unwrap()
- .summary;
- assert!(
- summary
- .as_deref()
- .unwrap_or_default()
- .contains("max_children"),
- "failure reason should mention max_children: {summary:?}"
- );
- // Phase a completed before the cap bit; partial state preserved.
- let states = phase_states(&config, &id);
- assert_eq!(
- states
- .get("a")
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str),
- Some("completed")
- );
-}
-
-#[tokio::test]
-async fn unit_failed_child_marks_run_failed_with_partial_state() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- // Force the phase-b child to fail (its prompt mentions "PARALLEL").
- provider.fail_when_prompt_contains("phase b PARALLEL");
- let def = linear_def(2, 8, 1);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "q", "modelOverride": "test-model" }),
- );
- let cancel = Arc::new(AtomicBool::new(false));
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases returns Ok with terminal Failed state");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Failed);
- let states = phase_states(&config, &id);
- assert_eq!(
- states
- .get("a")
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str),
- Some("completed"),
- "phase a should have completed before b failed"
- );
- assert_eq!(
- states
- .get("b")
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str),
- Some("failed")
- );
- assert_eq!(
- states
- .get("c")
- .and_then(|p| p.get("status"))
- .and_then(Value::as_str),
- Some("pending"),
- "phase c never ran"
- );
-}
-
-#[tokio::test]
-async fn unit_stop_mid_run_marks_interrupted() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- let def = linear_def(2, 8, 1);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "q", "modelOverride": "test-model" }),
- );
- // Pre-flip the cancel flag so the loop interrupts before the first phase.
- let cancel = Arc::new(AtomicBool::new(true));
-
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases ok");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Interrupted);
- // No children ran — cancellation was checked before the first phase.
- assert_eq!(provider.calls(), 0);
-}
-
-#[tokio::test]
-async fn unit_resume_skips_completed_phases() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let (_dir, config) = test_config();
- let provider = PeakModel::default();
- let def = linear_def(2, 8, 1);
- let id = seed_run(
- &config,
- &def,
- json!({ "question": "q", "modelOverride": "test-model" }),
- );
-
- // Mark phase 'a' already completed (simulating a prior partial run).
- let run = get_workflow_run(&config.workspace_dir, &id)
- .unwrap()
- .unwrap();
- let mut states = run.phase_states.clone();
- states["a"]["status"] = json!("completed");
- states["a"]["outputs"] =
- json!([{ "orchestrationId": "x", "agentId": "code_executor", "output": "A_DONE" }]);
- upsert_workflow_run(
- &config.workspace_dir,
- WorkflowRunUpsert {
- id: id.clone(),
- definition_id: run.definition_id.clone(),
- parent_thread_id: None,
- input: run.input.clone(),
- phase_states: states,
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: Some(run.started_at),
- completed_at: None,
- },
- )
- .unwrap();
-
- let cancel = Arc::new(AtomicBool::new(false));
- with_parent_context(mock_parent(Arc::new(provider.clone())), async {
- drive_phases(&config, &id, &def, &cancel).await
- })
- .await
- .expect("drive_phases ok");
-
- assert_eq!(status_of(&config, &id), WorkflowRunStatus::Completed);
- // Only phases b and c run on resume (a was already completed): 2 calls.
- assert_eq!(
- provider.calls(),
- 2,
- "resume must skip the completed phase a"
- );
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/graph.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/graph.rs
deleted file mode 100644
index 17ed7db0af..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/graph.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-//! The **workflow scheduler graph** (issue #4249, Phase 4).
-//!
-//! This is the `workflow_runs` folder's `graph.rs` per the per-folder graph
-//! convention: the durable workflow run's phase-DAG scheduler expressed as a
-//! `tinyagents` conditional-routing graph. A `dispatch` node selects the next
-//! runnable phase and a `run_phase` node executes it, looping
-//! `dispatch ⇄ run_phase` until no phase remains, then routing to `done`.
-//!
-//! The phase-execution logic (`select_next_phase`, `execute_phase`) and the run
-//! lifecycle (`start_workflow_run` / `stop_workflow_run` / `resume_workflow_run`)
-//! stay in [`super::engine`]; this module owns only the graph state machine that
-//! drives them. The two engine effects are **injected** as closures
-//! ([`build_scheduler_graph`]) so the structure has one definition shared by the
-//! live runner and the structure-only [`scheduler_graph_topology`] export.
-
-use std::future::Future;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-
-use anyhow::{anyhow, Result};
-use serde_json::Value;
-use tinyagents_graph::export::GraphTopology;
-use tinyagents_graph::recursion::RecursionPolicy;
-use tinyagents_graph::{
- ClosureStateReducer, Command, CompiledGraph, GraphBuilder, NodeContext, NodeResult,
-};
-
-use crate::config::Config;
-use tinyagents_session::run_ledger::get_workflow_run;
-
-use super::engine::{execute_phase, select_next_phase, PhaseExecOutcome, PhaseSelection};
-use tinyagents_orchestration::workflow::{WorkflowDefinition, WorkflowPhase};
-
-/// Lift an engine-internal `anyhow` error into the scheduler graph's error type
-/// so a ledger-write/spawn failure fails the run (and propagates back out via
-/// [`drive_phases`]). A *phase* that merely failed is not an error here — it is a
-/// normal `Terminated` outcome that persists `Failed` and routes to `done`.
-fn graph_err(e: anyhow::Error) -> tinyagents_harness::TinyAgentsError {
- tinyagents_harness::TinyAgentsError::Graph(e.to_string())
-}
-
-/// Typed state threaded through the scheduler graph: the phase `dispatch`
-/// selected for `run_phase`, and the running tally of spawned children (the
-/// `max_children` budget counter, carried across the dispatch⇄run_phase cycle).
-#[derive(Clone, Default)]
-struct SchedulerState {
- phase: Option<WorkflowPhase>,
- total_spawned: u32,
-}
-
-/// Reducer updates emitted by the scheduler graph nodes.
-enum SchedulerUpdate {
- /// `dispatch` chose the next phase to run.
- SelectPhase(WorkflowPhase),
- /// `run_phase` spawned this many children; fold into `total_spawned`.
- AddSpawned(u32),
- /// Terminal node fired; no state change.
- Noop,
-}
-
-/// Build (but do not run) the scheduler `CompiledGraph`. Shared by
-/// [`drive_phases`] and [`scheduler_graph_topology`] so the graph's structure
-/// has one definition. `select` and `run` are the injected engine effects:
-/// production captures the run's config/ledger session; the topology export
-/// passes no-op stubs.
-fn build_scheduler_graph<S, SF, R, RF>(
- phase_count: usize,
- select: S,
- run: R,
-) -> Result<CompiledGraph<SchedulerState, SchedulerUpdate>>
-where
- S: Fn() -> SF + Clone + Send + Sync + 'static,
- SF: Future<Output = Result<PhaseSelection>> + Send + 'static,
- R: Fn(WorkflowPhase, u32) -> RF + Clone + Send + Sync + 'static,
- RF: Future<Output = Result<PhaseExecOutcome>> + Send + 'static,
-{
- let mut builder = GraphBuilder::<SchedulerState, SchedulerUpdate>::new().set_reducer(
- ClosureStateReducer::new(|mut s: SchedulerState, u: SchedulerUpdate| {
- match u {
- SchedulerUpdate::SelectPhase(p) => s.phase = Some(p),
- SchedulerUpdate::AddSpawned(n) => s.total_spawned += n,
- SchedulerUpdate::Noop => {}
- }
- Ok(s)
- }),
- );
-
- // `dispatch`: pick the next runnable phase, or terminate (already persisted).
- builder = builder.add_node("dispatch", move |_s: SchedulerState, _c: NodeContext| {
- let select = select.clone();
- async move {
- match select().await.map_err(graph_err)? {
- PhaseSelection::Run(phase) => Ok(NodeResult::Command(
- Command::default()
- .with_update(SchedulerUpdate::SelectPhase(phase))
- .with_goto(["run_phase"]),
- )),
- PhaseSelection::Terminated => {
- Ok(NodeResult::Command(Command::default().with_goto(["done"])))
- }
- }
- }
- });
-
- // `run_phase`: execute the selected phase, then loop back to `dispatch` or
- // terminate (on phase failure / mid-phase cancellation).
- builder = builder.add_node("run_phase", move |s: SchedulerState, _c: NodeContext| {
- let run = run.clone();
- async move {
- let phase = s.phase.clone().ok_or_else(|| {
- tinyagents_harness::TinyAgentsError::Graph(
- "workflow run_phase reached with no selected phase".to_string(),
- )
- })?;
- match run(phase, s.total_spawned).await.map_err(graph_err)? {
- PhaseExecOutcome::Continue { spawned } => Ok(NodeResult::Command(
- Command::default()
- .with_update(SchedulerUpdate::AddSpawned(spawned))
- .with_goto(["dispatch"]),
- )),
- PhaseExecOutcome::Terminated => {
- Ok(NodeResult::Command(Command::default().with_goto(["done"])))
- }
- }
- }
- });
-
- let graph = builder
- .add_node("done", |_s: SchedulerState, _c: NodeContext| async move {
- Ok(NodeResult::Update(SchedulerUpdate::Noop))
- })
- .set_entry("dispatch")
- .mark_command_routing("dispatch")
- .mark_command_routing("run_phase")
- .set_finish("done")
- .compile()
- .map_err(|e| anyhow!("workflow scheduler graph compile failed: {e}"))?
- // Bound the dispatch⇄run_phase cycle as a backstop to the DAG's own
- // termination: `dispatch` is visited once per phase plus a final
- // no-phase visit, `run_phase` once per phase. A validated DAG always
- // drains, so this only guards a malformed definition.
- .with_recursion_policy(RecursionPolicy {
- max_visits_per_node: Some(phase_count + 2),
- max_total_steps: (phase_count + 1) * 3 + 16,
- ..RecursionPolicy::default()
- });
- Ok(graph)
-}
-
-/// Topologically walk the phase DAG on a `tinyagents` conditional-routing graph
-/// (issue #4249, Phase 4): a `dispatch` node selects the next runnable phase and
-/// a `run_phase` node executes it, looping `dispatch ⇄ run_phase` until no phase
-/// remains, then routing to `done`:
-///
-/// ```text
-/// dispatch ──phase──► run_phase ──► dispatch ──none/terminal──► done
-/// ```
-///
-/// This replaces the hand-rolled `loop {}` scheduler with a graph state machine
-/// while keeping the durable `workflow_runs` row as the source of truth (every
-/// node reloads + persists it, so resume picks up persisted phase progress and
-/// the read controllers see the same projection). Returns `Ok(())` once a
-/// terminal status (Completed / Failed / Interrupted) is written; returns `Err`
-/// only for engine-internal failures (ledger writes, graph mechanics).
-pub(super) async fn drive_phases(
- config: &Config,
- run_id: &str,
- definition: &WorkflowDefinition,
- cancel: &Arc<AtomicBool>,
-) -> Result<()> {
- use crate::agent::orchestration::AgentOrchestrationSession;
- use crate::agent::tinyagents::observability::GraphTracingSink;
-
- let session = AgentOrchestrationSession::new(format!("workflow-engine-{run_id}"));
-
- // Optional per-run model override. When present in the run input
- // (`{"modelOverride": "..."}`), every child is forced onto the parent
- // (root) provider with this model instead of its declarative workload
- // provider. Production runs omit it (agents use their configured provider);
- // deterministic mock-backend tests set it so children resolve to the
- // injected mock provider.
- let model_override = get_workflow_run(&config.workspace_dir, run_id)?
- .and_then(|r| {
- r.input
- .get("modelOverride")
- .and_then(Value::as_str)
- .map(str::to_string)
- })
- .filter(|m| !m.trim().is_empty());
-
- // `'static` captures for the injected engine effects (node handlers are
- // `Fn`, re-entered once per phase, so each invocation re-clones from these).
- let config_arc = Arc::new(config.clone());
- let definition_arc = Arc::new(definition.clone());
- let run_id_owned = run_id.to_string();
- let cancel = cancel.clone();
-
- let select = {
- let config = config_arc.clone();
- let definition = definition_arc.clone();
- let run_id = run_id_owned.clone();
- let cancel = cancel.clone();
- let session = session.clone();
- move || {
- let config = config.clone();
- let definition = definition.clone();
- let run_id = run_id.clone();
- let cancel = cancel.clone();
- let session = session.clone();
- async move { select_next_phase(&config, &run_id, &definition, &cancel, &session).await }
- }
- };
-
- let run = {
- let config = config_arc.clone();
- let definition = definition_arc.clone();
- let run_id = run_id_owned.clone();
- let cancel = cancel.clone();
- let session = session.clone();
- let model_override = model_override.clone();
- move |phase: WorkflowPhase, total_spawned: u32| {
- let config = config.clone();
- let definition = definition.clone();
- let run_id = run_id.clone();
- let cancel = cancel.clone();
- let session = session.clone();
- let model_override = model_override.clone();
- async move {
- execute_phase(
- &config,
- &run_id,
- &definition,
- &session,
- &cancel,
- model_override,
- &phase,
- total_spawned,
- )
- .await
- }
- }
- };
-
- let graph = build_scheduler_graph(definition.phases.len(), select, run)?.with_event_sink(
- Arc::new(GraphTracingSink::new(format!("workflow:{run_id_owned}"))),
- );
-
- graph
- .run(SchedulerState::default())
- .await
- .map_err(|e| anyhow!("workflow scheduler graph run failed: {e}"))?;
- Ok(())
-}
-
-/// Structure-only [`GraphTopology`] of the workflow scheduler graph for debug /
-/// inspection (issue #4249, Phase 4). Built with no-op stub effects — the
-/// topology exposes only node names, edges, and routing, never closure bodies.
-pub(crate) fn scheduler_graph_topology() -> Result<GraphTopology> {
- let graph = build_scheduler_graph(
- 1,
- || async { Ok(PhaseSelection::Terminated) },
- |_phase: WorkflowPhase, _spawned: u32| async { Ok(PhaseExecOutcome::Terminated) },
- )?;
- Ok(graph.topology())
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs
new file mode 100644
index 0000000000..928d168555
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs
@@ -0,0 +1,104 @@
+//! OpenHuman's thin, policy-owning adapter for the neutral workflow engine.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::json;
+use tinyagents_harness::CancellationToken;
+use tinyagents_orchestration::workflow::{
+ OrchestrationError, WorkflowChildRegistration, WorkflowChildRequest, WorkflowChildResult,
+ WorkflowExecutor,
+};
+
+use crate::agent::orchestration::{
+ AgentOrchestrationSession, OrchestrationTaskStatus, SpawnAgentRequest, WaitAgentOptions,
+};
+
+/// Host policy has already admitted the parent context before this executor is
+/// created. This adapter only translates one neutral child request into the
+/// existing OpenHuman subagent session and retains BUS/progress behaviour there.
+#[derive(Clone)]
+pub(super) struct OpenHumanWorkflowExecutor {
+ session: AgentOrchestrationSession,
+ model_override: Option<String>,
+}
+
+impl OpenHumanWorkflowExecutor {
+ pub(super) fn new(run_id: &str, model_override: Option<String>) -> Self {
+ Self {
+ session: AgentOrchestrationSession::new(format!("workflow-engine-{run_id}")),
+ model_override,
+ }
+ }
+}
+
+#[async_trait]
+impl WorkflowExecutor for OpenHumanWorkflowExecutor {
+ async fn execute(
+ &self,
+ request: WorkflowChildRequest,
+ cancel: CancellationToken,
+ registration: Arc<dyn WorkflowChildRegistration>,
+ ) -> Result<WorkflowChildResult, OrchestrationError> {
+ if cancel.is_cancelled() {
+ return Err(OrchestrationError(
+ "workflow cancelled before child spawn".to_owned(),
+ ));
+ }
+ let response = self
+ .session
+ .spawn_agent(SpawnAgentRequest {
+ agent_id: request.agent_id.clone(),
+ prompt: request.prompt,
+ model: self.model_override.clone(),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| OrchestrationError(error.to_string()))?;
+
+ // This must happen before awaiting the child: stop() can now cancel
+ // every real orchestration id while a worker remains in flight.
+ registration.register(response.orchestration_id.clone())?;
+ if cancel.is_cancelled() {
+ self.session.abort_all().await;
+ return Err(OrchestrationError(
+ "workflow cancelled after child spawn".to_owned(),
+ ));
+ }
+ let wait = self
+ .session
+ .wait_agents(WaitAgentOptions {
+ orchestration_ids: vec![response.orchestration_id.clone()],
+ timeout_ms: None,
+ })
+ .await
+ .map_err(|error| OrchestrationError(error.to_string()))?;
+ let child = wait.agents.into_iter().next().ok_or_else(|| {
+ OrchestrationError("workflow child returned no terminal snapshot".to_owned())
+ })?;
+ if child.status != OrchestrationTaskStatus::Completed {
+ return Err(OrchestrationError(format!(
+ "child '{}' (agent '{}') ended {:?}: {}",
+ child.orchestration_id,
+ child.agent_id,
+ child.status,
+ child.error.unwrap_or_default()
+ )));
+ }
+ Ok(WorkflowChildResult {
+ child_id: response.orchestration_id,
+ // Do not coerce to text: the neutral engine faithfully carries
+ // host output JSON into downstream prompts and synthesis.
+ output: json!({
+ "agentId": child.agent_id,
+ "summary": child.result_summary,
+ }),
+ })
+ }
+
+ async fn cancel_children(&self, _child_ids: &[String]) {
+ // AgentOrchestrationSession is per workflow run, so this aborts exactly
+ // its registered children while retaining existing BUS/progress events.
+ self.session.abort_all().await;
+ }
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
index 2b2f0ccfe6..6777d50794 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
@@ -21,11 +21,14 @@
//! handles SKILL.md / WORKFLOW.md bundle discovery.
mod engine;
-mod graph;
+mod host;
mod ops;
mod schemas;
-pub(crate) use graph::scheduler_graph_topology;
+pub(crate) fn scheduler_graph_topology() -> anyhow::Result<tinyagents_graph::export::GraphTopology>
+{
+ tinyagents_orchestration::workflow::scheduler_graph()
+}
pub use engine::{resume_workflow_run, start_workflow_run, stop_workflow_run};
pub use ops::{
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 433b5f47ee..acb7529061 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 433b5f47eeaf6179ac3e1056dcc607c05c04dc33
+Subproject commit acb7529061b9e0477a6feecc832c1f91fa4559ba