Skip to content

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

refactor(orchestration): remove parallel graph and worktree aliases

Steven Enamakelafcd16b26a39
diff --git a/.sdd-progress.md b/.sdd-progress.md
index dbc714052f..b90c5060d7 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -41,7 +41,19 @@ OpenHuman's production lifecycle constructs the neutral `WorkflowEngine` over
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.
+is complete locally, pending the shared build-lock test queue and final
+review/commit gates. The duplicate fixed `spawn_parallel_agents` phase
+coordinator and topology facade are deleted: the host now decodes its tool-only
+JSON contract at the tool boundary, executes host
+policy/progress/worktree stages directly, and uses the existing
+`tinyagents_graph::parallel::map_reduce` for bounded worker fanout. The typed
+request stays host-side because `toolkit`, `files:` ownership syntax and
+worktree options are product-policy inputs, not a neutral orchestration API.
+Historic OpenHuman aliases for git worktree create/list/status/diff/remove,
+base refs, errors and overlap detection are deleted; every consumer imports
+the harness surface directly. `OpenHumanWorktreeIsolation`, its BUS lifecycle
+events, descriptor gate and RPC schemas remain host-owned. Dirty-worktree
+refusal/removal and parallel policy coverage are retained.
O5 final durability remediation: complete locally, pending commit/review. The
session ledger now exposes revision-fenced host lifecycle transitions and
diff --git a/crates/openhuman-core/src/agent/orchestration/mod.rs b/crates/openhuman-core/src/agent/orchestration/mod.rs
index c85f6ced53..dc24338e6d 100644
--- a/crates/openhuman-core/src/agent/orchestration/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/mod.rs
@@ -53,7 +53,7 @@ pub use types::{
pub use workflow_runs::{
all_workflow_run_controller_schemas, all_workflow_run_registered_controllers,
};
-pub use worktree::{BaseRef, OpenHumanWorktreeIsolation, WorktreeError, WorktreeStatus};
+pub use worktree::OpenHumanWorktreeIsolation;
pub use worktree_schemas::{
all_controller_schemas as all_worktree_controller_schemas,
all_registered_controllers as all_worktree_registered_controllers,
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
index 21c398f4d4..3f07a174d9 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
@@ -1,7 +1,7 @@
-//! Structure-only graph scaffold for `spawn_parallel_agents`.
+//! Host-side execution pipeline for `spawn_parallel_agents`.
//!
//! The tool wrapper still owns `ToolResult` translation. This module owns
-//! request parsing, parent-context validation, graph-side request validation,
+//! tool request parsing, parent-context validation,
//! worktree preflight, progress/event projection, worker fanout, final JSON
//! formatting, and the topology surface.
//!
@@ -15,32 +15,25 @@
//!
//! ## Module layout
//!
-//! - [`request`] — request decoding and structural validation.
//! - [`types`] — shared worker/result/lineage types.
//! - [`staging`] — OpenHuman policy admission and shared-workspace arbitration.
//! - [`dispatch`] — worktree preflight and progress projection for the
//! `dispatch` phase, turning admitted tasks into staged workers.
//! - [`workers`] — the serial and `map_reduce` worker fanout.
//! - [`collect`] — collecting fanned-out results into the tool's final shape.
-//! - [`graph`] — the fixed phase-graph scaffold and topology export.
//! - [`run`] — the public entry points that tie the above together.
mod collect;
mod dispatch;
-mod graph;
-mod request;
mod run;
mod staging;
mod types;
mod workers;
pub(crate) use collect::{format_spawn_parallel_success, SpawnParallelGraphOutcome};
-pub(crate) use graph::spawn_parallel_graph_topology;
-pub(crate) use request::SpawnParallelTaskValidationError;
-pub(crate) use run::run_spawn_parallel_graph_with_cancellation_and_workspace;
+pub(crate) use run::run_spawn_parallel_tasks_with_cancellation_and_workspace;
+pub(crate) use types::ParallelAgentTask;
-#[cfg(test)]
-pub(crate) use request::ParallelAgentTask;
#[cfg(test)]
pub(crate) use staging::{
prepare_spawn_parallel_tasks_from_defs, with_ownership_boundary, ParallelTaskRejectionKind,
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs
index b956b7e34e..921ab24898 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs
@@ -10,7 +10,6 @@ use tokio::sync::mpsc::Sender;
use crate::agent::file_state;
use crate::agent::progress::AgentProgress;
-use super::request::SpawnParallelTaskValidationError;
use super::types::ParallelAgentResult;
#[derive(Clone)]
@@ -22,7 +21,6 @@ pub(crate) struct SpawnParallelCollected {
pub(crate) enum SpawnParallelGraphOutcome {
Collected(SpawnParallelCollected),
- InvalidRequest(SpawnParallelTaskValidationError),
Rejected(String),
Cancelled(String),
}
@@ -201,7 +199,7 @@ fn overlap_warnings_for_results(
)
})
.collect();
- let overlaps = crate::agent::orchestration::worktree::detect_overlaps(&per_worker);
+ let overlaps = tinyagents_harness::workspace::detect_worktree_overlaps(&per_worker);
let overlap_warnings: Vec<serde_json::Value> = overlaps
.iter()
.map(|(file, workers)| {
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs
index 6fb947fd7c..8b85fb3453 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs
@@ -14,12 +14,13 @@ use crate::agent::harness::fork_context::ParentExecutionContext;
use crate::agent::orchestration::worktree;
use crate::agent::progress::AgentProgress;
-use super::request::ParallelAgentTask;
use super::staging::{
prepare_spawn_parallel_tasks_from_defs, worktree_request_for_task, ParallelTaskRejectionKind,
ParallelWorktreeRequest, SpawnParallelTaskPreflight, WorkerDispatchMode,
};
-use super::types::{ParallelAgentLineage, ParallelAgentResult, SpawnParallelWorker};
+use super::types::{
+ ParallelAgentLineage, ParallelAgentResult, ParallelAgentTask, SpawnParallelWorker,
+};
pub(crate) fn spawn_parallel_lineage(
parent_session: &str,
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs
deleted file mode 100644
index ed717b51a3..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs
+++ /dev/null
@@ -1,422 +0,0 @@
-//! The fixed `spawn_parallel_agents` graph scaffold: phase state, the
-//! reducer, node wiring, and topology export.
-//!
-//! The node order is intentionally static for topology export:
-//!
-//! `validate -> dispatch -> worker -> collect -> finalize`
-
-use std::future::Future;
-use std::path::PathBuf;
-use std::pin::Pin;
-use std::sync::Arc;
-
-use tinyagents_graph::export::GraphTopology;
-use tinyagents_graph::{ClosureStateReducer, CompiledGraph, GraphBuilder, NodeContext, NodeResult};
-use tinyagents_harness::retry::RetryPolicy;
-use tinyagents_harness::{CancellationToken, TinyAgentsError};
-use tinytools::WorkspaceDescriptor;
-use tokio::sync::mpsc::Sender;
-
-use crate::agent::harness::definition::AgentDefinition;
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::progress::AgentProgress;
-use std::collections::HashMap;
-
-use super::collect::{
- collect_spawn_parallel_results, project_spawn_parallel_result, SpawnParallelCollected,
- SpawnParallelGraphOutcome,
-};
-use super::dispatch::stage_spawn_parallel_workers_from_defs;
-use super::request::ParallelAgentTask;
-use super::types::{ParallelAgentResult, SpawnParallelWorker};
-use super::workers::run_spawn_parallel_workers;
-
-const SPAWN_PARALLEL_PHASES: &[&str] = &["validate", "dispatch", "worker", "collect", "finalize"];
-
-#[derive(Clone, Default)]
-struct SpawnParallelState {
- visited: Vec<&'static str>,
- cancelled_phase: Option<&'static str>,
- tasks: Vec<ParallelAgentTask>,
- max_parallel: usize,
- rejection: Option<String>,
- prepared: Vec<SpawnParallelWorker>,
- immediate_results: Vec<ParallelAgentResult>,
- fanned_results: Vec<ParallelAgentResult>,
- results: Vec<ParallelAgentResult>,
- action_root: Option<PathBuf>,
- collected: Option<SpawnParallelCollected>,
-}
-
-impl SpawnParallelState {
- fn for_execution(
- tasks: Vec<ParallelAgentTask>,
- max_parallel: usize,
- action_root: Option<PathBuf>,
- ) -> Self {
- Self {
- tasks,
- max_parallel,
- action_root,
- ..Self::default()
- }
- }
-}
-
-enum SpawnParallelUpdate {
- PhaseEntered(&'static str),
- Cancelled(&'static str),
- Rejected(String),
- Staged {
- prepared: Vec<SpawnParallelWorker>,
- immediate_results: Vec<ParallelAgentResult>,
- },
- Fanned(Vec<ParallelAgentResult>),
- Results(Vec<ParallelAgentResult>),
- Collected(SpawnParallelCollected),
-}
-
-type SpawnParallelNodeFuture = Pin<
- Box<dyn Future<Output = tinyagents_harness::Result<NodeResult<SpawnParallelUpdate>>> + Send>,
->;
-
-fn phase_node(
- phase: &'static str,
-) -> impl Fn(SpawnParallelState, NodeContext) -> SpawnParallelNodeFuture + Clone + Send + Sync + 'static
-{
- move |_state: SpawnParallelState, _ctx: NodeContext| {
- Box::pin(async move { Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(phase))) })
- }
-}
-
-/// Build the fixed `spawn_parallel_agents` graph scaffold, for topology export.
-fn build_spawn_parallel_graph(
-) -> Result<CompiledGraph<SpawnParallelState, SpawnParallelUpdate>, String> {
- let phases = SPAWN_PARALLEL_PHASES;
- GraphBuilder::<SpawnParallelState, SpawnParallelUpdate>::new()
- .set_reducer(ClosureStateReducer::new(
- |mut state: SpawnParallelState, update: SpawnParallelUpdate| {
- match update {
- SpawnParallelUpdate::PhaseEntered(phase) => state.visited.push(phase),
- SpawnParallelUpdate::Cancelled(phase) => {
- state.visited.push(phase);
- state.cancelled_phase.get_or_insert(phase);
- }
- SpawnParallelUpdate::Rejected(message) => state.rejection = Some(message),
- SpawnParallelUpdate::Staged {
- prepared,
- immediate_results,
- } => {
- state.prepared = prepared;
- state.immediate_results = immediate_results;
- }
- SpawnParallelUpdate::Fanned(results) => state.fanned_results = results,
- SpawnParallelUpdate::Results(results) => state.results = results,
- SpawnParallelUpdate::Collected(collected) => state.collected = Some(collected),
- }
- Ok(state)
- },
- ))
- .add_node(phases[0], phase_node(phases[0]))
- .add_node(phases[1], phase_node(phases[1]))
- .add_node(phases[2], phase_node(phases[2]))
- .add_node(phases[3], phase_node(phases[3]))
- .add_node(phases[4], phase_node(phases[4]))
- .add_edge(phases[0], phases[1])
- .add_edge(phases[1], phases[2])
- .add_edge(phases[2], phases[3])
- .add_edge(phases[3], phases[4])
- .set_entry(phases[0])
- .set_finish(phases[4])
- .compile()
- .map_err(|e| format!("spawn_parallel_agents graph compile failed: {e}"))
-}
-
-/// Run the fixed fanout graph over the live worker/collect/finalize phases.
-///
-/// Validation and worktree preflight still happen before this helper; the graph
-/// owns the map-reduce worker fanout, compatibility progress projection, and
-/// final result collection.
-#[allow(clippy::too_many_arguments)]
-pub(crate) async fn run_spawn_parallel_execution_graph(
- parent_session: &str,
- progress_sink: Option<Sender<AgentProgress>>,
- tasks: Vec<ParallelAgentTask>,
- max_parallel: usize,
- definitions: HashMap<String, AgentDefinition>,
- parent: ParentExecutionContext,
- action_root: Option<PathBuf>,
- cancel: CancellationToken,
- parent_workspace_descriptor: Option<WorkspaceDescriptor>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
-) -> Result<SpawnParallelGraphOutcome, String> {
- let phases = SPAWN_PARALLEL_PHASES;
- let label = format!("spawn_parallel_agents:{parent_session}");
- let parent_for_dispatch_session = parent_session.to_string();
- let progress_for_dispatch = progress_sink.clone();
- let definitions_for_dispatch = definitions.clone();
- let parent_for_dispatch = parent.clone();
- let parent_workspace_for_dispatch = parent_workspace_descriptor.clone();
- let parent_for_collect = parent_session.to_string();
- let progress_for_collect = progress_sink.clone();
- let parent_for_finalize = parent_session.to_string();
- let cancel_for_validate = cancel.clone();
- let cancel_for_dispatch = cancel.clone();
- let cancel_for_worker = cancel.clone();
- let cancel_for_collect = cancel.clone();
- let cancel_for_finalize = cancel.clone();
- let run_context_for_worker = run_context.clone();
- let graph = GraphBuilder::<SpawnParallelState, SpawnParallelUpdate>::new()
- .set_reducer(ClosureStateReducer::new(
- |mut state: SpawnParallelState, update: SpawnParallelUpdate| {
- match update {
- SpawnParallelUpdate::PhaseEntered(phase) => state.visited.push(phase),
- SpawnParallelUpdate::Cancelled(phase) => {
- state.visited.push(phase);
- state.cancelled_phase.get_or_insert(phase);
- }
- SpawnParallelUpdate::Rejected(message) => state.rejection = Some(message),
- SpawnParallelUpdate::Staged {
- prepared,
- immediate_results,
- } => {
- state.prepared = prepared;
- state.immediate_results = immediate_results;
- }
- SpawnParallelUpdate::Fanned(results) => state.fanned_results = results,
- SpawnParallelUpdate::Results(results) => state.results = results,
- SpawnParallelUpdate::Collected(collected) => state.collected = Some(collected),
- }
- Ok(state)
- },
- ))
- .add_node(
- phases[0],
- move |state: SpawnParallelState, _ctx: NodeContext| {
- let cancel = cancel_for_validate.clone();
- async move {
- if cancel.is_cancelled() {
- tracing::debug!(
- phase = "validate",
- "[spawn_parallel_agents] graph_cancelled_at_boundary"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(
- "validate",
- )));
- }
- if state.tasks.len() > state.max_parallel {
- let message = format!(
- "spawn_parallel_agents received {} tasks but max_parallel_tools is {}",
- state.tasks.len(),
- state.max_parallel
- );
- Ok(NodeResult::Update(SpawnParallelUpdate::Rejected(message)))
- } else {
- Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(
- "validate",
- )))
- }
- }
- },
- )
- .add_node(
- phases[1],
- move |state: SpawnParallelState, _ctx: NodeContext| {
- let parent_session = parent_for_dispatch_session.clone();
- let progress_sink = progress_for_dispatch.clone();
- let definitions = definitions_for_dispatch.clone();
- let parent = parent_for_dispatch.clone();
- let parent_workspace_descriptor = parent_workspace_for_dispatch.clone();
- let cancel = cancel_for_dispatch.clone();
- async move {
- if state.cancelled_phase.is_some() || state.rejection.is_some() {
- return Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(
- "dispatch",
- )));
- }
- if cancel.is_cancelled() {
- tracing::debug!(
- phase = "dispatch",
- "[spawn_parallel_agents] graph_cancelled_at_boundary"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(
- "dispatch",
- )));
- }
- let (prepared, immediate_results) = stage_spawn_parallel_workers_from_defs(
- &parent_session,
- progress_sink.as_ref(),
- state.tasks,
- &definitions,
- &parent,
- state.action_root.as_deref(),
- parent_workspace_descriptor.as_ref(),
- )
- .await;
- Ok(NodeResult::Update(SpawnParallelUpdate::Staged {
- prepared,
- immediate_results,
- }))
- }
- },
- )
- .add_node(
- phases[2],
- move |state: SpawnParallelState, _ctx: NodeContext| {
- let cancel = cancel_for_worker.clone();
- let run_context = run_context_for_worker.clone();
- async move {
- if state.cancelled_phase.is_some() || state.rejection.is_some() {
- return Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(
- "worker",
- )));
- }
- if cancel.is_cancelled() {
- tracing::debug!(
- phase = "worker",
- "[spawn_parallel_agents] graph_cancelled_at_boundary"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled("worker")));
- }
- let fanned = match run_spawn_parallel_workers(
- state.prepared,
- state.action_root,
- cancel,
- run_context,
- )
- .await
- {
- Ok(fanned) => fanned,
- Err(TinyAgentsError::Cancelled) => {
- tracing::debug!(
- phase = "worker",
- "[spawn_parallel_agents] fanout_cancelled"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(
- "worker",
- )));
- }
- Err(err) => return Err(err),
- };
- Ok(NodeResult::Update(SpawnParallelUpdate::Fanned(fanned)))
- }
- },
- )
- .add_node(
- phases[3],
- move |state: SpawnParallelState, _ctx: NodeContext| {
- let parent_session = parent_for_collect.clone();
- let progress_sink = progress_for_collect.clone();
- let cancel = cancel_for_collect.clone();
- async move {
- if state.cancelled_phase.is_some() || state.rejection.is_some() {
- return Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(
- "collect",
- )));
- }
- if cancel.is_cancelled() {
- tracing::debug!(
- phase = "collect",
- "[spawn_parallel_agents] graph_cancelled_at_boundary"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(
- "collect",
- )));
- }
- let mut results = state.immediate_results;
- for result in state.fanned_results {
- project_spawn_parallel_result(
- &parent_session,
- progress_sink.as_ref(),
- &result,
- )
- .await;
- results.push(result);
- }
- Ok(NodeResult::Update(SpawnParallelUpdate::Results(results)))
- }
- },
- )
- .add_node(
- phases[4],
- move |state: SpawnParallelState, _ctx: NodeContext| {
- let parent_session = parent_for_finalize.clone();
- let cancel = cancel_for_finalize.clone();
- async move {
- if state.cancelled_phase.is_some() {
- return Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(
- "finalize",
- )));
- }
- if cancel.is_cancelled() {
- tracing::debug!(
- phase = "finalize",
- "[spawn_parallel_agents] graph_cancelled_at_boundary"
- );
- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(
- "finalize",
- )));
- }
- if let Some(message) = state.rejection {
- return Ok(NodeResult::Update(SpawnParallelUpdate::Rejected(message)));
- }
- let collected = collect_spawn_parallel_results(&parent_session, state.results);
- Ok(NodeResult::Update(SpawnParallelUpdate::Collected(
- collected,
- )))
- }
- },
- )
- .add_edge(phases[0], phases[1])
- .add_edge(phases[1], phases[2])
- .add_edge(phases[2], phases[3])
- .add_edge(phases[3], phases[4])
- .set_entry(phases[0])
- .set_finish(phases[4])
- .compile()
- .map_err(|e| format!("spawn_parallel_agents graph compile failed: {e}"))?
- .with_event_sink(Arc::new(
- crate::agent::tinyagents::observability::GraphTracingSink::new(label),
- ))
- // Adapter-first landing of the crate-native per-node RetryPolicy
- // (tinyagents 1.5.0 `CompiledGraph::with_node_retry`). Conservative:
- // `max_attempts(1)` preserves today's single-attempt phase semantics
- // exactly (no bespoke retry glue existed on these phases) and backoff
- // sleeping stays off (the default). Per-worker fanout resilience is
- // owned inside the worker/collect phases, not the phase-graph node loop;
- // this wires the crate seam so a future slice can raise the attempt cap
- // without re-plumbing.
- .with_node_retry(RetryPolicy::default().with_max_attempts(1));
-
- tracing::debug!(
- parent_session = %parent_session,
- "[spawn_parallel_agents] running graph fanout"
- );
- let execution = graph
- .run(SpawnParallelState::for_execution(
- tasks,
- max_parallel,
- action_root,
- ))
- .await
- .map_err(|e| format!("spawn_parallel_agents graph run failed: {e}"))?;
-
- if let Some(phase) = execution.state.cancelled_phase {
- return Ok(SpawnParallelGraphOutcome::Cancelled(format!(
- "spawn_parallel_agents cancelled at {phase}"
- )));
- }
- if let Some(message) = execution.state.rejection {
- return Ok(SpawnParallelGraphOutcome::Rejected(message));
- }
- execution
- .state
- .collected
- .map(SpawnParallelGraphOutcome::Collected)
- .ok_or_else(|| "spawn_parallel_agents graph finished without collected results".to_string())
-}
-
-/// Structure-only topology of the `spawn_parallel_agents` graph.
-pub(crate) fn spawn_parallel_graph_topology() -> Result<GraphTopology, String> {
- Ok(build_spawn_parallel_graph()?.topology())
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs
deleted file mode 100644
index 68e6b6d3b8..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/request.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-//! Request parsing and structural validation for `spawn_parallel_agents`,
-//! before any policy or workspace decision is made.
-
-/// One requested worker in a `spawn_parallel_agents` call.
-#[derive(Debug, Clone, serde::Deserialize)]
-pub(crate) struct ParallelAgentTask {
- pub(crate) agent_id: String,
- pub(crate) prompt: String,
- #[serde(default)]
- pub(crate) context: Option<String>,
- #[serde(default)]
- pub(crate) toolkit: Option<String>,
- #[serde(default)]
- pub(crate) ownership: Option<String>,
- /// File-isolation strategy for this worker: `"none"` (default) or
- /// `"worktree"` (dedicated git worktree checkout).
- #[serde(default)]
- pub(crate) isolation: Option<String>,
- /// Worktree base ref: `"head"` (default) or `"fresh"`.
- #[serde(default)]
- pub(crate) base_ref: Option<String>,
-}
-
-/// Decode and validate the request batch before the live worker fanout.
-///
-/// This is the first real `validate`-node responsibility moved out of the tool
-/// wrapper. Effectful worktree creation now runs in the graph path after the
-/// action root and worker definitions are resolved.
-fn validate_spawn_parallel_tasks(
- args: &serde_json::Value,
- max_parallel: Option<usize>,
-) -> Result<Vec<ParallelAgentTask>, String> {
- let tasks_value = args
- .get("tasks")
- .cloned()
- .ok_or_else(|| "Missing 'tasks' parameter".to_string())?;
- let tasks: Vec<ParallelAgentTask> =
- serde_json::from_value(tasks_value).map_err(|e| format!("Invalid tasks array: {e}"))?;
-
- if tasks.len() < 2 {
- return Err("spawn_parallel_agents requires at least two tasks".to_string());
- }
- if let Some(max_parallel) = max_parallel {
- if tasks.len() > max_parallel {
- return Err(format!(
- "spawn_parallel_agents received {} tasks but max_parallel_tools is {}",
- tasks.len(),
- max_parallel
- ));
- }
- }
-
- Ok(tasks)
-}
-
-pub(crate) enum SpawnParallelTaskValidationError {
- MissingTasks(String),
- InvalidTasks(String),
- Rejected(String),
-}
-
-pub(crate) fn validate_spawn_parallel_tool_request(
- args: &serde_json::Value,
- max_parallel: Option<usize>,
-) -> Result<Vec<ParallelAgentTask>, SpawnParallelTaskValidationError> {
- validate_spawn_parallel_tasks(args, max_parallel).map_err(|message| {
- if message == "Missing 'tasks' parameter" {
- SpawnParallelTaskValidationError::MissingTasks(message)
- } else if message.starts_with("Invalid tasks array:") {
- SpawnParallelTaskValidationError::InvalidTasks(message)
- } else {
- SpawnParallelTaskValidationError::Rejected(message)
- }
- })
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs
index 23a528b49a..d235cb3d03 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs
@@ -1,6 +1,10 @@
-//! Public entry points for running the `spawn_parallel_agents` graph:
-//! resolving the parent turn context and agent registry, then handing off to
-//! [`run_spawn_parallel_execution_graph`](super::graph::run_spawn_parallel_execution_graph).
+//! Host-side execution of an already-decoded `spawn_parallel_agents` batch.
+//!
+//! The fixed phase graph formerly here duplicated the graph crate's bounded
+//! fanout facility while capturing OpenHuman-only policy, progress, and
+//! execution adapters in every node. The tool now decodes its JSON contract;
+//! this module runs the host stages directly and delegates concurrent work to
+//! [`tinyagents_graph::parallel::map_reduce`] in `workers`.
use std::path::PathBuf;
@@ -9,54 +13,20 @@ use tinytools::WorkspaceDescriptor;
use crate::agent::harness::definition::AgentDefinitionRegistry;
-use super::collect::SpawnParallelGraphOutcome;
-use super::graph::run_spawn_parallel_execution_graph;
-use super::request::validate_spawn_parallel_tool_request;
+use super::collect::{
+ collect_spawn_parallel_results, project_spawn_parallel_result, SpawnParallelGraphOutcome,
+};
+use super::dispatch::stage_spawn_parallel_workers_from_defs;
use super::staging::snapshot_agent_definitions;
+use super::types::ParallelAgentTask;
+use super::workers::run_spawn_parallel_workers;
-pub(crate) async fn run_spawn_parallel_graph(
- args: serde_json::Value,
-) -> Result<SpawnParallelGraphOutcome, String> {
- run_spawn_parallel_graph_with_workspace(args, None).await
-}
-
-pub(crate) async fn run_spawn_parallel_graph_with_workspace(
- args: serde_json::Value,
- parent_workspace_descriptor: Option<WorkspaceDescriptor>,
-) -> Result<SpawnParallelGraphOutcome, String> {
- run_spawn_parallel_graph_with_cancellation_and_workspace(
- args,
- CancellationToken::new(),
- parent_workspace_descriptor,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- )
- .await
-}
-
-pub(crate) async fn run_spawn_parallel_graph_with_cancellation(
- args: serde_json::Value,
- cancel: CancellationToken,
-) -> Result<SpawnParallelGraphOutcome, String> {
- run_spawn_parallel_graph_with_cancellation_and_workspace(
- args,
- cancel,
- None,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- )
- .await
-}
-
-pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(
- args: serde_json::Value,
+pub(crate) async fn run_spawn_parallel_tasks_with_cancellation_and_workspace(
+ tasks: Vec<ParallelAgentTask>,
cancel: CancellationToken,
parent_workspace_descriptor: Option<WorkspaceDescriptor>,
run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> Result<SpawnParallelGraphOutcome, String> {
- let tasks = match validate_spawn_parallel_tool_request(&args, None) {
- Ok(tasks) => tasks,
- Err(err) => return Ok(SpawnParallelGraphOutcome::InvalidRequest(err)),
- };
-
let parent = match run_context.parent.clone() {
Some(parent) => parent,
None => {
@@ -89,19 +59,73 @@ pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(
let action_root =
resolve_spawn_parallel_action_root(parent_workspace_descriptor.as_ref()).await;
let definitions = snapshot_agent_definitions(registry);
- let outcome = run_spawn_parallel_execution_graph(
+ if cancel.is_cancelled() {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at validate".to_string(),
+ ));
+ }
+ if tasks.len() > max_parallel {
+ return Ok(SpawnParallelGraphOutcome::Rejected(format!(
+ "spawn_parallel_agents received {} tasks but max_parallel_tools is {}",
+ tasks.len(),
+ max_parallel
+ )));
+ }
+ if cancel.is_cancelled() {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at dispatch".to_string(),
+ ));
+ }
+ let (prepared, immediate_results) = stage_spawn_parallel_workers_from_defs(
&parent_session,
- progress_sink,
+ progress_sink.as_ref(),
tasks,
- max_parallel,
- definitions,
- parent,
+ &definitions,
+ &parent,
+ action_root.as_deref(),
+ parent_workspace_descriptor.as_ref(),
+ )
+ .await;
+ if cancel.is_cancelled() {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at worker".to_string(),
+ ));
+ }
+ let fanned = match run_spawn_parallel_workers(
+ prepared,
action_root,
- cancel,
- parent_workspace_descriptor,
+ cancel.clone(),
run_context,
)
- .await?;
+ .await
+ {
+ Ok(fanned) => fanned,
+ Err(tinyagents_harness::TinyAgentsError::Cancelled) => {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at worker".to_string(),
+ ));
+ }
+ Err(err) => return Err(err.to_string()),
+ };
+ if cancel.is_cancelled() {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at collect".to_string(),
+ ));
+ }
+ let mut results = immediate_results;
+ for result in fanned {
+ project_spawn_parallel_result(&parent_session, progress_sink.as_ref(), &result).await;
+ results.push(result);
+ }
+ if cancel.is_cancelled() {
+ return Ok(SpawnParallelGraphOutcome::Cancelled(
+ "spawn_parallel_agents cancelled at finalize".to_string(),
+ ));
+ }
+ let outcome = SpawnParallelGraphOutcome::Collected(collect_spawn_parallel_results(
+ &parent_session,
+ results,
+ ));
match &outcome {
SpawnParallelGraphOutcome::Collected(collected) => {
tracing::debug!(
@@ -120,12 +144,6 @@ pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(
"[spawn_parallel_agents] rejected_by_graph_validate"
);
}
- SpawnParallelGraphOutcome::InvalidRequest(_) => {
- tracing::debug!(
- parent_session = %parent_session,
- "[spawn_parallel_agents] invalid_request_after_graph_run"
- );
- }
SpawnParallelGraphOutcome::Cancelled(message) => {
tracing::debug!(
parent_session = %parent_session,
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
index c00b8a418b..0b6a5144cc 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
@@ -23,10 +23,10 @@ use crate::agent::harness::definition::{
AgentDefinition, AgentDefinitionRegistry, SandboxMode, ToolScope,
};
use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::worktree::BaseRef;
+use tinyagents_harness::workspace::GitWorktreeBaseRef;
use tinytools::PermissionLevel;
-use super::request::ParallelAgentTask;
+use super::types::ParallelAgentTask;
/// Prepared worker ready for the live dispatch/worker phases.
pub(crate) struct PreparedParallelTask {
@@ -79,7 +79,7 @@ pub(crate) enum WorkerDispatchMode {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ParallelWorktreeRequest {
SharedWorkspace,
- Isolated { base_ref: BaseRef },
+ Isolated { base_ref: GitWorktreeBaseRef },
}
pub(crate) fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWorktreeRequest {
@@ -91,7 +91,7 @@ pub(crate) fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWor
.unwrap_or(false);
if isolated {
ParallelWorktreeRequest::Isolated {
- base_ref: BaseRef::parse(task.base_ref.as_deref()),
+ base_ref: GitWorktreeBaseRef::parse(task.base_ref.as_deref()),
}
} else {
ParallelWorktreeRequest::SharedWorkspace
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs
index ea938b965c..bc02dfa80a 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs
@@ -3,14 +3,34 @@
use std::path::PathBuf;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use tinytools::WorkspaceDescriptor;
-use super::request::ParallelAgentTask;
use crate::agent::harness::definition::AgentDefinition;
use super::staging::WorkerDispatchMode;
+/// One worker admitted by the `spawn_parallel_agents` tool.
+///
+/// This is intentionally a host request contract: its `toolkit`, ownership
+/// syntax, and worktree options are OpenHuman product policy. The tool owns
+/// JSON decoding; the execution pipeline receives this typed value only.
+#[derive(Debug, Clone, Deserialize)]
+pub(crate) struct ParallelAgentTask {
+ pub(crate) agent_id: String,
+ pub(crate) prompt: String,
+ #[serde(default)]
+ pub(crate) context: Option<String>,
+ #[serde(default)]
+ pub(crate) toolkit: Option<String>,
+ #[serde(default)]
+ pub(crate) ownership: Option<String>,
+ #[serde(default)]
+ pub(crate) isolation: Option<String>,
+ #[serde(default)]
+ pub(crate) base_ref: Option<String>,
+}
+
/// A staged worker with everything the fanout needs: resolved definition,
/// prompt (with any ownership boundary applied), and worktree placement.
#[derive(Clone)]
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs
index 61cd710c1c..d8aa0b4f8d 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs
@@ -148,8 +148,7 @@ async fn run_one_parallel_task(
.map(|p| p.to_string_lossy().to_string());
let (changed_files, dirty_status) = match (&worktree_path, &repo_root) {
(Some(wt), Some(root)) => {
- use crate::agent::orchestration::worktree;
- match worktree::status(root, wt) {
+ match tinyagents_harness::workspace::git_worktree_status(root, wt) {
Ok(st) => {
tracing::debug!(
task_id = %task_id,
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
index 0c633bc811..10b8afde38 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
@@ -7,11 +7,10 @@ use crate::agent::orchestration::spawn_parallel_graph::with_ownership_boundary;
use crate::agent::orchestration::spawn_parallel_graph::ParallelAgentLineage;
#[cfg(test)]
use crate::agent::orchestration::spawn_parallel_graph::ParallelAgentResult;
-#[cfg(test)]
use crate::agent::orchestration::spawn_parallel_graph::ParallelAgentTask;
use crate::agent::orchestration::spawn_parallel_graph::{
- format_spawn_parallel_success, run_spawn_parallel_graph_with_cancellation_and_workspace,
- SpawnParallelGraphOutcome, SpawnParallelTaskValidationError,
+ format_spawn_parallel_success, run_spawn_parallel_tasks_with_cancellation_and_workspace,
+ SpawnParallelGraphOutcome,
};
use async_trait::async_trait;
use serde_json::json;
@@ -88,8 +87,18 @@ pub(crate) async fn execute_spawn_parallel_agents(
run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> anyhow::Result<ToolResult> {
tracing::debug!("[spawn_parallel_agents] execute entry");
- let outcome = run_spawn_parallel_graph_with_cancellation_and_workspace(
- args,
+ let tasks = match parse_parallel_agent_tasks(&args) {
+ Ok(tasks) => tasks,
+ Err(ParallelAgentTaskRequestError::MissingTasks(message))
+ | Err(ParallelAgentTaskRequestError::InvalidTasks(message)) => {
+ return Err(anyhow::anyhow!(message));
+ }
+ Err(ParallelAgentTaskRequestError::Rejected(message)) => {
+ return Ok(ToolResult::error(message));
+ }
+ };
+ let outcome = run_spawn_parallel_tasks_with_cancellation_and_workspace(
+ tasks,
cancellation,
workspace_descriptor,
run_context,
@@ -100,29 +109,39 @@ pub(crate) async fn execute_spawn_parallel_agents(
SpawnParallelGraphOutcome::Collected(collected) => Ok(ToolResult::success(
format_spawn_parallel_success(&collected),
)),
- SpawnParallelGraphOutcome::InvalidRequest(
- SpawnParallelTaskValidationError::MissingTasks(message),
- ) => {
- tracing::debug!("[spawn_parallel_agents] missing_tasks_parameter");
- Err(anyhow::anyhow!(message))
- }
- SpawnParallelGraphOutcome::InvalidRequest(
- SpawnParallelTaskValidationError::InvalidTasks(message),
- ) => {
- tracing::debug!(error = %message, "[spawn_parallel_agents] invalid_tasks_array");
- Err(anyhow::anyhow!(message))
- }
- SpawnParallelGraphOutcome::InvalidRequest(SpawnParallelTaskValidationError::Rejected(
- message,
- )) => {
- tracing::debug!("[spawn_parallel_agents] rejected_too_few_tasks");
- Ok(ToolResult::error(message))
- }
SpawnParallelGraphOutcome::Rejected(message) => Ok(ToolResult::error(message)),
SpawnParallelGraphOutcome::Cancelled(message) => Ok(ToolResult::error(message)),
}
}
+/// Decode the tool's JSON request before it reaches host execution policy.
+///
+/// This remains beside the tool rather than becoming a TinyAgents API: the
+/// parameter shape includes OpenHuman-specific ownership, toolkit, and
+/// worktree-policy fields.
+fn parse_parallel_agent_tasks(
+ args: &serde_json::Value,
+) -> Result<Vec<ParallelAgentTask>, ParallelAgentTaskRequestError> {
+ let tasks_value = args.get("tasks").cloned().ok_or_else(|| {
+ ParallelAgentTaskRequestError::MissingTasks("Missing 'tasks' parameter".into())
+ })?;
+ let tasks: Vec<ParallelAgentTask> = serde_json::from_value(tasks_value).map_err(|err| {
+ ParallelAgentTaskRequestError::InvalidTasks(format!("Invalid tasks array: {err}"))
+ })?;
+ if tasks.len() < 2 {
+ return Err(ParallelAgentTaskRequestError::Rejected(
+ "spawn_parallel_agents requires at least two tasks".into(),
+ ));
+ }
+ Ok(tasks)
+}
+
+enum ParallelAgentTaskRequestError {
+ MissingTasks(String),
+ InvalidTasks(String),
+ Rejected(String),
+}
+
#[async_trait]
impl Tool for SpawnParallelAgentsTool {
fn name(&self) -> &str {
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree.rs b/crates/openhuman-core/src/agent/orchestration/worktree.rs
index 67099a4c5b..5f88966966 100644
--- a/crates/openhuman-core/src/agent/orchestration/worktree.rs
+++ b/crates/openhuman-core/src/agent/orchestration/worktree.rs
@@ -12,8 +12,7 @@
//! The git plumbing itself is **TinyAgents'**
//! ([`tinyagents_harness::workspace::git`]): worktree create/list/status/diff/
//! remove, repo-root validation, run-id sanitizing, and cross-worker overlap
-//! detection are host-agnostic and are re-exported here under their historical
-//! OpenHuman names so call sites and the RPC surface are unchanged.
+//! detection. Callers import that surface directly from the harness.
//!
//! What stays in OpenHuman is the part that depends on *this* host: the
//! [`OpenHumanWorktreeIsolation`] adapter, which stamps an
@@ -29,7 +28,8 @@
//! - Every operation validates that `repo_root` is a real git repository
//! first (via `git rev-parse --is-inside-work-tree`), so a stray path can
//! never be mutated.
-//! - [`remove`] refuses to delete a **dirty** worktree unless `force = true`.
+//! - `remove_git_worktree` refuses to delete a **dirty** worktree unless
+//! `force = true`.
//! Clean worktrees can be auto-reclaimed; dirty ones require an explicit
//! user decision (acceptance criterion of #3376).
//!
@@ -39,26 +39,12 @@
use std::path::{Path, PathBuf};
-use tinyagents_harness::workspace::{GitWorktreeIsolation, WorkspaceIsolation};
+use tinyagents_harness::workspace::{GitWorktreeBaseRef, GitWorktreeIsolation, WorkspaceIsolation};
use tinytools::{SandboxMode, WorkspaceDescriptor};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
-// The git worktree surface is TinyAgents'. These aliases keep the historical
-// OpenHuman spellings — `worktree::create`, `worktree::BaseRef`,
-// `WorktreeStatus` — so the RPC schemas, tools, and tests that name them do not
-// change. `WorktreeStatus` in particular is serialized straight to the desktop
-// UI; it is field- and `serde`-identical to the crate type, pinned by
-// `worktree_status_serializes_with_stable_camel_case_keys`.
-pub use tinyagents_harness::workspace::{
- create_git_worktree as create, detect_worktree_overlaps as detect_overlaps,
- git_worktree_diff_summary as diff_summary, git_worktree_status as status,
- list_git_worktrees as list, remove_git_worktree as remove, GitWorktreeBaseRef as BaseRef,
- GitWorktreeError as WorktreeError, GitWorktreeStatus as WorktreeStatus,
- GIT_WORKTREE_SUBDIR as WORKTREE_SUBDIR,
-};
-
/// OpenHuman's [`WorkspaceIsolation`] adapter over the TinyAgents git-worktree
/// provider.
///
@@ -81,7 +67,7 @@ impl OpenHumanWorktreeIsolation {
}
/// Select which ref new worktrees branch from.
- pub fn with_base_ref(mut self, base_ref: BaseRef) -> Self {
+ pub fn with_base_ref(mut self, base_ref: GitWorktreeBaseRef) -> Self {
self.inner = self.inner.with_base_ref(base_ref);
self
}
@@ -224,7 +210,7 @@ pub fn enforce_workspace_path(
/// Rejection from [`enforce_workspace_path`].
///
-/// Separate from [`WorktreeError`] (which is TinyAgents' git-plumbing error)
+/// Separate from `GitWorktreeError` (which is TinyAgents' git-plumbing error)
/// because this gate is about OpenHuman's descriptor policy, not about git.
#[derive(Debug, thiserror::Error)]
pub enum WorkspacePathError {
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs b/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
index 92ba1e2565..a445040459 100644
--- a/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
@@ -19,11 +19,14 @@ use std::path::{Path, PathBuf};
use serde_json::{json, Map, Value};
-use crate::agent::orchestration::worktree::{self, WorktreeError, WorktreeStatus};
use crate::config::rpc as config_rpc;
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use crate::rpc::RpcOutcome;
+use tinyagents_harness::workspace::{
+ detect_worktree_overlaps, git_worktree_diff_summary, git_worktree_status, list_git_worktrees,
+ remove_git_worktree, GitWorktreeError, GitWorktreeStatus, GIT_WORKTREE_SUBDIR,
+};
/// Controller schemas exposed by the worktree manager.
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
@@ -190,9 +193,9 @@ fn handle_remove(params: Map<String, Value>) -> ControllerFuture {
fn list_view(root: &Path, cid: &str) -> Result<Value, String> {
// A non-git action_dir is normal (the user may not have opened a repo).
// Degrade to an empty list rather than surfacing an error to the panel.
- let all = match worktree::list(root) {
+ let all = match list_git_worktrees(root) {
Ok(list) => list,
- Err(WorktreeError::NotAGitRepo(p)) => {
+ Err(GitWorktreeError::NotAGitRepo(p)) => {
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] list.not_a_git_repo path={}", p.display());
return to_json(json!({ "worktrees": [], "overlaps": [] }));
}
@@ -205,7 +208,7 @@ fn list_view(root: &Path, cid: &str) -> Result<Value, String> {
// Only the isolated worker worktrees are management targets — never the
// main checkout. Filter to those nested under `.claude/worktrees`.
- let worktrees: Vec<WorktreeStatus> = all
+ let worktrees: Vec<GitWorktreeStatus> = all
.into_iter()
.filter(|w| is_managed_worktree(&w.path))
.collect();
@@ -223,7 +226,7 @@ fn list_view(root: &Path, cid: &str) -> Result<Value, String> {
/// Pure status logic anchored on a resolved `repo_root` — see [`list_view`].
fn status_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.path={}", path.display());
- let status = worktree::status(root, path).map_err(|e| {
+ let status = git_worktree_status(root, path).map_err(|e| {
let s = e.to_string();
log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.error err={s}");
s
@@ -234,7 +237,7 @@ fn status_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
/// Pure diff logic anchored on a resolved `repo_root` — see [`list_view`].
fn diff_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.path={}", path.display());
- let summary = worktree::diff_summary(root, path).map_err(|e| {
+ let summary = git_worktree_diff_summary(root, path).map_err(|e| {
let s = e.to_string();
log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.error err={s}");
s
@@ -245,7 +248,7 @@ fn diff_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
/// Pure remove logic anchored on a resolved `repo_root` — see [`list_view`].
fn remove_view(root: &Path, path: &Path, force: bool, cid: &str) -> Result<Value, String> {
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.path={} force={force}", path.display());
- worktree::remove(root, path, force).map_err(|e| {
+ remove_git_worktree(root, path, force).map_err(|e| {
let s = e.to_string();
log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.error err={s}");
s
@@ -257,7 +260,7 @@ fn remove_view(root: &Path, path: &Path, force: bool, cid: &str) -> Result<Value
/// `true` when `path` is an isolated worker worktree (nested under the
/// `.claude/worktrees` convention dir), i.e. a manageable cleanup target.
fn is_managed_worktree(path: &Path) -> bool {
- let needle = std::path::Path::new(worktree::WORKTREE_SUBDIR);
+ let needle = std::path::Path::new(GIT_WORKTREE_SUBDIR);
let mut comps = needle.components();
let (Some(a), Some(b)) = (comps.next(), comps.next()) else {
return false;
@@ -269,7 +272,7 @@ fn is_managed_worktree(path: &Path) -> bool {
/// Compute cross-worktree file overlaps (a changed file touched by more than
/// one worktree), keyed for display by each worktree's branch (path fallback).
-fn overlaps_json(worktrees: &[WorktreeStatus]) -> Vec<Value> {
+fn overlaps_json(worktrees: &[GitWorktreeStatus]) -> Vec<Value> {
let per_worker: Vec<(String, Vec<PathBuf>)> = worktrees
.iter()
.filter(|w| !w.changed_files.is_empty())
@@ -281,7 +284,7 @@ fn overlaps_json(worktrees: &[WorktreeStatus]) -> Vec<Value> {
(label, w.changed_files.clone())
})
.collect();
- worktree::detect_overlaps(&per_worker)
+ detect_worktree_overlaps(&per_worker)
.into_iter()
.map(|(file, branches)| json!({ "file": file.to_string_lossy(), "branches": branches }))
.collect()
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree_schemas_tests.rs b/crates/openhuman-core/src/agent/orchestration/worktree_schemas_tests.rs
index db3fa4b15e..e21aa71d85 100644
--- a/crates/openhuman-core/src/agent/orchestration/worktree_schemas_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/worktree_schemas_tests.rs
@@ -1,5 +1,6 @@
use super::*;
use std::process::Command;
+use tinyagents_harness::workspace::{create_git_worktree, GitWorktreeBaseRef, GitWorktreeStatus};
/// `true` when `git` is invokable on this host. Tests that need real
/// `git worktree` plumbing skip (pass trivially) when it's absent, so a
@@ -59,7 +60,7 @@ fn list_view_surfaces_managed_worktree() {
return;
}
let (_tmp, root) = init_repo();
- let st = worktree::create(&root, "run-1", worktree::BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-1", GitWorktreeBaseRef::Head).expect("create");
assert!(
is_managed_worktree(&st.path),
"created under .claude/worktrees"
@@ -113,7 +114,7 @@ fn status_and_diff_views_round_trip_a_worktree() {
return;
}
let (_tmp, root) = init_repo();
- let st = worktree::create(&root, "run-2", worktree::BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-2", GitWorktreeBaseRef::Head).expect("create");
// `WorktreeStatus` serializes `rename_all = "camelCase"` → `isDirty`.
let status = status_view(&root, &st.path, "cid").expect("status ok");
@@ -130,7 +131,7 @@ fn remove_view_clears_a_clean_worktree() {
return;
}
let (_tmp, root) = init_repo();
- let st = worktree::create(&root, "run-3", worktree::BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-3", GitWorktreeBaseRef::Head).expect("create");
assert!(st.path.exists());
let removed = remove_view(&root, &st.path, false, "cid").expect("remove ok");
@@ -209,13 +210,13 @@ fn require_managed_worktree_path_enforces_absolute_and_managed() {
#[test]
fn overlaps_detected_across_branches() {
let worktrees = vec![
- WorktreeStatus {
+ GitWorktreeStatus {
path: PathBuf::from("/r/.claude/worktrees/a"),
branch: Some("worker/a".into()),
is_dirty: true,
changed_files: vec![PathBuf::from("src/lib.rs"), PathBuf::from("a.rs")],
},
- WorktreeStatus {
+ GitWorktreeStatus {
path: PathBuf::from("/r/.claude/worktrees/b"),
branch: Some("worker/b".into()),
is_dirty: true,
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs b/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs
index e702eae888..2cd9b8e131 100644
--- a/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs
@@ -7,6 +7,11 @@
use super::*;
use std::path::Path;
use std::process::Command;
+use tinyagents_harness::workspace::{
+ create_git_worktree, detect_worktree_overlaps, git_worktree_diff_summary, git_worktree_status,
+ list_git_worktrees, remove_git_worktree, GitWorktreeBaseRef, GitWorktreeError,
+ GitWorktreeStatus,
+};
/// `true` when `git` is invokable on this host.
fn git_available() -> bool {
@@ -51,8 +56,8 @@ fn validate_repo_root_rejects_non_repo() {
return;
}
let tmp = tempfile::tempdir().unwrap();
- let err = create(tmp.path(), "run-1", BaseRef::Head).unwrap_err();
- assert!(matches!(err, WorktreeError::NotAGitRepo(_)));
+ let err = create_git_worktree(tmp.path(), "run-1", GitWorktreeBaseRef::Head).unwrap_err();
+ assert!(matches!(err, GitWorktreeError::NotAGitRepo(_)));
}
#[test]
@@ -61,7 +66,7 @@ fn create_then_status_reports_clean_worktree() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-1", BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-1", GitWorktreeBaseRef::Head).expect("create");
assert!(st.path.exists(), "worktree dir should exist");
assert_eq!(st.branch.as_deref(), Some("worker/run-1"));
assert!(!st.is_dirty, "fresh worktree is clean");
@@ -79,9 +84,9 @@ fn list_includes_created_worktree() {
return;
}
let (_tmp, root) = init_repo();
- create(&root, "run-a", BaseRef::Head).expect("create a");
- create(&root, "run-b", BaseRef::Fresh).expect("create b");
- let all = list(&root).expect("list");
+ create_git_worktree(&root, "run-a", GitWorktreeBaseRef::Head).expect("create a");
+ create_git_worktree(&root, "run-b", GitWorktreeBaseRef::Fresh).expect("create b");
+ let all = list_git_worktrees(&root).expect("list");
// main worktree + the two we created
assert!(all.len() >= 3, "expected >=3 worktrees, got {}", all.len());
let branches: Vec<_> = all.iter().filter_map(|w| w.branch.clone()).collect();
@@ -95,12 +100,12 @@ fn status_detects_dirty_changes() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-dirty", BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-dirty", GitWorktreeBaseRef::Head).expect("create");
// Touch a tracked file + add an untracked one.
std::fs::write(st.path.join("README.md"), "changed\n").unwrap();
std::fs::write(st.path.join("new.txt"), "fresh\n").unwrap();
- let st2 = status(&root, &st.path).expect("status");
+ let st2 = git_worktree_status(&root, &st.path).expect("status");
assert!(st2.is_dirty, "worktree with edits must be dirty");
let names: Vec<String> = st2
.changed_files
@@ -117,11 +122,11 @@ fn diff_summary_lists_tracked_and_untracked() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-diff", BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-diff", GitWorktreeBaseRef::Head).expect("create");
std::fs::write(st.path.join("README.md"), "changed body\n").unwrap();
std::fs::write(st.path.join("brand_new.txt"), "x\n").unwrap();
- let summary = diff_summary(&root, &st.path).expect("diff");
+ let summary = git_worktree_diff_summary(&root, &st.path).expect("diff");
assert!(
summary.contains("README.md"),
"diff should mention tracked change: {summary}"
@@ -138,11 +143,11 @@ fn remove_refuses_dirty_without_force() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-keep", BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-keep", GitWorktreeBaseRef::Head).expect("create");
std::fs::write(st.path.join("README.md"), "dirty\n").unwrap();
- let err = remove(&root, &st.path, false).expect_err("must refuse dirty");
- assert!(matches!(err, WorktreeError::DirtyRefused(_)));
+ let err = remove_git_worktree(&root, &st.path, false).expect_err("must refuse dirty");
+ assert!(matches!(err, GitWorktreeError::DirtyRefused(_)));
assert!(st.path.exists(), "dirty worktree must NOT be deleted");
}
@@ -152,10 +157,10 @@ fn remove_force_deletes_dirty_worktree() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-force", BaseRef::Head).expect("create");
+ let st = create_git_worktree(&root, "run-force", GitWorktreeBaseRef::Head).expect("create");
std::fs::write(st.path.join("README.md"), "dirty\n").unwrap();
- remove(&root, &st.path, true).expect("force remove");
+ remove_git_worktree(&root, &st.path, true).expect("force remove");
assert!(!st.path.exists(), "force remove deletes the worktree dir");
}
@@ -165,19 +170,34 @@ fn remove_clean_worktree_succeeds() {
return;
}
let (_tmp, root) = init_repo();
- let st = create(&root, "run-clean", BaseRef::Head).expect("create");
- remove(&root, &st.path, false).expect("clean remove");
+ let st = create_git_worktree(&root, "run-clean", GitWorktreeBaseRef::Head).expect("create");
+ remove_git_worktree(&root, &st.path, false).expect("clean remove");
assert!(!st.path.exists(), "clean worktree removed without force");
}
#[test]
fn base_ref_parse_defaults_to_head() {
- assert_eq!(BaseRef::parse(None), BaseRef::Head);
- assert_eq!(BaseRef::parse(Some("head")), BaseRef::Head);
- assert_eq!(BaseRef::parse(Some("HEAD")), BaseRef::Head);
- assert_eq!(BaseRef::parse(Some("fresh")), BaseRef::Fresh);
- assert_eq!(BaseRef::parse(Some(" Fresh ")), BaseRef::Fresh);
- assert_eq!(BaseRef::parse(Some("garbage")), BaseRef::Head);
+ assert_eq!(GitWorktreeBaseRef::parse(None), GitWorktreeBaseRef::Head);
+ assert_eq!(
+ GitWorktreeBaseRef::parse(Some("head")),
+ GitWorktreeBaseRef::Head
+ );
+ assert_eq!(
+ GitWorktreeBaseRef::parse(Some("HEAD")),
+ GitWorktreeBaseRef::Head
+ );
+ assert_eq!(
+ GitWorktreeBaseRef::parse(Some("fresh")),
+ GitWorktreeBaseRef::Fresh
+ );
+ assert_eq!(
+ GitWorktreeBaseRef::parse(Some(" Fresh ")),
+ GitWorktreeBaseRef::Fresh
+ );
+ assert_eq!(
+ GitWorktreeBaseRef::parse(Some("garbage")),
+ GitWorktreeBaseRef::Head
+ );
}
// `sanitize_run_id` is TinyAgents-internal now; the identical assertions live
@@ -198,7 +218,7 @@ fn detect_overlaps_flags_shared_files() {
),
("w3".to_string(), vec![PathBuf::from("src/c.rs")]),
];
- let overlaps = detect_overlaps(&per_worker);
+ let overlaps = detect_worktree_overlaps(&per_worker);
// b.rs touched by w1+w2; c.rs touched by w2+w3; a.rs only w1 (no overlap).
assert_eq!(overlaps.len(), 2);
assert_eq!(
@@ -218,7 +238,7 @@ fn detect_overlaps_empty_when_disjoint() {
("w1".to_string(), vec![PathBuf::from("a.rs")]),
("w2".to_string(), vec![PathBuf::from("b.rs")]),
];
- assert!(detect_overlaps(&per_worker).is_empty());
+ assert!(detect_worktree_overlaps(&per_worker).is_empty());
}
#[test]
@@ -228,10 +248,10 @@ fn detect_overlaps_ignores_intra_worker_duplicates() {
"w1".to_string(),
vec![PathBuf::from("a.rs"), PathBuf::from("a.rs")],
)];
- assert!(detect_overlaps(&per_worker).is_empty());
+ assert!(detect_worktree_overlaps(&per_worker).is_empty());
}
-/// Pins the JSON-RPC wire shape of [`WorktreeStatus`].
+/// Pins the JSON-RPC wire shape of [`GitWorktreeStatus`].
///
/// `worktree_schemas.rs` serializes this type straight to the desktop UI, so a
/// renamed or dropped field surfaces as an empty worktree panel rather than a
@@ -240,7 +260,7 @@ fn detect_overlaps_ignores_intra_worker_duplicates() {
/// silently changing the contract.
#[test]
fn worktree_status_serializes_with_stable_camel_case_keys() {
- let status = WorktreeStatus {
+ let status = GitWorktreeStatus {
path: std::path::PathBuf::from("/tmp/repo/.claude/worktrees/run-1"),
branch: Some("agent/run-1".to_string()),
is_dirty: true,
@@ -250,7 +270,7 @@ fn worktree_status_serializes_with_stable_camel_case_keys() {
],
};
- let value = serde_json::to_value(&status).expect("WorktreeStatus serializes");
+ let value = serde_json::to_value(&status).expect("GitWorktreeStatus serializes");
let object = value.as_object().expect("serializes to a JSON object");
let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
@@ -270,7 +290,7 @@ fn worktree_status_serializes_with_stable_camel_case_keys() {
);
// A detached worktree serializes `branch` as null, not as an omitted key.
- let detached = WorktreeStatus {
+ let detached = GitWorktreeStatus {
branch: None,
..status
};
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology.rs b/crates/openhuman-core/src/agent/tinyagents/topology.rs
index f12bf3dd7c..0338d2af11 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology.rs
@@ -61,14 +61,8 @@ pub(crate) fn all_graph_topologies() -> Vec<GraphTopologyReport> {
out.push(describe("agent:researcher", &t));
}
- if let Ok(t) =
- crate::agent::orchestration::spawn_parallel_graph::spawn_parallel_graph_topology()
- {
- out.push(describe("spawn_parallel_graph", &t));
- }
-
- // Not exported: generic item-count-driven `map_reduce` fan-outs whose node
- // set is determined per run rather than by a fixed named topology.
+ // Not exported: item-count-driven `map_reduce` fan-outs whose node set is
+ // determined per run rather than by a fixed named topology.
out
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
index e6cd7a5cf8..ee303363d8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
@@ -20,11 +20,7 @@ fn all_topologies_includes_the_member_graph() {
#[test]
fn all_topologies_includes_delegation_and_workflow_scheduler() {
let reports = all_graph_topologies();
- for name in [
- "delegation",
- "workflow_runs:scheduler_preview",
- "spawn_parallel_graph",
- ] {
+ for name in ["delegation", "workflow_runs:scheduler_preview"] {
let report = reports
.iter()
.find(|r| r.name == name)