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: correct staging logic in parallel graph and RPC source sync
Steven Enamakelbc08d7e41fc4
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.rsnew file mode 100644index 0000000000..a8b3d8c3c3--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs@@ -0,0 +1,773 @@+//! Turning a validated task batch into staged [`SpawnParallelWorker`] values:+//! OpenHuman policy admission (identity, allowlist, toolkit requirement,+//! shared-workspace write claims), crate-side arbitration over those claims,+//! worktree preflight, and progress/event projection for the `dispatch` phase.+//!+//! **Write safety.** Whether a worker *needs* a claim on the shared workspace is+//! an OpenHuman decision — it reads sandbox mode, tool permissions and the+//! isolation request. Whether the claims of a whole batch can be granted+//! together is not, and goes through+//! [`plan_shared_workspace_dispatch`](tinyagents_graph::parallel::plan_shared_workspace_dispatch).+//! The rejection sentences stay here, which is why the crate reports conflicts+//! as data.++use std::collections::HashMap;+use std::path::{Path, PathBuf};++use tinyagents_graph::parallel::{+ parse_relative_claim_paths, plan_shared_workspace_dispatch, ClaimConflict, ClaimPathError,+ DispatchMode, WorkspaceClaim,+};+use tinyagents_harness::workspace::WorkspaceDescriptor;+use tokio::sync::mpsc::Sender;++use crate::agent::file_state;+use crate::agent::harness::definition::{+ AgentDefinition, AgentDefinitionRegistry, SandboxMode, ToolScope,+};+use crate::agent::harness::fork_context::ParentExecutionContext;+use crate::agent::orchestration::worktree::{self, BaseRef};+use crate::agent::progress::AgentProgress;+use crate::tools::PermissionLevel;++use super::request::ParallelAgentTask;+use super::types::{ParallelAgentLineage, ParallelAgentResult, SpawnParallelWorker};++/// Prepared worker ready for the live dispatch/worker phases.+pub(crate) struct PreparedParallelTask {+ pub(crate) definition: AgentDefinition,+ pub(crate) prompt: String,+ pub(crate) task: ParallelAgentTask,+ pub(crate) task_id: String,+ pub(crate) dispatch_mode: WorkerDispatchMode,+}++impl PreparedParallelTask {+ /// How this worker will be dispatched relative to its siblings.+ ///+ /// Exposed so the write-safety decision can be asserted directly: it is the+ /// one property of a preflight whose regression corrupts a shared checkout+ /// silently rather than failing a run.+ pub(crate) fn dispatch_mode(&self) -> WorkerDispatchMode {+ self.dispatch_mode+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ParallelTaskRejectionKind {+ MissingAgentOrPrompt,+ UnknownAgent,+ OutsideAllowlist,+ MissingToolkit,+ RequiresIsolation,+}++pub(crate) struct ParallelTaskRejection {+ pub(crate) task_id: String,+ pub(crate) agent_id: String,+ pub(crate) error: String,+ pub(crate) ownership: Option<String>,+ pub(crate) kind: ParallelTaskRejectionKind,+}++pub(crate) enum SpawnParallelTaskPreflight {+ Prepared(PreparedParallelTask),+ Rejected(ParallelTaskRejection),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum WorkerDispatchMode {+ Parallel,+ SerialSharedWorkspaceWrite,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ParallelWorktreeRequest {+ SharedWorkspace,+ Isolated { base_ref: BaseRef },+}++fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWorktreeRequest {+ let isolated = task+ .isolation+ .as_deref()+ .map(str::trim)+ .map(|s| s.eq_ignore_ascii_case("worktree"))+ .unwrap_or(false);+ if isolated {+ ParallelWorktreeRequest::Isolated {+ base_ref: BaseRef::parse(task.base_ref.as_deref()),+ }+ } else {+ ParallelWorktreeRequest::SharedWorkspace+ }+}++fn disallowed_tool_matches(disallowed: &[String], name: &str) -> bool {+ disallowed.iter().any(|entry| {+ if let Some(prefix) = entry.strip_suffix('*') {+ name.starts_with(prefix)+ } else {+ entry == name+ }+ })+}++fn definition_visible_tool_permissions(+ definition: &AgentDefinition,+ parent: &ParentExecutionContext,+) -> Vec<(String, PermissionLevel)> {+ let skill_prefix = definition+ .skill_filter+ .as_ref()+ .map(|skill| format!("{skill}__"));+ parent+ .all_tools+ .iter()+ .filter_map(|tool| {+ let name = tool.name();+ if disallowed_tool_matches(&definition.disallowed_tools, name) {+ return None;+ }+ if let Some(prefix) = skill_prefix.as_deref() {+ if !name.starts_with(prefix) {+ return None;+ }+ }+ let allowed = match &definition.tools {+ ToolScope::Wildcard => true,+ ToolScope::Named(names) => {+ names.iter().any(|allowed| allowed == name)+ || definition.extra_tools.iter().any(|extra| extra == name)+ || (crate::inference::tokenjuice::is_recovery_tool(name)+ && !names.is_empty())+ }+ };+ allowed.then(|| (name.to_string(), tool.permission_level()))+ })+ .collect()+}++fn shared_workspace_write_capable_tools(+ definition: &AgentDefinition,+ parent: &ParentExecutionContext,+) -> Vec<String> {+ let mut write_capable_tools = definition_visible_tool_permissions(definition, parent)+ .into_iter()+ .filter(|(_, level)| *level > PermissionLevel::ReadOnly)+ .map(|(name, level)| format!("{name}:{level}"))+ .collect::<Vec<_>>();+ write_capable_tools.sort();+ write_capable_tools.dedup();+ write_capable_tools+}++fn shared_workspace_write_preview(write_capable_tools: &[String]) -> String {+ let preview = write_capable_tools+ .iter()+ .take(6)+ .cloned()+ .collect::<Vec<_>>()+ .join(", ");+ let suffix = if write_capable_tools.len() > 6 {+ format!(", +{} more", write_capable_tools.len() - 6)+ } else {+ String::new()+ };+ format!("{preview}{suffix}")+}++/// Parse OpenHuman's `files: a.rs, b.rs` ownership syntax into claimed paths.+///+/// The `files:` prefix is this tool's parameter shape, so it is stripped here;+/// validating what follows is generic and belongs to+/// [`parse_relative_claim_paths`]. Its typed rejection is rendered into the+/// sentence the model reads at this boundary, which is why the crate returns+/// data rather than a message.+fn ownership_file_paths(ownership: Option<&str>) -> Result<Vec<PathBuf>, String> {+ let Some(ownership) = ownership.map(str::trim).filter(|s| !s.is_empty()) else {+ return Ok(Vec::new());+ };+ let Some(rest) = ownership.strip_prefix("files:") else {+ return Ok(Vec::new());+ };+ parse_relative_claim_paths(rest).map_err(|err| {+ let raw = match &err {+ ClaimPathError::Absolute { raw } | ClaimPathError::Escaping { raw } => raw,+ };+ format!("ownership path '{raw}' must be a relative file path under the workspace")+ })+}++fn shared_workspace_write_claim(+ task: &ParallelAgentTask,+ definition: &AgentDefinition,+ parent: &ParentExecutionContext,+) -> Result<Option<Vec<PathBuf>>, String> {+ if matches!(+ worktree_request_for_task(task),+ ParallelWorktreeRequest::Isolated { .. }+ ) {+ return Ok(None);+ }+ if matches!(definition.sandbox_mode, SandboxMode::ReadOnly) {+ return Ok(None);+ }+ let write_capable_tools = shared_workspace_write_capable_tools(definition, parent);+ if write_capable_tools.is_empty() {+ return Ok(None);+ }+ let paths = ownership_file_paths(task.ownership.as_deref())?;+ if paths.is_empty() {+ return Err(format!(+ "agent '{}' can use write/execute tools in the shared workspace ({}); \+ set isolation=\"worktree\" for edit-capable parallel workers, use a read-only agent, \+ or provide disjoint files: ownership for serial fallback",+ definition.id,+ shared_workspace_write_preview(&write_capable_tools)+ ));+ }+ Ok(Some(paths))+}++pub(crate) fn spawn_parallel_lineage(+ parent_session: &str,+ session_parent_prefix: Option<&str>,+ task_id: &str,+) -> ParallelAgentLineage {+ let root_session = session_parent_prefix+ .and_then(|prefix| prefix.split("__").next())+ .filter(|root| !root.is_empty())+ .unwrap_or(parent_session);+ ParallelAgentLineage {+ parent_session: parent_session.to_string(),+ root_session: root_session.to_string(),+ child_task_id: task_id.to_string(),+ }+}++async fn create_spawn_parallel_worktree(+ parent_session: &str,+ action_root: Option<&Path>,+ task_id: &str,+ definition: &AgentDefinition,+ task: &ParallelAgentTask,+ session_parent_prefix: Option<&str>,+) -> Result<Option<WorkspaceDescriptor>, ParallelAgentResult> {+ match worktree_request_for_task(task) {+ ParallelWorktreeRequest::SharedWorkspace => Ok(None),+ ParallelWorktreeRequest::Isolated { base_ref } => match action_root {+ Some(repo_root) => {+ let sandbox = match definition.sandbox_mode {+ SandboxMode::Sandboxed => tinyagents_harness::tool::SandboxMode::Required,+ SandboxMode::None | SandboxMode::ReadOnly => {+ tinyagents_harness::tool::SandboxMode::Inherit+ }+ };+ let isolation = worktree::OpenHumanWorktreeIsolation::new(repo_root)+ .with_base_ref(base_ref)+ .with_sandbox(sandbox);+ match isolation.prepare(task_id, Some(&definition.id)).await {+ Ok(descriptor) => {+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %task_id,+ worktree = %descriptor.root.display(),+ policy_id = %descriptor.policy_id,+ base_ref = base_ref.as_str(),+ "[spawn_parallel_agents] prepared isolated workspace descriptor"+ );+ Ok(Some(descriptor))+ }+ Err(err) => {+ tracing::warn!(+ parent_session = %parent_session,+ task_id = %task_id,+ error = %err,+ "[spawn_parallel_agents] workspace_prepare_failed"+ );+ Err(ParallelAgentResult {+ task_id: task_id.to_string(),+ agent_id: definition.id.clone(),+ lineage: spawn_parallel_lineage(+ parent_session,+ session_parent_prefix,+ task_id,+ ),+ success: false,+ output: None,+ error: Some(format!("worktree isolation failed: {err}")),+ ownership: task.ownership.clone(),+ elapsed_ms: 0,+ iterations: 0,+ stale_parent_reads: Vec::new(),+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ })+ }+ }+ }+ None => {+ tracing::warn!(+ parent_session = %parent_session,+ task_id = %task_id,+ "[spawn_parallel_agents] worktree_requested_but_no_action_dir"+ );+ Err(ParallelAgentResult {+ task_id: task_id.to_string(),+ agent_id: definition.id.clone(),+ lineage: spawn_parallel_lineage(parent_session, session_parent_prefix, task_id),+ success: false,+ output: None,+ error: Some(+ "worktree isolation requested but action_dir is unavailable".to_string(),+ ),+ ownership: task.ownership.clone(),+ elapsed_ms: 0,+ iterations: 0,+ stale_parent_reads: Vec::new(),+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ })+ }+ },+ }+}++pub(crate) fn snapshot_agent_definitions(+ registry: &AgentDefinitionRegistry,+) -> HashMap<String, AgentDefinition> {+ registry+ .list()+ .into_iter()+ .map(|definition| (definition.id.clone(), definition.clone()))+ .collect()+}++/// One task that cleared every OpenHuman policy gate and is awaiting the+/// shared-workspace arbitration verdict.+struct AdmittedParallelTask {+ definition: AgentDefinition,+ prompt: String,+ task: ParallelAgentTask,+ task_id: String,+ /// What this worker needs from the shared workspace, in the crate's terms.+ claim: WorkspaceClaim,+}++pub(crate) fn prepare_spawn_parallel_tasks_from_defs(+ tasks: Vec<ParallelAgentTask>,+ definitions: &HashMap<String, AgentDefinition>,+ parent: &ParentExecutionContext,+) -> Vec<SpawnParallelTaskPreflight> {+ // Pass 1 — OpenHuman policy. Identity, the parent's subagent allowlist, the+ // integrations toolkit requirement, and whether a worker can write the+ // shared workspace at all are all product decisions, so they are settled+ // here and rejected in their own vocabulary. What survives carries a+ // `WorkspaceClaim` describing only what the arbiter needs to know.+ enum Admission {+ Admitted(Box<AdmittedParallelTask>),+ Rejected(ParallelTaskRejection),+ }++ let admissions: Vec<Admission> = tasks+ .into_iter()+ .map(|task| {+ let agent_id = task.agent_id.trim().to_string();+ let prompt = task.prompt.trim().to_string();+ let task_id = format!("sub-{}", uuid::Uuid::new_v4());++ if agent_id.is_empty() || prompt.is_empty() {+ return Admission::Rejected(ParallelTaskRejection {+ task_id,+ agent_id,+ error: "agent_id and prompt are required".to_string(),+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::MissingAgentOrPrompt,+ });+ }++ let Some(definition) = definitions.get(&agent_id).cloned() else {+ return Admission::Rejected(ParallelTaskRejection {+ task_id,+ agent_id: agent_id.clone(),+ error: format!("unknown agent_id '{agent_id}'"),+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::UnknownAgent,+ });+ };++ if !parent.allowed_subagent_ids.contains(&definition.id) {+ return Admission::Rejected(ParallelTaskRejection {+ task_id,+ agent_id: definition.id.clone(),+ error: format!(+ "agent '{}' is not in parent agent '{}' subagents.allowlist",+ definition.id, parent.agent_definition_id+ ),+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::OutsideAllowlist,+ });+ }++ if definition.id == "integrations_agent"+ && task+ .toolkit+ .as_ref()+ .map(|s| s.trim().is_empty())+ .unwrap_or(true)+ {+ return Admission::Rejected(ParallelTaskRejection {+ task_id,+ agent_id,+ error: "integrations_agent requires toolkit".to_string(),+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::MissingToolkit,+ });+ }++ let claim = match shared_workspace_write_claim(&task, &definition, parent) {+ // Needs the shared workspace and declares what it owns.+ Ok(Some(paths)) => WorkspaceClaim::writing(task_id.clone(), paths),+ // Cannot collide. Both arms plan as parallel, but they say so+ // for different reasons and the claim should carry the real one:+ // an isolated worker has its own root, a shared one simply never+ // writes.+ Ok(None) => {+ if matches!(+ worktree_request_for_task(&task),+ ParallelWorktreeRequest::Isolated { .. }+ ) {+ WorkspaceClaim::isolated(task_id.clone())+ } else {+ WorkspaceClaim::read_only(task_id.clone())+ }+ }+ Err(error) => {+ return Admission::Rejected(ParallelTaskRejection {+ task_id,+ agent_id: definition.id.clone(),+ error,+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::RequiresIsolation,+ });+ }+ };++ Admission::Admitted(Box::new(AdmittedParallelTask {+ definition,+ prompt,+ task,+ task_id,+ claim,+ }))+ })+ .collect();++ // Pass 2 — arbitration. One planner call over every admitted claim, in input+ // order, so the verdict is a pure function of the request rather than of+ // which worker happened to be considered first. `shared_workspace_write_claim`+ // has already ruled out the unbounded-write case, so the only conflict the+ // planner can report here is an overlap.+ let claims: Vec<WorkspaceClaim> = admissions+ .iter()+ .filter_map(|admission| match admission {+ Admission::Admitted(admitted) => Some(admitted.claim.clone()),+ Admission::Rejected(_) => None,+ })+ .collect();+ let plan = plan_shared_workspace_dispatch(&claims);+ let conflicts: HashMap<usize, &ClaimConflict> = plan+ .conflicts+ .iter()+ .map(|(index, conflict)| (*index, conflict))+ .collect();++ let mut admitted_index = 0usize;+ admissions+ .into_iter()+ .map(|admission| {+ let admitted = match admission {+ Admission::Rejected(rejection) => {+ return SpawnParallelTaskPreflight::Rejected(rejection);+ }+ Admission::Admitted(admitted) => admitted,+ };+ let index = admitted_index;+ admitted_index += 1;++ let AdmittedParallelTask {+ definition,+ prompt,+ task,+ task_id,+ claim: _,+ } = *admitted;++ if let Some(conflict) = conflicts.get(&index) {+ return SpawnParallelTaskPreflight::Rejected(ParallelTaskRejection {+ task_id,+ agent_id: definition.id.clone(),+ error: shared_workspace_conflict_message(&definition.id, conflict),+ ownership: task.ownership,+ kind: ParallelTaskRejectionKind::RequiresIsolation,+ });+ }++ let dispatch_mode = match plan.modes.get(index).copied().flatten() {+ Some(DispatchMode::Serial) => WorkerDispatchMode::SerialSharedWorkspaceWrite,+ // A claim the planner neither serialized nor rejected cannot+ // collide, so it is safe to fan out.+ Some(DispatchMode::Parallel) | None => WorkerDispatchMode::Parallel,+ };++ let prompt = with_ownership_boundary(&prompt, task.ownership.as_deref());+ SpawnParallelTaskPreflight::Prepared(PreparedParallelTask {+ definition,+ prompt,+ task,+ task_id,+ dispatch_mode,+ })+ })+ .collect()+}++/// Render a claim conflict as the sentence the calling model reads.+///+/// The crate reports conflicts as data precisely so this phrasing — the+/// `isolation="worktree"` remedy, the `files:` vocabulary — stays a product+/// decision rather than becoming API.+fn shared_workspace_conflict_message(agent_id: &str, conflict: &ClaimConflict) -> String {+ match conflict {+ ClaimConflict::Overlap {+ other_worker_id,+ path,+ ..+ } => format!(+ "agent '{agent_id}' requested shared-workspace write access to '{}' but it overlaps with serial worker {other_worker_id}; set isolation=\"worktree\" or use disjoint files: ownership",+ path.display()+ ),+ ClaimConflict::UnboundedWrite { .. } => format!(+ "agent '{agent_id}' can write the shared workspace without declaring which files it owns; set isolation=\"worktree\" or provide disjoint files: ownership"+ ),+ }+}++pub(crate) fn with_ownership_boundary(prompt: &str, ownership: Option<&str>) -> String {+ match ownership.map(str::trim).filter(|s| !s.is_empty()) {+ Some(boundary) => format!(+ "[Ownership Boundary]\n{boundary}\n\n[Task]\n{prompt}\n\nDo not work outside the ownership boundary unless the parent explicitly asks you to."+ ),+ None => prompt.to_string(),+ }+}++pub(crate) async fn stage_spawn_parallel_workers_from_defs(+ parent_session: &str,+ progress_sink: Option<&Sender<AgentProgress>>,+ tasks: Vec<ParallelAgentTask>,+ definitions: &HashMap<String, AgentDefinition>,+ parent: &ParentExecutionContext,+ action_root: Option<&Path>,+ parent_workspace_descriptor: Option<&WorkspaceDescriptor>,+) -> (Vec<SpawnParallelWorker>, Vec<ParallelAgentResult>) {+ let mut immediate_results = Vec::new();+ let mut prepared = Vec::new();++ for preflight in prepare_spawn_parallel_tasks_from_defs(tasks, definitions, parent) {+ let (definition, prompt, task, task_id, dispatch_mode) = match preflight {+ SpawnParallelTaskPreflight::Rejected(rejection) => {+ match rejection.kind {+ ParallelTaskRejectionKind::MissingAgentOrPrompt => {+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %rejection.task_id,+ agent_id = %rejection.agent_id,+ "[spawn_parallel_agents] invalid_task_missing_agent_or_prompt"+ );+ }+ ParallelTaskRejectionKind::UnknownAgent => {+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %rejection.task_id,+ agent_id = %rejection.agent_id,+ "[spawn_parallel_agents] invalid_task_unknown_agent"+ );+ }+ ParallelTaskRejectionKind::OutsideAllowlist => {+ tracing::warn!(+ parent_session = %parent_session,+ parent_agent = %parent.agent_definition_id,+ task_id = %rejection.task_id,+ agent_id = %rejection.agent_id,+ allowed = ?parent.allowed_subagent_ids,+ "[spawn_parallel_agents] rejected_task_outside_subagent_allowlist"+ );+ }+ ParallelTaskRejectionKind::MissingToolkit => {+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %rejection.task_id,+ agent_id = %rejection.agent_id,+ "[spawn_parallel_agents] invalid_task_missing_toolkit"+ );+ }+ ParallelTaskRejectionKind::RequiresIsolation => {+ tracing::warn!(+ parent_session = %parent_session,+ task_id = %rejection.task_id,+ agent_id = %rejection.agent_id,+ ownership = rejection.ownership.as_deref().unwrap_or(""),+ "[spawn_parallel_agents] rejected_shared_workspace_write_capable_task"+ );+ }+ }+ let lineage = spawn_parallel_lineage(+ parent_session,+ parent.session_parent_prefix.as_deref(),+ &rejection.task_id,+ );+ immediate_results.push(ParallelAgentResult {+ task_id: rejection.task_id,+ agent_id: rejection.agent_id,+ lineage,+ success: false,+ output: None,+ error: Some(rejection.error),+ ownership: rejection.ownership,+ elapsed_ms: 0,+ iterations: 0,+ stale_parent_reads: Vec::new(),+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ });+ continue;+ }+ SpawnParallelTaskPreflight::Prepared(prepared_task) => (+ prepared_task.definition,+ prepared_task.prompt,+ prepared_task.task,+ prepared_task.task_id,+ prepared_task.dispatch_mode,+ ),+ };+ project_spawn_parallel_spawned(+ parent_session,+ progress_sink,+ &definition,+ &task_id,+ &prompt,+ task.ownership+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .is_some(),+ )+ .await;+ let workspace_descriptor = match create_spawn_parallel_worktree(+ parent_session,+ action_root,+ &task_id,+ &definition,+ &task,+ parent.session_parent_prefix.as_deref(),+ )+ .await+ {+ Ok(descriptor) => descriptor,+ Err(result) => {+ immediate_results.push(result);+ continue;+ }+ };+ let worktree_path = workspace_descriptor+ .as_ref()+ .map(|descriptor| descriptor.root.clone());+ let worker_workspace_descriptor = workspace_descriptor+ .clone()+ .or_else(|| parent_workspace_descriptor.cloned());+ let lineage = spawn_parallel_lineage(+ parent_session,+ parent.session_parent_prefix.as_deref(),+ &task_id,+ );+ prepared.push(SpawnParallelWorker {+ definition,+ prompt,+ task,+ task_id,+ lineage,+ worktree_path,+ workspace_descriptor: worker_workspace_descriptor,+ dispatch_mode,+ });+ }++ tracing::debug!(+ parent_session = %parent_session,+ prepared_count = prepared.len(),+ immediate_count = immediate_results.len(),+ serial_write_count = prepared+ .iter()+ .filter(|worker| matches!(+ worker.dispatch_mode,+ WorkerDispatchMode::SerialSharedWorkspaceWrite+ ))+ .count(),+ "[spawn_parallel_agents] prepared_tasks"+ );+ (prepared, immediate_results)+}++async fn project_spawn_parallel_spawned(+ parent_session: &str,+ progress_sink: Option<&Sender<AgentProgress>>,+ definition: &AgentDefinition,+ task_id: &str,+ prompt: &str,+ has_ownership: bool,+) {+ let prompt_chars = prompt.chars().count();+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %task_id,+ agent_id = %definition.id,+ prompt_chars,+ has_ownership,+ "[spawn_parallel_agents] publishing_subagent_spawned"+ );+ crate::agent::orchestration::subagent_events::publish_subagent_spawned(+ parent_session.to_string(),+ definition.id.clone(),+ "typed".to_string(),+ task_id.to_string(),+ prompt_chars,+ );+ if let Some(tx) = progress_sink {+ if let Err(err) = tx+ .send(AgentProgress::SubagentSpawned {+ agent_id: definition.id.clone(),+ task_id: task_id.to_string(),+ mode: "typed".to_string(),+ dedicated_thread: false,+ prompt_chars,+ prompt: prompt.to_string(),+ worker_thread_id: None,+ display_name: Some(definition.display_name().to_string()),+ })+ .await+ {+ tracing::debug!(+ parent_session = %parent_session,+ task_id = %task_id,+ agent_id = %definition.id,+ error = %err,+ "[spawn_parallel_agents] progress_send_failed spawned"+ );+ }+ }+}diff --git a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rsnew file mode 100644index 0000000000..7e15d2382d--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs@@ -0,0 +1,322 @@+//! Per-source sync (the row-level Sync button) and raw-archive ↔ tree+//! reconciliation.++use super::coding_sessions::unserved;+use crate::config::rpc as config_rpc;+use crate::memory::sources::registry;+use crate::memory::sources::types::MemorySourceEntry;+use crate::rpc::RpcOutcome;++// ── Sync ──++#[derive(Debug, serde::Deserialize)]+pub struct SyncRequest {+ pub source_id: String,+}++#[derive(Debug, serde::Serialize)]+pub struct SyncResponse {+ pub requested: bool,+ pub source_id: String,+}++/// Which sync path a source row belongs to.+///+/// Extracted because there are **two** callers and they disagreed. The per-row+/// Sync button ([`sync_rpc`]) special-cased Composio; the Apply-all sweep+/// ([`super::apply_all::apply_all_in_rpc`]) dispatched every enabled row+/// through `MemorySourceSync`, which the driver refuses for Composio ("… is+/// synced through the connector module, not this engine"). So "sync+/// everything" failed for exactly the rows a user most expects it to fix+/// (openhuman#6007). Two call sites open-coding one rule is how that+/// happened; both now match on this.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum SyncDispatch {+ /// Connector-mediated. tinymemory v1.13.4 removed the engine's in-process+ /// Composio sync, so the connector-backed run IS the sync for this kind —+ /// the same entry point the `openhuman.composio_sync` RPC uses, which reads+ /// the connected account through the module and ingests through this same+ /// binding.+ Connector {+ connection_id: String,+ max_items: Option<u32>,+ },+ /// The memory driver's own source pipeline — folder, git, RSS, and every+ /// other tree-coupled kind.+ Driver,+}++/// Resolve a source row to its sync path.+///+/// The only failure is a Composio row carrying no `connection_id`: the connector+/// call is addressed *by* connection, so there is nothing to sync and nothing to+/// guess. That is a malformed row rather than a transient fault, which is why the+/// message says to remove and re-add rather than to retry.+pub(crate) fn sync_dispatch(entry: &MemorySourceEntry) -> Result<SyncDispatch, String> {+ if entry.kind != tinymemory_sources::types::SourceKind::Composio {+ return Ok(SyncDispatch::Driver);+ }+ let connection_id = entry.connection_id.clone().ok_or_else(|| {+ format!(+ "composio source '{}' has no connection_id; remove and re-add the source",+ entry.id+ )+ })?;+ Ok(SyncDispatch::Connector {+ connection_id,+ max_items: entry.max_items,+ })+}++/// Turn a source-sync failure into something a reader can act on.+///+/// A `NotFound` from the driver is ambiguous: either nobody ever registered the+/// id, or the driver is reading a different registry than the host is writing.+/// The second happens because the memory module is loaded once per process and+/// tinybus never unloads a library (`modules/ops.rs`), so the `config_path` it+/// is handed at load is the one it keeps for the life of the process. Boot+/// signed out, log in, and the host starts writing `[[memory_sources]]` into+/// the new profile's `config.toml` while the module still reads the pre-login+/// one — every id the host registers is then unknown to it, permanently.+///+/// The host can tell the two apart, because at this point it holds both halves+/// of the contradiction: `host_has_source` is its own registry's answer for the+/// same id. When the host has it and the driver does not, the registries+/// disagree, and the only in-process remedy is a restart — the same remedy+/// `ops` already states for a module that failed to load.+///+/// Every other failure is returned exactly as the driver stated it; inventing a+/// diagnosis for those would send the reader down the wrong path.+///+/// `pub(super)` so `rpc`'s sibling test module can reach it through+/// `super::*`.+pub(super) fn describe_source_sync_failure(+ source_id: &str,+ host_has_source: bool,+ error: &crate::memory::api::error::MemoryError,+) -> String {+ match error {+ crate::memory::api::error::MemoryError::NotFound(_) if host_has_source => format!(+ "the memory module cannot see source '{source_id}', but this profile has it \+ registered. The module is bound to a different profile's source registry — it \+ reads the config it was given when it first loaded, and that binding cannot be \+ changed while the app is running. Restart the app to rebind it."+ ),+ other => other.to_string(),+ }+}++pub async fn sync_rpc(req: SyncRequest) -> Result<RpcOutcome<SyncResponse>, String> {+ tracing::info!(source_id = %req.source_id, "[memory_sources] sync_rpc: entry");++ let config = config_rpc::load_config_with_timeout().await?;++ // The existence check is the driver's now: `run_source_sync` resolves the id+ // against the registry it already reads for per-source budgets, and answers+ // `NotFound` for an id nobody registered. Looking it up here as well would+ // be a second read of the same file that can disagree with the one the+ // pipeline actually applies.+ let binding = crate::memory::binding::for_config(&config)?;+ // The enabled gate is not the driver's. `run_source_sync` runs whatever id+ // it is handed; it is `sources::sync::sync_source` and the periodic loop+ // that refuse a disabled entry, and this RPC is the third caller, the one+ // behind the user's Sync button. Same words as `sync_source` so the UI+ // reads one message (#5820).+ // Kept past the `if let` because the failure path below needs the host's own+ // answer for this id: a driver `NotFound` means something different when the+ // host has the source than when it does not.+ let host_entry = registry::get_source_in(&config, &req.source_id)?;+ if let Some(entry) = &host_entry {+ if !entry.enabled {+ return Err(format!("source '{}' is disabled", entry.id));+ }+ // Composio rows never reach the memory driver's pipeline — see+ // [`SyncDispatch`], which both this button and the Apply-all sweep read+ // the rule from.+ if let SyncDispatch::Connector {+ connection_id,+ max_items,+ } = sync_dispatch(entry)?+ {+ crate::integrations::composio::ops::composio_sync_budgeted(+ &config,+ &connection_id,+ Some("manual".to_string()),+ Some(entry.id.clone()),+ max_items,+ )+ .await?;+ return Ok(RpcOutcome::new(+ SyncResponse {+ requested: true,+ source_id: req.source_id,+ },+ vec![],+ ));+ }+ }+ // Resolved after the composio branch on purpose: the connector-backed+ // dispatch above needs `as_sources`, not `as_source_sync`, and a driver+ // serving the former without the latter must not fail a composio sync on+ // a capability it never uses (review finding on #5932).+ let sync = binding.provider().as_source_sync().ok_or_else(|| {+ format!(+ "the bound memory driver '{}' does not serve source sync",+ binding.driver_id()+ )+ })?;+ sync.run_source_sync(&req.source_id)+ .await+ .map_err(|error| {+ describe_source_sync_failure(&req.source_id, host_entry.is_some(), &error)+ })?;++ Ok(RpcOutcome::new(+ SyncResponse {+ requested: true,+ source_id: req.source_id,+ },+ vec![],+ ))+}++// ── Reconcile ──++#[derive(Debug, Default, serde::Deserialize)]+pub struct ReconcileRequest {+ /// Restrict to one source; omit to inspect every enabled source.+ #[serde(default)]+ pub source_id: Option<String>,+ /// When true, kick off background summarise+ingest for every scope+ /// with pending files. When false (default), report-only.+ #[serde(default)]+ pub execute: bool,+}++#[derive(Debug, serde::Serialize)]+pub struct ReconcileScopeReport {+ pub source_id: String,+ pub tree_scope: String,+ /// Raw `.md` files on disk for this scope.+ pub total_raw_files: u64,+ /// Files already covered by a tree summary.+ pub covered: u64,+ /// Files awaiting summarisation into the tree.+ ///+ /// A count the driver computed, not one this handler derived from a list.+ /// The engine's coverage scan returned each pending file's absolute path+ /// inside the content vault and this handler called `.len()` on it;+ /// `RawArchiveCoverage` deliberately reports the count alone, because a+ /// path describes the driver's storage layout and nothing here ever read+ /// one. The number is the same number.+ pub pending: u64,+ /// True when `execute` was set and a background reconcile was started.+ pub started: bool,+}++#[derive(Debug, serde::Serialize)]+pub struct ReconcileResponse {+ pub scopes: Vec<ReconcileScopeReport>,+}++/// Report (and optionally repair) raw-archive → tree coverage for memory+/// sources. The same incremental reconcile runs automatically after every+/// sync; this RPC exposes it for inspection and manual triggering.+///+/// The scopes themselves are still derived host-side (`derive_scopes` reads the+/// registry row); what moved is the crosscheck and the repair, which are+/// `MemorySourceSync::raw_archive_coverage` and `rebuild_from_raw_archive`.+pub async fn reconcile_rpc(req: ReconcileRequest) -> Result<RpcOutcome<ReconcileResponse>, String> {+ use crate::memory::sources::sync::derive_scopes;++ tracing::info!(+ source_id = ?req.source_id,+ execute = req.execute,+ "[memory_sources] reconcile_rpc: entry"+ );++ let config = config_rpc::load_config_with_timeout().await?;+ let binding = crate::memory::binding::for_config(&config)?;+ let Some(sync) = binding.provider().as_source_sync() else {+ return Err(unserved(&binding, "source sync", "reconcile"));+ };++ let sources: Vec<MemorySourceEntry> = match &req.source_id {+ Some(id) => vec![registry::get_source(id)+ .await?+ .ok_or_else(|| format!("source '{id}' not found"))?],+ None => registry::list_sources().await?,+ };++ let mut reports: Vec<ReconcileScopeReport> = Vec::new();+ for source in sources.iter().filter(|s| s.enabled) {+ for scope in derive_scopes(source, &config) {+ let coverage = sync+ .raw_archive_coverage(&scope.tree_scope, &scope.archive_source_id)+ .await+ .map_err(|e| format!("coverage for {}: {e}", scope.tree_scope))?;+ let mut started = false;+ if req.execute && coverage.pending > 0 {+ // The binding, not the config: the repair is a driver call now,+ // and the spawned task must reach the same bound driver this+ // request resolved rather than re-deriving one.+ let binding = std::sync::Arc::clone(&binding);+ let tree_scope = scope.tree_scope.clone();+ let archive = scope.archive_source_id.clone();+ tokio::spawn(async move {+ // Re-resolved inside the task because the borrow cannot+ // cross the spawn. It answered `Some` a moment ago on this+ // same binding, so `None` here would mean the driver+ // changed underneath the request — logged loudly rather+ // than returning as a silent no-op.+ let Some(sync) = binding.provider().as_source_sync() else {+ tracing::error!(+ driver = %binding.driver_id(),+ tree_scope = %tree_scope,+ "[memory_sources] reconcile_rpc: background reconcile abandoned — \+ driver stopped serving source sync between the report and the repair"+ );+ return;+ };+ match sync.rebuild_from_raw_archive(&tree_scope, &archive).await {+ Ok(outcome) => tracing::info!(+ tree_scope = %tree_scope,+ files = outcome.files_read,+ batches = outcome.batches,+ "[memory_sources] reconcile_rpc: background reconcile complete"+ ),+ Err(e) => tracing::warn!(+ tree_scope = %tree_scope,+ error = %e,+ "[memory_sources] reconcile_rpc: background reconcile failed"+ ),+ }+ });+ started = true;+ }+ tracing::debug!(+ driver = %binding.driver_id(),+ source_id = %source.id,+ tree_scope = %scope.tree_scope,+ total = coverage.total,+ covered = coverage.covered,+ pending = coverage.pending,+ started = started,+ "[memory_sources] reconcile_rpc: scope report"+ );+ reports.push(ReconcileScopeReport {+ source_id: source.id.clone(),+ tree_scope: scope.tree_scope,+ total_raw_files: coverage.total,+ covered: coverage.covered,+ pending: coverage.pending,+ started,+ });+ }+ }++ Ok(RpcOutcome::new(+ ReconcileResponse { scopes: reports },+ vec![],+ ))+}