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
refactor(agent): finish explicit turn carrier cutover
Steven Enamakel5f0e0a417403
diff --git a/crates/openhuman-core/src/agent/harness/README.md b/crates/openhuman-core/src/agent/harness/README.mdindex a7d4053f27..3498e5ed44 100644--- a/crates/openhuman-core/src/agent/harness/README.md+++ b/crates/openhuman-core/src/agent/harness/README.md@@ -25,7 +25,7 @@ iterations.plumbing that lets a spawned tool see its parent's runtime context(`definition*.rs`, `builtin_definitions.rs`, `fork_context.rs`,`sandbox_context.rs`, `spawn_depth_context.rs`, `task_recency_context.rs`,- `turn_attachments_context.rs`).+ `OpenHumanRunContext`).- Run the channel/CLI turn graph (`graph.rs`) and let a built-in agentselect a bespoke sub-agent turn graph (`agent_graph.rs`).- Extract lessons and episodic memory after each turn as a `PostTurnHook`@@ -43,7 +43,7 @@ iterations.| `session/` | `Agent`/`AgentBuilder`/`TurnOverrides` (`types.rs`), the fluent builder + `Agent::from_config` factory (`builder/`), the turn lifecycle (`turn/`: `context.rs`, `core*.rs`, `graph.rs`, `recall_lanes.rs`, `session_io*.rs`, `tools.rs`), transcript persistence + legacy migration (`transcript*.rs`, `migration.rs`, `turn_checkpoint.rs`). || `subagent_runner/` | `run_subagent`/`SubagentRunOptions`/`SubagentRunError` and the build pipeline around the tinyagents graph: model resolution, tool filtering, sandbox/action-root narrowing, checkpoint/handback, transcript mirroring (`autonomous.rs`, `extract_tool.rs`, `handoff.rs`, `tool_prep.rs`, `ops/{provider,prompt,runner,graph,checkpoint,pause_checkpoint}.rs`). || `definition*.rs`, `builtin_definitions.rs`, `definition_loader.rs` | `AgentDefinition`/`AgentDefinitionRegistry`/`SandboxMode`/`ToolScope`/`PromptSource`/`ModelSpec`; loads built-ins from `crate::agent::registry::agents` and user TOML from the workspace/home `agents/` directory. |-| `fork_context.rs`, `sandbox_context.rs`, `spawn_depth_context.rs`, `task_recency_context.rs`, `turn_attachments_context.rs` | `ParentExecutionContext` and other task-locals a spawned tool reads to see its parent's provider, tools, sandbox mode, spawn depth (capped by `MAX_SPAWN_DEPTH`), and recent-task window. |+| `fork_context.rs`, `sandbox_context.rs`, `spawn_depth_context.rs`, `task_recency_context.rs` | Transitional task-locals for legacy callers. Live TinyAgents tool dispatch receives `OpenHumanRunContext` directly for parent, attachments, dispatch, and usage. || `graph.rs` | `run_channel_turn_via_graph` (`pub(crate)`) — the channel/CLI turn graph, thin over `run_turn_via_tinyagents_shared`; called by the `agent.run_turn` native-bus handler in `agent/bus.rs`. || `agent_graph.rs` | `AgentGraph` (`Default`/`Custom`), `AgentTurnRequest`, `AgentTurnResult`, `AgentTurnUsage` — per-agent sub-agent turn-graph selection consulted by `subagent_runner`'s `run_typed_mode`. Every built-in agent currently selects `Default`. || `archivist/` | `ArchivistHook` (`types.rs`, `PostTurnHook` impl in `hook_impl.rs`) — post-turn episodic insert, segment boundary detection + lifecycle, LLM recap with heuristic fallback, lesson extraction from tool failures, and raw-prose ingestion into the memory tree when `config.learning.chat_to_tree_enabled` (`boundary.rs`, `lifecycle.rs`, `recap.rs`, `resummarise.rs`, `store.rs`, `tree_ingest.rs`, `events_heuristic.rs`). |@@ -53,7 +53,7 @@ iterations.| `memory_context.rs`, `memory_context_safety.rs`, `memory_protocol.rs` | Working-memory and `[Cross-chat context]` lines surfaced into the prompt (capped by `WORKING_MEMORY_LIMIT`); trust-tier wrapping of recalled entries that came from connectors (`wrap_untrusted_for_agent`); and the read-index → dedupe → write → update-index enforcement state machine for memory-mutating tools (issue #4116). || `instructions.rs`, `parse.rs`, `required_output.rs` | Text-mode `<tool_call>` protocol section (`build_tool_instructions*`), `parse_tool_calls_with_pformat`, and required structured-output validation/repair. || `credentials.rs` | `scrub_credentials` — regex scrubbing of credential-shaped text (key/value secrets, AWS access-key IDs, `sk-…` keys). Applied to every tool result by the middleware in `agent/tinyagents/`. |-| `turn_dispatch_guard.rs`, `turn_subagent_usage.rs` | Turn-scoped guard that refuses a new sub-agent dispatch once the run's remaining wall-clock/cap budget cannot fit it (issue #5804), and `LastTurnUsage`/`SubagentUsageEntry` accounting. |+| `tinyagents/host/run_context.rs` | Explicit turn-scoped dispatch refusal and `LastTurnUsage`/`SubagentUsageEntry` accounting shared by synchronous descendants. Detached work resets these turn-only handles. |## Public surfacediff --git a/crates/openhuman-core/src/agent/harness/fork_context.rs b/crates/openhuman-core/src/agent/harness/fork_context.rsindex 08d1c9df1a..e10a759316 100644--- a/crates/openhuman-core/src/agent/harness/fork_context.rs+++ b/crates/openhuman-core/src/agent/harness/fork_context.rs@@ -195,7 +195,7 @@ where{// Box before `scope` so only a pointer moves into the task-local frame// rather than the whole nested turn generator — see the measurements on- // `with_turn_collector` in `turn_subagent_usage.rs`.+ // the explicit usage ledger on `OpenHumanRunContext`.PARENT_CONTEXT.scope(ctx, Box::pin(future)).await}@@ -218,7 +218,7 @@ where{// Box before `scope` so only a pointer moves into the task-local frame// rather than the whole nested turn generator — see the measurements on- // `with_turn_collector` in `turn_subagent_usage.rs`.+ // the explicit usage ledger on `OpenHumanRunContext`.AGENT_CONTEXT_PREPARED_SOURCES.scope(Arc::new(sources), Box::pin(future)).awaitdiff --git a/crates/openhuman-core/src/agent/harness/sandbox_context.rs b/crates/openhuman-core/src/agent/harness/sandbox_context.rsindex ffedb231ee..cdbc696e77 100644--- a/crates/openhuman-core/src/agent/harness/sandbox_context.rs+++ b/crates/openhuman-core/src/agent/harness/sandbox_context.rs@@ -52,7 +52,7 @@ where{// Box before `scope` so only a pointer moves into the task-local frame// rather than the whole nested turn generator — see the measurements on- // `with_turn_collector` in `turn_subagent_usage.rs`.+ // the explicit usage ledger on `OpenHumanRunContext`.CURRENT_AGENT_SANDBOX_MODE.scope(mode, Box::pin(future)).awaitdiff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rsindex 0de410f81c..aa1983ad03 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs@@ -127,6 +127,10 @@ impl Agent {let options = harness::SubagentRunOptions {task_id: Some(task_id.clone()),model_override: Some(parent_context.model_name.clone()),+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext {+ parent: Some(parent_context.clone()),+ ..Default::default()+ },..Default::default()};@@ -138,10 +142,7 @@ impl Agent {);let started = std::time::Instant::now();- let result = harness::with_parent_context(parent_context.clone(), async move {- harness::run_subagent(&definition, &prompt, options).await- })- .await;+ let result = harness::run_subagent(&definition, &prompt, options).await;match result {Ok(outcome) => {diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rsindex a6b110e0a6..43baac06e0 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs@@ -73,9 +73,14 @@ impl Agent {);tokio::spawn(async move {- let options = harness::SubagentRunOptions::default();- let fut = harness::run_subagent(&definition, &extraction_prompt, options);- let result = harness::with_parent_context(parent_ctx, fut).await;+ let options = harness::SubagentRunOptions {+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext {+ parent: Some(parent_ctx),+ ..Default::default()+ },+ ..Default::default()+ };+ let result = harness::run_subagent(&definition, &extraction_prompt, options).await;match result {Ok(outcome) => {tracing::info!(diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rsindex ff54666594..d780d2e850 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs@@ -388,6 +388,32 @@ pub async fn run_subagent(// child's tinyagents drive future further chunk the child's state so// a single sub-agent run can't blow the stack either.Box::pin(async move {+ // A nested delegate writes its terminal total to this run's isolated+ // ledger. If the outer future errors or is cancelled after that child+ // has completed, Drop promotes those finished totals before the error+ // can escape. Success marks the finalizer complete after folding the+ // same entries into this run's single terminal total.+ struct UsageFinalizer {+ context: crate::agent::tinyagents::host::OpenHumanRunContext,+ complete: bool,+ }+ impl UsageFinalizer {+ fn finish(&mut self, entry: crate::agent::tinyagents::host::SubagentUsageEntry) {+ self.context.record_completed_subagent_usage(entry);+ self.complete = true;+ }+ }+ impl Drop for UsageFinalizer {+ fn drop(&mut self) {+ if !self.complete {+ self.context.promote_completed_descendant_usage();+ }+ }+ }+ let mut usage_finalizer = UsageFinalizer {+ context: options.run_context.clone(),+ complete: false,+ };let task_id = options.task_id.clone()@@ -558,6 +584,11 @@ pub async fn run_subagent(if let Some(dispatch) = options.run_context.dispatch.as_deref() {dispatch.record_subagent_elapsed(started.elapsed());}+ usage_finalizer.finish(crate::agent::tinyagents::host::SubagentUsageEntry {+ task_id: task_id.clone(),+ agent_id: definition.id.clone(),+ usage: outcome.usage,+ });return Ok(outcome);}}@@ -650,6 +681,12 @@ pub async fn run_subagent(// deterministic memory fast path via `apply_max_result_chars`).apply_max_result_chars(&mut outcome.output, definition.max_result_chars, &definition.id);+ usage_finalizer.finish(crate::agent::tinyagents::host::SubagentUsageEntry {+ task_id: task_id.clone(),+ agent_id: definition.id.clone(),+ usage: outcome.usage,+ });+tracing::info!(agent_id = %definition.id,task_id = %task_id,@@ -1745,14 +1782,6 @@ async fn run_typed_mode(.saturating_add(entry.usage.cached_input_tokens);usage.charged_amount_usd += entry.usage.charged_amount_usd;}- options.run_context.record_completed_subagent_usage(- crate::agent::tinyagents::host::SubagentUsageEntry {- task_id: task_id.to_string(),- agent_id: definition.id.clone(),- usage,- },- );-Ok(SubagentRunOutcome {task_id: task_id.to_string(),agent_id: definition.id.clone(),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.rsindex cdf3cf573d..23a528b49a 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@@ -8,7 +8,6 @@ use tinyagents_harness::CancellationToken;use tinytools::WorkspaceDescriptor;use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::current_parent;use super::collect::SpawnParallelGraphOutcome;use super::graph::run_spawn_parallel_execution_graph;@@ -58,7 +57,7 @@ pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(Err(err) => return Ok(SpawnParallelGraphOutcome::InvalidRequest(err)),};- let parent = match current_parent() {+ let parent = match run_context.parent.clone() {Some(parent) => parent,None => {tracing::debug!("[spawn_parallel_agents] rejected_outside_agent_turn");diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rsindex 80f74e5013..0dca50f749 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs@@ -3,7 +3,7 @@//! and bootstrapping a thread goal from the scout's proposal.use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::{current_parent, AgentContextPreparedSource};+use crate::agent::harness::fork_context::AgentContextPreparedSource;use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunError, SubagentRunOptions, SubagentRunStatus,};@@ -98,7 +98,7 @@ pub(super) fn already_prepared_context_bundle(sources: &[AgentContextPreparedSou/// and runs the scout against the parent's provider. Outside a turn the/// `run_subagent` call surfaces a no-parent error as a [`ToolResult::error`].pub async fn run_context_scout(question: &str, focus: Option<&str>) -> anyhow::Result<ToolResult> {- let tool_catalog = AgentPrepareContextTool::render_parent_tool_catalog();+ let tool_catalog = AgentPrepareContextTool::render_parent_tool_catalog(None);run_context_scout_with_catalog(question, focus, &tool_catalog).await}@@ -219,6 +219,7 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace(thread_id: Option<String>,run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> anyhow::Result<ToolResult> {+ let parent = run_context.parent.clone();let question = question.trim().to_string();let focus = focus.map(|s| s.to_string());@@ -264,10 +265,11 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace();let task_id = format!("ctx-{}", uuid::Uuid::new_v4());- let parent_session = current_parent()+ let parent_session = parent+ .as_ref().map(|p| p.session_id.clone()).unwrap_or_else(|| "standalone".into());- let progress_sink = current_parent().and_then(|p| p.on_progress.clone());+ let progress_sink = run_context.progress.clone();// Surface the scout as a live subagent row in the parent thread. The// child's own iterations/tool-calls already stream to this sink from@@ -404,7 +406,7 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace(// context-gathering path just seeds a goal on the first scout of// a fresh chat so the harness has something to steer toward.// Best-effort — never fails the call.- if let (Some(parent), Some(thread_id)) = (current_parent(), thread_id) {+ if let (Some(parent), Some(thread_id)) = (parent.as_ref(), thread_id) {if let Some(objective) = AgentPrepareContextTool::parse_proposed_goal(&bundle) {match crate::agent::goals::store::set_if_absent(&parent.workspace_dir,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rsindex e35f268150..e44304c983 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs@@ -5,7 +5,7 @@use std::fmt::Write as _;use std::sync::Arc;-use crate::agent::harness::fork_context::{current_agent_context_prepared_sources, current_parent};+use crate::agent::harness::fork_context::ParentExecutionContext;use async_trait::async_trait;use serde_json::json;use tinyagents_harness::context::RunContext;@@ -78,8 +78,8 @@ impl AgentPrepareContextTool {/// Falls back to that registry, name-filtered, when a context does not/// carry the visible list, to preserve behaviour for builders that don't/// populate it.- pub(super) fn render_parent_tool_catalog() -> String {- let Some(parent) = current_parent() else {+ pub(super) fn render_parent_tool_catalog(parent: Option<&ParentExecutionContext>) -> String {+ let Some(parent) = parent else {return String::new();};let visible = &parent.visible_tool_names;@@ -242,7 +242,7 @@ impl AgentPrepareContextTool {tool_context: Option<&dyn ToolRunContext>,run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> anyhow::Result<ToolResult> {- let prepared_sources = current_agent_context_prepared_sources();+ let prepared_sources = run_context.prepared_context_sources.as_ref();if !prepared_sources.is_empty() {tracing::info!(target: "agent_prepare_context",@@ -256,7 +256,8 @@ impl AgentPrepareContextTool {let question = args.get("question").and_then(|v| v.as_str()).unwrap_or("");let focus = args.get("focus").and_then(|v| v.as_str());- let tool_catalog = AgentPrepareContextTool::render_parent_tool_catalog();+ let tool_catalog =+ AgentPrepareContextTool::render_parent_tool_catalog(run_context.parent.as_ref());run_context_scout_with_catalog_and_workspace(question,focus,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rsindex 2e2d4bf8f1..784f95463c 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs@@ -9,7 +9,6 @@//! appended to the conversation history.use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::current_parent;use crate::agent::harness::subagent_runner::{run_subagent, SubagentCheckpointData, SubagentRunOptions, SubagentRunStatus,};@@ -266,7 +265,7 @@ impl ContinueSubagentTool {));}- let parent = match current_parent() {+ let parent = match run_context.parent.clone() {Some(p) => p,None => {return Ok(ToolResult::error(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rsindex 06b49437a9..f59b9c8338 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs@@ -5,7 +5,6 @@//! events and, when possible, persisted in the child worker thread.use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::{current_parent, with_parent_context};use crate::agent::harness::run_queue::RunQueue;use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions, SubagentRunStatus};use crate::agent::messages::ChatMessage;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rsindex 0d5b5c93b2..921aed2c2f 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs@@ -54,7 +54,7 @@ impl SpawnAsyncSubagentTool {));}- let parent = match current_parent() {+ let parent = match run_context.parent.clone() {Some(parent) => parent,None => {return Ok(ToolResult::error(@@ -383,7 +383,6 @@ impl SpawnAsyncSubagentTool {let task_queue = steer_queue.clone();let (status_tx, status_rx) = running_subagents::status_channel();- let background_parent = parent.clone();let background_workspace_dir = parent.workspace_dir.clone();let background_definition = definition.clone();let background_agent_id = definition.id.clone();@@ -417,16 +416,11 @@ impl SpawnAsyncSubagentTool {register_parent_thread_id.as_deref().unwrap_or("none"));let background_prompt = add_background_contract(&prompt);- // The detached child starts on a fresh task. Capture its durable thread- // identity now and carry it in `SubagentRunOptions`; task-local scope- // does not cross `tokio::spawn`. The turn's origin label and workspace- // root are the other values that must travel, and they are captured- // **here**, on the spawning task. Without the origin every external-effect tool the- // child calls reaches the approval gate unlabelled and is refused,- // which is the whole of why a delegated coding task could not run a- // shell.- let join = tokio::spawn(crate::agent::turn_origin::propagate(- crate::agent::turn_workspace::propagate(async move {+ // The detached child starts on a fresh task. Its explicit carrier keeps+ // authority, origin, thread, and workspace while deliberately dropping+ // the originating turn's accounting, dispatch refusal, and cancellation.+ let detached_run_context = run_context.detached_child();+ let join = tokio::spawn(async move {let options = SubagentRunOptions {skill_filter_override: None,toolkit_override,@@ -434,7 +428,7 @@ impl SpawnAsyncSubagentTool {model_override,task_id: Some(background_task_id.clone()),thread_id: Some(background_thread_id),- run_context,+ run_context: detached_run_context,worker_thread_id: background_worker_thread_id.clone(),initial_history: background_initial_history,checkpoint_dir: None,@@ -443,10 +437,7 @@ impl SpawnAsyncSubagentTool {run_queue: Some(task_queue),};- let result = with_parent_context(background_parent, async move {- run_subagent(&background_definition, &background_prompt, options).await- })- .await;+ let result = run_subagent(&background_definition, &background_prompt, options).await;match result {Ok(outcome) => match outcome.status {@@ -687,8 +678,7 @@ impl SpawnAsyncSubagentTool {}}}- }),- ));+ });// Register *after* spawn so the AbortHandle is available. The task owns// `status_tx`; this side holds `status_rx` for `wait_subagent`.diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rsindex 4b07479977..257f26c161 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs@@ -13,7 +13,6 @@//! prompt with a filtered tool list, on a cheaper model where applicable.//!use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::current_parent;use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,};diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rsindex 08cf152dc0..abe020c66b 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs@@ -201,7 +201,7 @@ impl SpawnSubagentTool {}};- if let Some(parent_ctx) = current_parent() {+ if let Some(parent_ctx) = run_context.parent.as_ref() {if !parent_ctx.allowed_subagent_ids.contains(&definition.id) {log::warn!("[spawn_subagent] blocked subagent outside parent allowlist parent_agent={} requested_agent={} allowed={:?}",@@ -238,7 +238,7 @@ impl SpawnSubagentTool {// truth. Falls back to the parent's frozen list when the// live fetch returns empty (no signed-in user, backend// unreachable, …) so offline behaviour is unchanged.- let parent_ctx = current_parent();+ let parent_ctx = run_context.parent.clone();let live_integrations: Vec<crate::agent::prompts::ConnectedIntegration,> = {@@ -428,7 +428,9 @@ impl SpawnSubagentTool {}// ── Publish SubagentSpawned event ──────────────────────────────- let parent_session = current_parent()+ let parent_session = run_context+ .parent+ .as_ref().map(|p| p.session_id.clone()).unwrap_or_else(|| "standalone".into());let task_id = format!("sub-{}", uuid::Uuid::new_v4());@@ -438,7 +440,7 @@ impl SpawnSubagentTool {// navigation and restarts — the same machinery `spawn_worker_thread`// uses. Best-effort: with no parent context or thread store the run// still proceeds live-only (`worker_thread_id: None`).- let worker_thread_id = current_parent().and_then(|p| {+ let worker_thread_id = run_context.parent.as_ref().and_then(|p| {let parent_thread_id = parent_thread_id.as_ref()?;let title: String = prompt.chars().take(60).collect();super::worker_thread::create_worker_thread(@@ -464,7 +466,7 @@ impl SpawnSubagentTool {// parent thread's UI. Best-effort: a closed/missing sink is// silently ignored — the global DomainEvent above is the// authoritative record.- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {+ if let Some(progress) = run_context.progress.clone() {let _ = progress.send(AgentProgress::SubagentSpawned {agent_id: definition.id.clone(),@@ -493,6 +495,11 @@ impl SpawnSubagentTool {"[spawn_subagent] using ToolExecutionContext workspace root");}+ let progress_sink = run_context.progress.clone();+ let parent_workspace_dir = run_context+ .parent+ .as_ref()+ .map(|parent| parent.workspace_dir.clone());let options = SubagentRunOptions {skill_filter_override: None,toolkit_override,@@ -509,8 +516,6 @@ impl SpawnSubagentTool {run_queue: None,};- let progress_sink = current_parent().and_then(|p| p.on_progress.clone());-match run_subagent(definition, &prompt, options).await {Ok(outcome) => {match &outcome.status {@@ -589,8 +594,8 @@ impl SpawnSubagentTool {}if dedicated_thread {- let workspace_dir = current_parent()- .map(|p| p.workspace_dir.clone())+ let workspace_dir = parent_workspace_dir+ .clone().unwrap_or_else(|| PathBuf::from("."));let parent_visible = match persist_worker_thread(&workspace_dir,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rsindex 262f053dc8..e307641173 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs@@ -10,7 +10,6 @@//! another worker thread.use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::current_parent;use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions};use crate::memory::conversations;use async_trait::async_trait;@@ -200,7 +199,10 @@ impl SpawnWorkerThreadTool {return Ok(ToolResult::error("agent_id and prompt are required"));}- let parent = current_parent().ok_or_else(|| anyhow::anyhow!("no parent context"))?;+ let parent = run_context+ .parent+ .clone()+ .ok_or_else(|| anyhow::anyhow!("no parent context"))?;// ── Depth Guard ────────────────────────────────────────────────// Check if the current thread is already a worker thread.diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 2226b3e184..0dcf128472 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -443,8 +443,8 @@ pub(super) fn assemble_turn_harness(//// FLIP CRITERIA — what must hold before the crate `BudgetMiddleware` becomes// the enforcing owner and the local `CostBudgetMiddleware` + the- // `agent/harness/turn_subagent_usage.rs` task-local are DELETED (deletion- // ledger row: "crate-internal CostBudgetMiddleware + turn_subagent_usage.rs+ // `OpenHumanRunContext` explicit carrier owns the per-turn roll-up (deletion+ // ledger row: "crate-internal CostBudgetMiddleware + explicit run context// task-local", `docs/tinyagents-full-migration-plan/99-deletion-ledger.md`):// 1. ≥ 500 production turns across BOTH parent and sub-agent runs with// ZERO `[budget_shadow]` divergence log lines — proving the crate@@ -457,7 +457,7 @@ pub(super) fn assemble_turn_harness(// and the local gate is the sole money-budget authority.// 3. Run-tree rollup wired: the same shared `BudgetTracker` handed to every// sub-agent harness so a parent budget halts a recursive run pre-spend —- // replacing the `turn_subagent_usage` parent-turn rollup (06-cost step 3+ // replacing the former task-local parent-turn rollup (06-cost step 3// / 07.2 TaskStore rollup).// Until all three hold, this middleware is observe-only and the local gate// enforces.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex bce77a78db..b24773195e 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -273,6 +273,22 @@ impl OpenHumanRunContext {child}+ /// Builds the explicit carrier for detached background work.+ ///+ /// A detached task keeps the authority, thread and workspace descriptor it+ /// needs to execute and deliver its own result, but it is no longer part of+ /// the originating turn. In particular it cannot consume that turn's+ /// dispatch budget, append to its usage ledger, or observe a cancellation+ /// request that only stopped the interactive turn.+ pub fn detached_child(&self) -> Self {+ let mut child = self.child();+ child.dispatch = None;+ child.subagent_usage = Arc::new(Mutex::new(Vec::new()));+ child.parent_subagent_usage = None;+ child.cancellation = tinyagents_harness::cancel::CancellationToken::new();+ child+ }+/// Converts this host context into TinyAgents' canonical run context.////// The canonical context receives the exact same cancellation and direct@@ -334,6 +350,16 @@ impl OpenHumanRunContext {.clone()}+ /// Promote already-completed descendants when this run cannot produce its+ /// own terminal outcome. This is intentionally a snapshot: callers invoke+ /// it only from one terminal finalizer, so every completed descendant is+ /// promoted once without exposing a shared, in-flight sibling ledger.+ pub fn promote_completed_descendant_usage(&self) {+ for entry in self.subagent_usage_entries() {+ self.record_completed_subagent_usage(entry);+ }+ }+/// Resolves whether a file-state scope has been assigned to this context./// Keeping the conversion here makes file-state callers use the explicit/// context instead of discovering an ambient identifier.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsindex af7d546a9d..f3ad02744d 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -108,6 +108,49 @@ fn child_ledgers_are_isolated_and_parent_keeps_completed_child_totals() {assert_eq!(left.subagent_usage_entries().len(), 1);}+#[test]+fn failed_outer_run_promotes_completed_nested_usage_once() {+ let root = OpenHumanRunContext::new();+ let outer = root.child();+ outer.append_subagent_usage(SubagentUsageEntry {+ task_id: "nested".into(),+ agent_id: "researcher".into(),+ usage: crate::agent::harness::subagent_runner::SubagentUsage {+ input_tokens: 7,+ ..Default::default()+ },+ });++ // This is the failure/cancellation finalizer path. Calling it once leaves+ // the root with the completed nested work even though the outer run has no+ // terminal outcome of its own.+ outer.promote_completed_descendant_usage();+ assert_eq!(root.subagent_usage_entries().len(), 1);+ assert_eq!(root.subagent_usage_entries()[0].task_id, "nested");+}++#[test]+fn detached_children_reset_turn_accounting_and_cancellation() {+ let mut root = OpenHumanRunContext::new();+ root.thread_id = Some("thread-a".into());+ let dispatch = Arc::new(TurnDispatchState::new(Some(std::time::Duration::ZERO)));+ dispatch.record_subagent_elapsed(std::time::Duration::from_secs(1));+ root.dispatch = Some(dispatch);+ let detached = root.detached_child();++ assert_eq!(detached.thread_id.as_deref(), Some("thread-a"));+ assert!(detached.dispatch.is_none());+ root.cancellation.cancel();+ assert!(!detached.cancellation.is_cancelled());+ detached.record_completed_subagent_usage(SubagentUsageEntry {+ task_id: "background".into(),+ agent_id: "archivist".into(),+ usage: Default::default(),+ });+ assert!(root.subagent_usage_entries().is_empty());+ assert_eq!(detached.subagent_usage_entries().len(), 1);+}+#[test]fn children_inherit_attachment_placeholders() {let mut root = OpenHumanRunContext::new();diff --git a/crates/openhuman-core/src/agent/triage/escalation.rs b/crates/openhuman-core/src/agent/triage/escalation.rsindex 683601c2d5..e615da7809 100644--- a/crates/openhuman-core/src/agent/triage/escalation.rs+++ b/crates/openhuman-core/src/agent/triage/escalation.rs@@ -13,13 +13,13 @@//! `react`/`escalate` build a full [`Agent`] from config so they have//! a real provider, tool registry, and memory backing — the same//! construction path `agent_chat` uses. A [`ParentExecutionContext`] is-//! installed on the task-local so [`run_subagent`] can inherit the-//! provider and tools.+//! carried explicitly into [`run_subagent`] so it can inherit the provider+//! and tools.use anyhow::{anyhow, Context};use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext};+use crate::agent::harness::fork_context::ParentExecutionContext;use crate::agent::harness::subagent_runner::{self, SubagentRunOptions};use crate::agent::orchestration::parent_context::build_root_parent;use crate::config::Config;@@ -311,9 +311,17 @@ async fn dispatch_target_agent(agent_id: &str, prompt: &str) -> anyhow::Result<S"[triage::escalation] dispatching run_subagent with parent context");- let outcome = with_parent_context(parent_ctx, async {- subagent_runner::run_subagent(definition, prompt, SubagentRunOptions::default()).await- })+ let outcome = subagent_runner::run_subagent(+ definition,+ prompt,+ SubagentRunOptions {+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext {+ parent: Some(parent_ctx),+ ..Default::default()+ },+ ..Default::default()+ },+ ).await.map_err(|e| anyhow!("run_subagent(`{agent_id}`) failed: {e}"))?;diff --git a/docs/plans/migrate-agent-runtime-to-tinyagents.md b/docs/plans/migrate-agent-runtime-to-tinyagents.mdindex 09568099d9..abf0ba4a37 100644--- a/docs/plans/migrate-agent-runtime-to-tinyagents.md+++ b/docs/plans/migrate-agent-runtime-to-tinyagents.md@@ -223,8 +223,8 @@ scope, attachments, dispatch/recency/fork state, subagent usage and routeobserver. Replace reads of:- `fork_context`, `sandbox_context`, `spawn_depth_context`,- `task_recency_context`, `turn_attachments_context`, `turn_dispatch_guard`,- `turn_subagent_usage`;+ `task_recency_context`; attachment, dispatch, and usage state now live on+ `OpenHumanRunContext`;- `progress_sink`, `resolved_route`,`thread_context`, `turn_origin`, and `turn_workspace` task-local scopes.diff --git a/docs/specs/agent-runtime-upstream-boundary.md b/docs/specs/agent-runtime-upstream-boundary.mdindex 214641af7c..9df7775693 100644--- a/docs/specs/agent-runtime-upstream-boundary.md+++ b/docs/specs/agent-runtime-upstream-boundary.md@@ -314,7 +314,7 @@ all consumers import the owner directly, not that behavior is dropped.| `run_queue/` | `tinyagents-harness::run_queue` | Delete the OpenHuman copy/facade after parity tests and direct imports. || `tool_result_artifacts/` | Keep host store | OpenHuman action-dir artifact persistence implementing the upstream artifact callback/store seam. || `credentials.rs`, `memory_context.rs`, `memory_context_safety.rs` | Keep host policy/adapters | Feed explicit context/capability requests; move only host-free formatting/traversal helpers. |-| `fork_context.rs`, `sandbox_context.rs`, `spawn_depth_context.rs`, `task_recency_context.rs`, `turn_attachments_context.rs`, `turn_dispatch_guard.rs`, `turn_subagent_usage.rs` | explicit `RunContext`/child context | Delete task-local shells. |+| `fork_context.rs`, `sandbox_context.rs`, `spawn_depth_context.rs`, `task_recency_context.rs` | explicit `RunContext`/child context | Delete task-local shells. || `subagent_runner/` generic recursion/drive | host-capability `invoke_agent` + `tinyagents-graph` | Keep only OpenHuman request/result mapping if still needed. || `subagent_runner/handoff.rs`, `extract_tool.rs` | `tinyagents-harness::handoff` | Delete OpenHuman wrapper/cache after upstream storage/chunk/extract parity and direct imports. || `session/` loop/turn assembly | `AgentHarness::invoke_agent[_stream]` | Keep OpenHuman transcript/checkpoint persistence and a thin product-facing constructor only if it adds a real OpenHuman API; no runtime duplication. |diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex 4de2903004..d2442ff26c 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -314,13 +314,6 @@"text": "if self.auto_save && crate::agent::turn_origin::current_is_user_authored() {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs",- "line": 141,- "text": "let result = harness::with_parent_context(parent_context.clone(), async move {",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs",@@ -342,13 +335,6 @@"text": "with_current_sandbox_mode(graph.sandbox_mode, async {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs",- "line": 78,- "text": "let result = harness::with_parent_context(parent_ctx, fut).await;",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs",@@ -394,14 +380,14 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 601,+ "line": 632,"text": "let run_result = with_spawn_depth(attempted_depth, async {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 603,+ "line": 634,"text": "with_current_sandbox_mode(definition.sandbox_mode, async {","occurrence": 1},@@ -524,69 +510,6 @@"text": "Ok(with_parent_context(parent, fut).await)","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs",- "line": 11,- "text": "use crate::agent::harness::fork_context::current_parent;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs",- "line": 61,- "text": "let parent = match current_parent() {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs",- "line": 6,- "text": "use crate::agent::harness::fork_context::{current_parent, AgentContextPreparedSource};",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs",- "line": 267,- "text": "let parent_session = current_parent()",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs",- "line": 270,- "text": "let progress_sink = current_parent().and_then(|p| p.on_progress.clone());",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs",- "line": 407,- "text": "if let (Some(parent), Some(thread_id)) = (current_parent(), thread_id) {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs",- "line": 8,- "text": "use crate::agent::harness::fork_context::{current_agent_context_prepared_sources, current_parent};",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs",- "line": 82,- "text": "let Some(parent) = current_parent() else {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs",- "line": 245,- "text": "let prepared_sources = current_agent_context_prepared_sources();",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs",@@ -601,20 +524,6 @@"text": "let parent = match current_parent() {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs",- "line": 12,- "text": "use crate::agent::harness::fork_context::current_parent;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs",- "line": 269,- "text": "let parent = match current_parent() {",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs",@@ -629,34 +538,6 @@"text": "let parent = match current_parent() {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",- "line": 57,- "text": "let parent = match current_parent() {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",- "line": 428,- "text": "let join = tokio::spawn(crate::agent::turn_origin::propagate(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",- "line": 429,- "text": "crate::agent::turn_workspace::propagate(async move {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",- "line": 446,- "text": "let result = with_parent_context(background_parent, async move {",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs",@@ -664,55 +545,6 @@"text": "use crate::agent::harness::fork_context::{current_parent, with_parent_context};","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 204,- "text": "if let Some(parent_ctx) = current_parent() {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 241,- "text": "let parent_ctx = current_parent();",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 431,- "text": "let parent_session = current_parent()",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 441,- "text": "let worker_thread_id = current_parent().and_then(|p| {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 467,- "text": "if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 512,- "text": "let progress_sink = current_parent().and_then(|p| p.on_progress.clone());",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",- "line": 592,- "text": "let workspace_dir = current_parent()",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs",@@ -720,20 +552,6 @@"text": "use crate::agent::harness::fork_context::current_parent;","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs",- "line": 13,- "text": "use crate::agent::harness::fork_context::current_parent;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs",- "line": 203,- "text": "let parent = current_parent().ok_or_else(|| anyhow::anyhow!(\"no parent context\"))?;",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs",@@ -867,20 +685,6 @@"text": "if let Some(parent) = crate::agent::harness::fork_context::current_parent() {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/triage/escalation.rs",- "line": 22,- "text": "use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext};",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/triage/escalation.rs",- "line": 314,- "text": "let outcome = with_parent_context(parent_ctx, async {",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/turn_origin.rs",@@ -1759,7 +1563,7 @@{"rule": "tinyagents-tool-calling-facade","path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/run_loop.rs",- "line": 1001,+ "line": 1000,"text": "use tinytools_agent::dialect::{DialectResponse, ToolDialect, XmlDialect};","occurrence": 1},diff --git a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rsindex b6996d4643..1673653158 100644--- a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs+++ b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs@@ -712,12 +712,13 @@ fn subagent_prompt_renderer_handles_formats_caps_and_stale_tool_indices() -> Res// ── Turn dispatch guard (#5810) ────────────────────────────────────────────────//-// `run_subagent` consults `turn_dispatch_guard::check()` as its first statement+// `run_subagent` consults the explicit `OpenHumanRunContext` dispatch state as+// its first statement// and refuses two ways: a graceful pause already requested at the model-call// cap, and less wall-clock remaining than this turn's slowest completed child.//-// Both cases below install a REAL guard around the call — the gate is a no-op-// outside a turn scope, so a test that skips `with_dispatch_guard` exercises+// Both cases below attach a REAL guard to the explicit carrier — the gate is a+// no-op without that carrier, so a test that skips the carrier exercises// nothing. Each asserts on the refusal AND on the provider request count: the// refusal is meant to cost nothing, so a gate that let the dispatch reach the// model before erroring would still be a defect. Each also drives an ALLOWED@@ -731,42 +732,38 @@ async fn dispatch_is_refused_once_the_turn_has_requested_a_cap_pause() -> Resultlet provider_handle = provider.clone();let parent = parent_context(tmp.path().to_path_buf(), provider);- let outcome = with_parent_context(parent, async {+ let outcome = async {+ let mut root = openhuman_core::agent::tinyagents::host::OpenHumanRunContext::new();+ root.parent = Some(parent);+ let dispatch = Arc::new(openhuman_core::agent::tinyagents::host::TurnDispatchState::new(None));+ root.dispatch = Some(dispatch.clone());// No ceiling, so the budget gate can never fire here and the only thing// under test is the pause.- openhuman_core::agent::harness::turn_dispatch_guard::with_dispatch_guard(- None,- async {// Control: inside the guard, with nothing recorded, a dispatch// must still go through. Without this a gate that refused every// call would satisfy the assertion below.let allowed = run_subagent(&definition(None),"before the cap",- SubagentRunOptions::default(),+ SubagentRunOptions { run_context: root.child(), ..Default::default() },).await;- let state =- openhuman_core::agent::harness::turn_dispatch_guard::current()- .expect("the guard is installed for this turn");- state.record_pause_requested(15, 15);+ dispatch.record_pause_requested(15, 15);let refused = run_subagent(&definition(None),"after the cap",SubagentRunOptions {task_id: Some("post-pause-dispatch".to_string()),+ run_context: root.child(),..SubagentRunOptions::default()},).await;(allowed, refused)- },- )- .await- })+ }.await;let (allowed, refused) = outcome;@@ -809,45 +806,40 @@ async fn dispatch_is_refused_when_less_budget_remains_than_the_slowest_child() -let provider_handle = provider.clone();let parent = parent_context(tmp.path().to_path_buf(), provider);- let outcome = with_parent_context(parent, async {+ let outcome = async {+ let mut root = openhuman_core::agent::tinyagents::host::OpenHumanRunContext::new();+ root.parent = Some(parent);+ let dispatch = Arc::new(openhuman_core::agent::tinyagents::host::TurnDispatchState::new(Some(std::time::Duration::from_secs(3600))));+ root.dispatch = Some(dispatch.clone());// A generous ceiling, so `remaining` stays far above the sample the// control records and only the deliberate one below can trip the gate.- openhuman_core::agent::harness::turn_dispatch_guard::with_dispatch_guard(- Some(std::time::Duration::from_secs(3600)),- async {// Control: a budget of an hour against a one-millisecond// observed maximum must still allow a dispatch.- openhuman_core::agent::harness::turn_dispatch_guard::record_subagent_elapsed(- std::time::Duration::from_millis(1),- );+ dispatch.record_subagent_elapsed(std::time::Duration::from_millis(1));let allowed = run_subagent(&definition(None),"while budget remains",- SubagentRunOptions::default(),+ SubagentRunOptions { run_context: root.child(), ..Default::default() },).await;// Now fold in a child that took far longer than the whole// ceiling. `remaining` is at most an hour; the observed maximum// is a hundred, so the refusal is a fact rather than a race.- openhuman_core::agent::harness::turn_dispatch_guard::record_subagent_elapsed(- std::time::Duration::from_secs(360_000),- );+ dispatch.record_subagent_elapsed(std::time::Duration::from_secs(360_000));let refused = run_subagent(&definition(None),"after the budget is gone",SubagentRunOptions {task_id: Some("over-budget-dispatch".to_string()),+ run_context: root.child(),..SubagentRunOptions::default()},).await;(allowed, refused)- },- )- .await- })+ }.await;let (allowed, refused) = outcome;