The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(workflow): fence host lifecycle handoffs
Steven Enamakel258e14f3864e
diff --git a/.sdd-progress.md b/.sdd-progress.mdindex 95880441a7..3b65aa35bb 100644--- a/.sdd-progress.md+++ b/.sdd-progress.md@@ -43,6 +43,23 @@ origin and model override. The old host scheduler/state/phase graph andduplicate tests are deleted; topology imports the neutral graph directly. O6remains: parallel/worktree cleanup plus final cross-repo review/PR gates.+O5 final durability remediation: complete locally, pending commit/review. The+session ledger now exposes revision-fenced host lifecycle transitions and+lease-only renewal; stale drivers cannot write terminal/error state after a+stop/resume hand-off. The neutral engine heartbeats throughout child execution,+fails closed by cancelling every registered child on renewal loss, resets+interrupted `running` phases to retryable `pending`, and flushes truthful+terminal graph events. Phase outputs retain the established RPC projection+`{ agentId, output: String }`; lossless JSON is stored in versioned+`metadata.rawOutput` and consumed preferentially by downstream phases. The+host parses and enforces `safetyTier` at admission and child dispatch, retaining+all policy in OpenHuman. Fresh TinyAgents session (62) and orchestration (26)+unit tests pass, including short-lease takeover, lease-loss cancellation,+stop fencing, output-wire compatibility and terminal events. The focused+OpenHuman lib test target still fails before workflow tests on unrelated+pre-existing fixture/API migration diagnostics; normal `cargo check -p+openhuman` is in progress on the shared build lock.+Session extraction S1-S4: in progress. `tinyagents-session::transcript` ownsthe neutral append-only JSONL codec, paths, display/model readers, metadata,history and locator interfaces. Its public history API now stays entirely ondiff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rsindex 9015ddcfc0..806833efba 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@@ -4,12 +4,15 @@use anyhow::{anyhow, Context, Result};use serde_json::Value;use std::sync::Arc;-use tinyagents_orchestration::workflow::{SessionWorkflowStore, WorkflowEngine};+use tinyagents_orchestration::workflow::{+ reset_running_phases, SessionWorkflowStore, WorkflowEngine,+};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,+ compare_and_swap_workflow_run_lifecycle, get_workflow_run, WorkflowRun, WorkflowRunStatus,+ WorkflowRunUpsert,};use super::super::ops::definition_by_id;@@ -38,12 +41,15 @@ pub async fn start_workflow_run();let definition = definition_by_id(definition_id).ok_or_else(|| anyhow!("unknown workflow definition: {definition_id}"))?;+ let safety_tier = super::super::host::admit_workflow(&definition)?;let run_id = format!("wfrun-{}", uuid::Uuid::new_v4());let initial_engine = WorkflowEngine::new(Arc::new(SessionWorkflowStore::new(config.workspace_dir.clone())),Arc::new(super::super::host::OpenHumanWorkflowExecutor::new(- &run_id, None,+ &run_id,+ None,+ safety_tier,)),);let run = initial_engine@@ -123,22 +129,31 @@ pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<Workfsignal.token.cancel();}- let updated = upsert_workflow_run(+ let mut phase_states = run.phase_states.clone();+ reset_running_phases(+ &mut phase_states,+ "workflow interrupted by host; phase will retry on resume",+ );+ let updated = compare_and_swap_workflow_run_lifecycle(&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(),+ phase_states,child_run_ids: run.child_run_ids.clone(),status: WorkflowRunStatus::Interrupted,summary: run.summary.clone(),started_at: Some(run.started_at),completed_at: None,},+ run.revision,).context("persist workflow run interrupt")?;+ let updated = updated.ok_or_else(|| {+ anyhow!("workflow run {id} changed while stop was being applied; reload and retry")+ })?;log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.marked_interrupted run={id}");Ok(Some(updated))@@ -163,12 +178,9 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRulet definition = definition_by_id(&run.definition_id).ok_or_else(|| anyhow!("definition {} no longer exists", run.definition_id))?;+ let _safety_tier = super::super::host::admit_workflow(&definition)?;- // Clear any prior cancellation intent and re-register a fresh flag.- clear_cancel_flag(id);- register_cancel_flag(id);-- let resumed = upsert_workflow_run(+ let resumed = compare_and_swap_workflow_run_lifecycle(&config.workspace_dir,WorkflowRunUpsert {id: run.id.clone(),@@ -182,8 +194,17 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRustarted_at: Some(run.started_at),completed_at: None,},+ run.revision,).context("persist workflow run resume")?;+ let resumed = resumed.ok_or_else(|| {+ anyhow!("workflow run {id} changed while resume was being applied; reload and retry")+ })?;++ // Only replace the process-local signal after the durable hand-off won.+ // Otherwise a losing resumer could erase the live driver's stop request.+ clear_cancel_flag(id);+ register_cancel_flag(id);let task_run_id = id.to_string();// Same inherit-only origin propagation as `start_workflow_run`: the resumed@@ -229,11 +250,38 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W.map(str::to_owned)}).filter(|model| !model.trim().is_empty());+ let safety_tier = match super::super::host::admit_workflow(&definition) {+ Ok(tier) => tier,+ Err(error) => {+ log::error!(target: LOG_TARGET, "[workflow_run_engine] loop.safety_admission_failed run={run_id} err={error}");+ if let Ok(Some(run)) = get_workflow_run(&config.workspace_dir, run_id) {+ let _ = compare_and_swap_workflow_run_lifecycle(+ &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!("workflow safety admission failed: {error}")),+ started_at: Some(run.started_at),+ completed_at: Some(chrono::Utc::now()),+ },+ run.revision,+ );+ }+ clear_cancel_flag(run_id);+ return;+ }+ };let engine = WorkflowEngine::new(Arc::new(SessionWorkflowStore::new(config.workspace_dir.clone())),Arc::new(super::super::host::OpenHumanWorkflowExecutor::new(run_id,model_override,+ safety_tier,)),).with_event_sink(Arc::new(@@ -266,7 +314,7 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W| WorkflowRunStatus::Cancelled| WorkflowRunStatus::Interrupted) {- let _ = upsert_workflow_run(+ let _ = compare_and_swap_workflow_run_lifecycle(&config.workspace_dir,WorkflowRunUpsert {id: run.id.clone(),@@ -280,6 +328,7 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: Wstarted_at: Some(run.started_at),completed_at: Some(chrono::Utc::now()),},+ run.revision,);}}@@ -287,3 +336,7 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: Wclear_cancel_flag(run_id);}++#[cfg(test)]+#[path = "lifecycle_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rsnew file mode 100644index 0000000000..4796decf67--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rs@@ -0,0 +1,43 @@+use super::*;+use serde_json::json;+use tinyagents_session::run_ledger::upsert_workflow_run;++#[tokio::test]+async fn stop_fences_the_driver_and_makes_a_running_phase_resumable() {+ let workspace = tempfile::tempdir().expect("workspace");+ let config = Config {+ workspace_dir: workspace.path().to_path_buf(),+ ..Config::default()+ };+ let run = upsert_workflow_run(+ &config.workspace_dir,+ WorkflowRunUpsert {+ id: "stop-resume-lifecycle".into(),+ definition_id: "parallel_research_cross_check".into(),+ parent_thread_id: None,+ input: json!({"question":"q"}),+ phase_states: json!({+ "decompose": {"status":"completed", "outputs": []},+ "research": {"status":"running", "outputs": []}+ }),+ child_run_ids: vec!["live-child".into()],+ status: WorkflowRunStatus::Running,+ summary: None,+ started_at: None,+ completed_at: None,+ },+ )+ .expect("seed run");++ let stopped = stop_workflow_run(&config, &run.id)+ .await+ .expect("stop succeeds")+ .expect("row exists");+ assert_eq!(stopped.status, WorkflowRunStatus::Interrupted);+ assert_eq!(stopped.phase_states["research"]["status"], json!("pending"));+ assert!(stopped.lease_owner.is_none());+ assert!(+ stopped.revision > run.revision,+ "stop must fence the old driver"+ );+}diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rsindex 928d168555..532d9f3070 100644--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs@@ -2,18 +2,46 @@use std::sync::Arc;+use anyhow::{anyhow, Result};use async_trait::async_trait;use serde_json::json;use tinyagents_harness::CancellationToken;use tinyagents_orchestration::workflow::{OrchestrationError, WorkflowChildRegistration, WorkflowChildRequest, WorkflowChildResult,- WorkflowExecutor,+ WorkflowDefinition, WorkflowExecutor,};+use crate::agent::harness::definition::{AgentDefinitionRegistry, SandboxMode, ToolScope};use crate::agent::orchestration::{AgentOrchestrationSession, OrchestrationTaskStatus, SpawnAgentRequest, WaitAgentOptions,};+/// Product policy deliberately remains in OpenHuman. The portable engine sees+/// no safety labels; this adapter admits a catalog definition and keeps its+/// children inside the advertised capability envelope.+#[derive(Clone, Copy)]+pub(super) enum WorkflowSafetyTier {+ ReadOnly,+}++pub(super) fn admit_workflow(definition: &WorkflowDefinition) -> Result<WorkflowSafetyTier> {+ match definition+ .extensions+ .get("safetyTier")+ .and_then(serde_json::Value::as_str)+ {+ Some("read_only") => Ok(WorkflowSafetyTier::ReadOnly),+ Some(other) => Err(anyhow!(+ "workflow '{}' has unsupported safetyTier '{other}'",+ definition.id+ )),+ None => Err(anyhow!(+ "workflow '{}' is missing required safetyTier",+ definition.id+ )),+ }+}+/// 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.@@ -21,13 +49,47 @@ use crate::agent::orchestration::{pub(super) struct OpenHumanWorkflowExecutor {session: AgentOrchestrationSession,model_override: Option<String>,+ safety_tier: WorkflowSafetyTier,}impl OpenHumanWorkflowExecutor {- pub(super) fn new(run_id: &str, model_override: Option<String>) -> Self {+ pub(super) fn new(+ run_id: &str,+ model_override: Option<String>,+ safety_tier: WorkflowSafetyTier,+ ) -> Self {Self {session: AgentOrchestrationSession::new(format!("workflow-engine-{run_id}")),model_override,+ safety_tier,+ }+ }++ fn admit_child(&self, agent_id: &str) -> Result<(), OrchestrationError> {+ match self.safety_tier {+ WorkflowSafetyTier::ReadOnly => {+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| {+ OrchestrationError(+ "workflow safety admission requires the agent registry".to_owned(),+ )+ })?;+ let definition = registry.get(agent_id).ok_or_else(|| {+ OrchestrationError(format!(+ "workflow safety admission rejected unknown agent '{agent_id}'"+ ))+ })?;+ let allowed_named_tool =+ |tool: &str| matches!(tool, "web_search_tool" | "web_fetch");+ let read_only = matches!(definition.sandbox_mode, SandboxMode::ReadOnly)+ || matches!(&definition.tools, ToolScope::Named(tools) if tools.iter().all(|tool| allowed_named_tool(tool)));+ if read_only {+ Ok(())+ } else {+ Err(OrchestrationError(format!(+ "workflow safetyTier read_only rejected agent '{agent_id}' with acting-capable tools"+ )))+ }+ }}}}@@ -40,6 +102,7 @@ impl WorkflowExecutor for OpenHumanWorkflowExecutor {cancel: CancellationToken,registration: Arc<dyn WorkflowChildRegistration>,) -> Result<WorkflowChildResult, OrchestrationError> {+ self.admit_child(&request.agent_id)?;if cancel.is_cancelled() {return Err(OrchestrationError("workflow cancelled before child spawn".to_owned(),@@ -102,3 +165,7 @@ impl WorkflowExecutor for OpenHumanWorkflowExecutor {self.session.abort_all().await;}}++#[cfg(test)]+#[path = "host_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rsnew file mode 100644index 0000000000..b4368aa772--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rs@@ -0,0 +1,29 @@+use super::*;+use std::collections::BTreeMap;+use tinyagents_orchestration::workflow::WorkflowDefinition;++fn definition(safety_tier: Option<&str>) -> WorkflowDefinition {+ let mut extensions = BTreeMap::new();+ if let Some(safety_tier) = safety_tier {+ extensions.insert("safetyTier".to_owned(), serde_json::json!(safety_tier));+ }+ WorkflowDefinition {+ id: "host-safety".into(),+ name: "host safety".into(),+ description: String::new(),+ phases: Vec::new(),+ default_concurrency: 1,+ max_children: 1,+ extensions,+ }+}++#[test]+fn host_admits_only_explicit_supported_safety_tiers() {+ assert!(matches!(+ admit_workflow(&definition(Some("read_only"))),+ Ok(WorkflowSafetyTier::ReadOnly)+ ));+ assert!(admit_workflow(&definition(None)).is_err());+ assert!(admit_workflow(&definition(Some("full"))).is_err());+}diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rsindex 6777d50794..f5e4c18670 100644--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs@@ -25,9 +25,10 @@ mod host;mod ops;mod schemas;-pub(crate) fn scheduler_graph_topology() -> anyhow::Result<tinyagents_graph::export::GraphTopology>+/// A diagnostic topology preview, not the effectful workflow scheduler.+pub(crate) fn scheduler_topology_preview() -> anyhow::Result<tinyagents_graph::export::GraphTopology>{- tinyagents_orchestration::workflow::scheduler_graph()+ tinyagents_orchestration::workflow::scheduler_topology_preview()}pub use engine::{resume_workflow_run, start_workflow_run, stop_workflow_run};diff --git a/crates/openhuman-core/src/agent/tinyagents/topology.rs b/crates/openhuman-core/src/agent/tinyagents/topology.rsindex c46dec52e5..f12bf3dd7c 100644--- a/crates/openhuman-core/src/agent/tinyagents/topology.rs+++ b/crates/openhuman-core/src/agent/tinyagents/topology.rs@@ -53,8 +53,8 @@ pub(crate) fn all_graph_topologies() -> Vec<GraphTopologyReport> {out.push(describe("delegation", &t));}- if let Ok(t) = crate::agent::orchestration::workflow_runs::scheduler_graph_topology() {- out.push(describe("workflow_runs:scheduler", &t));+ if let Ok(t) = crate::agent::orchestration::workflow_runs::scheduler_topology_preview() {+ out.push(describe("workflow_runs:scheduler_preview", &t));}if let Ok(t) = crate::agent::registry::agents::researcher::graph::topology() {diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 24d8ec8f32..5cd6aac98e 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 24d8ec8f32181a790cf15e0000bf6162183cb710+Subproject commit 5cd6aac98efdfb124f305f9032443d104d74af0b