Skip to content

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

refactor(workflow): remove legacy engine parts and fix test imports

Steven Enamakel647754519afa
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_part_01.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_part_01.rs
deleted file mode 100644
index 0dbd30a29b..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_part_01.rs
+++ /dev/null
@@ -1,448 +0,0 @@
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Mutex, OnceLock};
-
-use anyhow::{anyhow, Context, Result};
-use serde_json::{json, Value};
-use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};
-use tinyagents_harness::{CancellationToken, TinyAgentsError};
-
-use crate::agent::orchestration::parent_context::with_root_parent;
-use crate::config::Config;
-use tinyagents_session::run_ledger::{
- get_workflow_run, upsert_workflow_run, WorkflowRun, WorkflowRunStatus, WorkflowRunUpsert,
-};
-
-use super::ops::definition_by_id;
-use super::types::{WorkflowDefinition, WorkflowPhase};
-
-const LOG_TARGET: &str = "workflow_run_engine";
-
-/// Per-phase status stored inside the run's `phase_states` JSON column.
-const PHASE_PENDING: &str = "pending";
-const PHASE_RUNNING: &str = "running";
-const PHASE_COMPLETED: &str = "completed";
-const PHASE_FAILED: &str = "failed";
-
-/// One worker's outcome from the intra-phase graph fan-out (see
-/// [`drive_phases`]). 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>,
-}
-
-// ───────────────────────────────────────────────────────────────────────────
-// Cancellation registry
-// ───────────────────────────────────────────────────────────────────────────
-
-/// Process-wide map of `run_id -> cancellation flag`. `stop_workflow_run`
-/// flips the flag; the engine loop checks it between phases and aborts in-flight
-/// child tasks via the orchestration session before marking the run
-/// `Interrupted`.
-#[derive(Clone)]
-struct WorkflowCancelSignal {
- flag: Arc<AtomicBool>,
- token: CancellationToken,
-}
-
-fn cancel_registry() -> &'static Mutex<HashMap<String, WorkflowCancelSignal>> {
- static REGISTRY: OnceLock<Mutex<HashMap<String, WorkflowCancelSignal>>> = OnceLock::new();
- REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
-}
-
-/// Register (or reuse) a cancellation flag for `run_id`.
-fn register_cancel_signal(run_id: &str) -> WorkflowCancelSignal {
- let mut map = cancel_registry().lock().expect("cancel registry poisoned");
- map.entry(run_id.to_string())
- .or_insert_with(|| WorkflowCancelSignal {
- flag: Arc::new(AtomicBool::new(false)),
- token: CancellationToken::new(),
- })
- .clone()
-}
-
-/// Register (or reuse) a cancellation flag for `run_id`.
-fn register_cancel_flag(run_id: &str) -> Arc<AtomicBool> {
- register_cancel_signal(run_id).flag
-}
-
-/// Look up an existing cancellation signal for `run_id`, if one is registered.
-fn lookup_cancel_signal(run_id: &str) -> Option<WorkflowCancelSignal> {
- cancel_registry()
- .lock()
- .expect("cancel registry poisoned")
- .get(run_id)
- .cloned()
-}
-
-/// Look up an existing cancellation flag for `run_id`, if one is registered.
-fn lookup_cancel_flag(run_id: &str) -> Option<Arc<AtomicBool>> {
- lookup_cancel_signal(run_id).map(|signal| signal.flag)
-}
-
-/// Look up an SDK cancellation token for `run_id`, if one is registered.
-fn lookup_cancel_token(run_id: &str) -> Option<CancellationToken> {
- lookup_cancel_signal(run_id).map(|signal| signal.token)
-}
-
-/// Drop a run's cancellation flag once the engine loop is done with it.
-fn clear_cancel_flag(run_id: &str) {
- cancel_registry()
- .lock()
- .expect("cancel registry poisoned")
- .remove(run_id);
-}
-
-// ───────────────────────────────────────────────────────────────────────────
-// Public entry points
-// ───────────────────────────────────────────────────────────────────────────
-
-/// Start a new workflow run and return immediately.
-///
-/// Resolves `definition_id` to a builtin [`WorkflowDefinition`], creates a
-/// `Running` ledger row with `phase_states` initialised to one `pending` entry
-/// per phase, persists it, then `tokio::spawn`s the engine loop. The returned
-/// [`WorkflowRun`] is the freshly-created row (status `Running`); callers poll
-/// `workflow_run_get` to observe progress.
-pub async fn start_workflow_run(
- config: &Config,
- definition_id: &str,
- input: Value,
- parent_thread_id: Option<String>,
-) -> Result<WorkflowRun> {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] start.entry definition={definition_id} parent_thread={parent_thread_id:?}"
- );
- let definition = definition_by_id(definition_id)
- .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")?;
-
- register_cancel_flag(&run_id);
-
- // Spawn the engine loop. Clone what the task needs (the engine reloads
- // config inside the task so it can build a real Agent without holding a
- // borrow across the spawn boundary).
- let task_run_id = run_id.clone();
- // Task-locals don't cross `tokio::spawn`, so capture the starting turn's
- // origin here and re-scope it around the engine loop — the phases spawn
- // sub-agents whose tool calls the approval gate judges by that label.
- // Inherit-only: `None` leaves the loop unlabelled and failing closed.
- let inherited_origin = crate::agent::turn_origin::capture();
- tokio::spawn(async move {
- match Config::load_or_init().await {
- Ok(task_config) => {
- crate::agent::turn_origin::with_inherited_origin(
- inherited_origin,
- run_engine_loop(&task_config, &task_run_id, definition),
- )
- .await;
- }
- Err(err) => {
- log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] start.config_load_failed run={task_run_id} err={err}"
- );
- }
- }
- });
-
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] start.spawned run={run_id} phases={}",
- run.phase_states.as_object().map(|m| m.len()).unwrap_or(0)
- );
- Ok(run)
-}
-
-/// Signal a running workflow to stop after its current phase.
-///
-/// Flips the run's cancellation flag (checked by the loop between phases) and
-/// eagerly marks the persisted row `Interrupted` so a poller sees the intent
-/// immediately even while the in-flight phase drains. Idempotent: stopping a
-/// terminal or unknown run is a no-op that returns the current row.
-pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<WorkflowRun>> {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.entry run={id}");
- let Some(run) = get_workflow_run(&config.workspace_dir, id)? else {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.unknown run={id}");
- return Ok(None);
- };
-
- if matches!(
- run.status,
- WorkflowRunStatus::Completed | WorkflowRunStatus::Failed | WorkflowRunStatus::Cancelled
- ) {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] stop.already_terminal run={id} status={}",
- run.status.as_str()
- );
- return Ok(Some(run));
- }
-
- if let Some(signal) = lookup_cancel_signal(id) {
- signal.flag.store(true, Ordering::SeqCst);
- signal.token.cancel();
- } else {
- // No live loop (e.g. process restart) — register a flag anyway so a
- // future resume observes the stop intent.
- let signal = register_cancel_signal(id);
- signal.flag.store(true, Ordering::SeqCst);
- signal.token.cancel();
- }
-
- let updated = 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::Interrupted,
- summary: run.summary.clone(),
- started_at: Some(run.started_at),
- completed_at: None,
- },
- )
- .context("persist workflow run interrupt")?;
-
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.marked_interrupted run={id}");
- Ok(Some(updated))
-}
-
-/// Resume an interrupted (or otherwise incomplete) workflow run.
-///
-/// Reloads the run, clears any stale cancellation flag, flips the row back to
-/// `Running`, and spawns a fresh engine loop. Phases already `completed` in
-/// `phase_states` are skipped; the loop continues from the first incomplete
-/// phase whose dependencies are satisfied. Returns the run row (now `Running`),
-/// or an error if the run is unknown / already terminal-complete / its
-/// definition no longer exists.
-pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRun> {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.entry run={id}");
- let run = get_workflow_run(&config.workspace_dir, id)?
- .ok_or_else(|| anyhow!("unknown workflow run: {id}"))?;
-
- if matches!(run.status, WorkflowRunStatus::Completed) {
- return Err(anyhow!("workflow run {id} is already completed"));
- }
-
- let definition = definition_by_id(&run.definition_id)
- .ok_or_else(|| anyhow!("definition {} no longer exists", run.definition_id))?;
-
- // Clear any prior cancellation intent and re-register a fresh flag.
- clear_cancel_flag(id);
- register_cancel_flag(id);
-
- let resumed = 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::Running,
- summary: run.summary.clone(),
- started_at: Some(run.started_at),
- completed_at: None,
- },
- )
- .context("persist workflow run resume")?;
-
- let task_run_id = id.to_string();
- // Same inherit-only origin propagation as `start_workflow_run`: the resumed
- // loop runs on a fresh task, which would otherwise drop the caller's label.
- let inherited_origin = crate::agent::turn_origin::capture();
- tokio::spawn(async move {
- match Config::load_or_init().await {
- Ok(task_config) => {
- crate::agent::turn_origin::with_inherited_origin(
- inherited_origin,
- run_engine_loop(&task_config, &task_run_id, definition),
- )
- .await;
- }
- Err(err) => {
- log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] resume.config_load_failed run={task_run_id} err={err}"
- );
- }
- }
- });
-
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.spawned run={id}");
- Ok(resumed)
-}
-
-// ───────────────────────────────────────────────────────────────────────────
-// Engine loop
-// ───────────────────────────────────────────────────────────────────────────
-
-/// Build the root parent context + drive the phase DAG to completion.
-///
-/// Separated from [`start_workflow_run`] so it can run on the spawned task with
-/// an owned [`Config`]. Errors are recorded on the run row (status `Failed`)
-/// rather than propagated — there is no caller to receive them.
-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 outcome = with_root_parent(config, "workflow_engine", "workflow", "workflow", async {
- super::graph::drive_phases(config, run_id, &definition, &cancel).await
- })
- .await
- // Flatten: outer Err = root-parent build failure, inner = drive_phases result.
- .unwrap_or_else(Err);
-
- if let Err(err) = outcome {
- log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] loop.failed run={run_id} err={err}"
- );
- // Best-effort terminal failure write, preserving partial phase state.
- if let Ok(Some(run)) = get_workflow_run(&config.workspace_dir, run_id) {
- if !matches!(
- run.status,
- WorkflowRunStatus::Completed
- | WorkflowRunStatus::Failed
- | 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,
- );
- }
- }
- }
-
- clear_cancel_flag(run_id);
-}
-
-/// What the scheduler's `dispatch` step decided.
-pub(super) enum PhaseSelection {
- /// Execute this phase next.
- Run(WorkflowPhase),
- /// The run reached a terminal status (already persisted) — route to `done`.
- Terminated,
-}
-
-/// Outcome of executing one phase in the `run_phase` step.
-pub(super) 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,
-}
-
-/// `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(super) 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_part_02.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_part_02.rs
deleted file mode 100644
index 431bd9bda7..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine_part_02.rs
+++ /dev/null
@@ -1,531 +0,0 @@
-
-/// `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(super) 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,
- })
-}
-
-// ───────────────────────────────────────────────────────────────────────────
-// Phase-state helpers
-// ───────────────────────────────────────────────────────────────────────────
-
-/// Initialise `phase_states` to one `pending` entry per phase, preserving
-/// declaration order via an object keyed by phase name.
-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)
-}
-
-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)
-}
-
-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);
- }
- }
- }
-}
-
-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.
-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))
- })
-}
-
-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.
-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.
-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`.
-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)]
-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/core/subsystem/schemas_tests.rs b/crates/openhuman-core/src/core/subsystem/schemas_tests.rs
index d981521c9e..63de807baa 100644
--- a/crates/openhuman-core/src/core/subsystem/schemas_tests.rs
+++ b/crates/openhuman-core/src/core/subsystem/schemas_tests.rs
@@ -1,38 +1,38 @@
use super::*;
- use super::*;
+use super::*;
- #[test]
- fn status_schema_shape() {
- let schema = schemas("status");
- assert_eq!(schema.namespace, "subsystems");
- assert_eq!(schema.function, "status");
- assert!(schema.inputs.is_empty());
- assert_eq!(schema.outputs.len(), 1);
- assert_eq!(schema.outputs[0].name, "subsystems");
- }
+#[test]
+fn status_schema_shape() {
+ let schema = schemas("status");
+ assert_eq!(schema.namespace, "subsystems");
+ assert_eq!(schema.function, "status");
+ assert!(schema.inputs.is_empty());
+ assert_eq!(schema.outputs.len(), 1);
+ assert_eq!(schema.outputs[0].name, "subsystems");
+}
- #[test]
- fn unknown_function_returns_the_unknown_schema() {
- assert_eq!(schemas("not_real").function, "unknown");
- }
+#[test]
+fn unknown_function_returns_the_unknown_schema() {
+ assert_eq!(schemas("not_real").function, "unknown");
+}
- #[test]
- fn schemas_and_controllers_line_up() {
- let schemas = all_controller_schemas();
- let controllers = all_registered_controllers();
- assert_eq!(schemas.len(), controllers.len());
- for (schema, controller) in schemas.iter().zip(controllers.iter()) {
- assert_eq!(schema.namespace, controller.schema.namespace);
- assert_eq!(schema.function, controller.schema.function);
- }
+#[test]
+fn schemas_and_controllers_line_up() {
+ let schemas = all_controller_schemas();
+ let controllers = all_registered_controllers();
+ assert_eq!(schemas.len(), controllers.len());
+ for (schema, controller) in schemas.iter().zip(controllers.iter()) {
+ assert_eq!(schema.namespace, controller.schema.namespace);
+ assert_eq!(schema.function, controller.schema.function);
}
+}
- #[tokio::test]
- async fn handler_returns_a_subsystems_array_containing_the_memory_slot() {
- let value = handle_status(Map::new()).await.expect("handler succeeds");
- let rows = value["subsystems"].as_array().expect("array");
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0]["slot"], "memory");
- assert!(rows[0]["contract_version"].is_string());
- assert!(rows[0]["capabilities"].is_array());
- }
+#[tokio::test]
+async fn handler_returns_a_subsystems_array_containing_the_memory_slot() {
+ let value = handle_status(Map::new()).await.expect("handler succeeds");
+ let rows = value["subsystems"].as_array().expect("array");
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0]["slot"], "memory");
+ assert!(rows[0]["contract_version"].is_string());
+ assert!(rows[0]["capabilities"].is_array());
+}
diff --git a/crates/openhuman-core/src/security/credentials/ops_tests.rs b/crates/openhuman-core/src/security/credentials/ops_tests.rs
index adae0406ce..b5d54e0d05 100644
--- a/crates/openhuman-core/src/security/credentials/ops_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/ops_tests.rs
@@ -1,5 +1,7 @@
use super::*;
+use crate::config::{default_root_openhuman_dir, user_openhuman_dir, write_active_user_id, Config};
use crate::security::credentials::session_support::local_session_user_id;
+use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
use axum::http::StatusCode;
use axum::routing::get;
use axum::Router;