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
test(orchestration): thread dispatch context through background delivery tests
Steven Enamakel0a319b6ca432
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rsindex 784d22301a..0f2b50b3c9 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs@@ -23,7 +23,7 @@ fn profile(name: &str, workspace: &std::path::Path) -> Arc<CoreContext> {async fn record(ctx: &Arc<CoreContext>, ws: &std::path::Path, task: &str) {CoreContext::scope(Arc::clone(ctx),- record_completion(ws, "sess-1", task, "researcher", "done", Some("t1".into())),+ record_completion(&crate::core::runtime::DispatchCtx::ambient(), ws, "sess-1", task, "researcher", "done", Some("t1".into())),).await;}@@ -44,7 +44,7 @@ async fn one_profiles_stop_and_delete_never_reach_anothers_thread() {// Alice presses Stop on her `t1`.CoreContext::scope(Arc::clone(&alice), async {- discard_pending_for_thread("t1");+ discard_pending_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "t1");}).await;@@ -57,13 +57,13 @@ async fn one_profiles_stop_and_delete_never_reach_anothers_thread() {// Bob deletes his `t1`; Alice re-engages hers and keeps working.CoreContext::scope(Arc::clone(&bob), async {- discard_for_thread(ws_b.path(), "t1");+ discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), ws_b.path(), "t1");}).await;CoreContext::scope(Arc::clone(&alice), async {- resume_stopped_thread("t1");+ resume_stopped_thread(&crate::core::runtime::DispatchCtx::ambient(), "t1");assert!(- !mark_stopped_task_if_thread_stopped(ws_a.path(), "t1", "alice-2"),+ !mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(), ws_a.path(), "t1", "alice-2"),"bob's delete does not abort alice's child");})@@ -78,7 +78,7 @@ async fn one_profiles_stop_and_delete_never_reach_anothers_thread() {// Each profile resolves `t1` to its own workspace.let resolved = |ctx: &Arc<CoreContext>| {- CoreContext::sync_scope(Arc::clone(ctx), || workspace_for_thread("t1"))+ CoreContext::sync_scope(Arc::clone(ctx), || workspace_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "t1"))};assert_eq!(resolved(&alice).as_deref(), Some(ws_a.path()));assert_eq!(resolved(&bob).as_deref(), Some(ws_b.path()));diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rsindex d68c5c4a75..e3ef9f9e2f 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs@@ -16,7 +16,7 @@ fn workspace() -> TestWorkspace {}fn record(ws: &Path, session: &str, task: &str, summary: &str, thread: Option<&str>) {- futures::executor::block_on(record_completion(+ futures::executor::block_on(record_completion(&crate::core::runtime::DispatchCtx::ambient(),ws,session,task,@@ -76,7 +76,7 @@ fn headless_completion_is_dropped() {.claim_pending("", usize::MAX).unwrap().is_empty());- assert!(recover_pending_threads(ws.path()).is_empty());+ assert!(recover_pending_threads(&crate::core::runtime::DispatchCtx::ambient(), ws.path()).is_empty());}#[test]@@ -85,13 +85,13 @@ fn the_session_is_mapped_to_its_thread_for_the_idle_gate() {let ws = workspace();record(ws.path(), "sess-map", "sub-1", "x", Some("thread-map"));assert_eq!(- thread_for_session("sess-map").as_deref(),+ thread_for_session(&crate::core::runtime::DispatchCtx::ambient(), "sess-map").as_deref(),Some("thread-map"));// A web-channel session id carries its thread in the JSON body.let web = r#"{"client_id":"c","thread_id":"thread-json"}"#;- assert_eq!(thread_for_session(web).as_deref(), Some("thread-json"));- assert_eq!(thread_for_session("cron:job-1"), None);+ assert_eq!(thread_for_session(&crate::core::runtime::DispatchCtx::ambient(), web).as_deref(), Some("thread-json"));+ assert_eq!(thread_for_session(&crate::core::runtime::DispatchCtx::ambient(), "cron:job-1"), None);}#[test]@@ -103,7 +103,7 @@ fn discard_for_thread_removes_matching_and_drops_stragglers() {record(w, "sess-d1", "sub-b", "y", Some("thread-KEEP"));record(w, "sess-d2", "sub-c", "z", Some("thread-DEL"));- assert_eq!(discard_for_thread(w, "thread-DEL"), 2);+ assert_eq!(discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-DEL"), 2);assert!(pending_ids(w, "thread-DEL").is_empty());assert_eq!(pending_ids(w, "thread-KEEP"), ["sub-b"]);}@@ -115,7 +115,7 @@ fn record_after_discard_is_dropped_by_the_cancelled_parent() {let w = ws.path();// The thread is deleted before this process ever saw a child of it: the// delete still writes the cancelled-parent marker in the caller's workspace.- discard_for_thread(w, "thread-race");+ discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-race");// A straggler that records after the sweep (the cooperative-abort race) is// dropped rather than queued.record(w, "sess-race", "sub-late", "stale", Some("thread-race"));@@ -130,17 +130,17 @@ fn a_child_registering_after_its_thread_was_deleted_is_aborted_and_stays_droppedlet _guard = test_guard();let ws = workspace();let w = ws.path();- assert!(!mark_stopped_task_if_thread_stopped(+ assert!(!mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-del-reg","sub-a"));- discard_for_thread(w, "thread-del-reg");+ discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-del-reg");// A child spawned before the delete registers after it: it must be aborted,// and registering must not lift the delete (unlike a stopped thread, a// deleted one never reopens).- assert!(mark_stopped_task_if_thread_stopped(+ assert!(mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-del-reg","sub-b"@@ -273,7 +273,7 @@ fn record_awaiting_input_queues_a_framed_needs_input_for_delivery() {let _guard = test_guard();let ws = workspace();let w = ws.path();- futures::executor::block_on(record_awaiting_input(+ futures::executor::block_on(record_awaiting_input(&crate::core::runtime::DispatchCtx::ambient(),w,"sess-ask","sub-ask",@@ -296,7 +296,7 @@ fn the_outcome_survives_a_claim() {let _guard = test_guard();let ws = workspace();let w = ws.path();- futures::executor::block_on(record_outcome(+ futures::executor::block_on(record_outcome(&crate::core::runtime::DispatchCtx::ambient(),w,"sess-out","sub-1",@@ -335,7 +335,7 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {);// Stop drops the undelivered result so it can't start a delivery turn...- assert_eq!(discard_pending_for_thread("thread-stop-live"), 1);+ assert_eq!(discard_pending_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop-live"), 1);assert!(pending_ids(w, "thread-stop-live").is_empty());assert_eq!(pending_ids(w, "thread-stop-other"), ["sub-stop-keep"]);@@ -352,7 +352,7 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {// Completing Stop keeps the thread gate until a new user turn begins, so a// child that registers after the cancellation sweep is still rejected.- finish_stop_for_thread("thread-stop-live", &["sub-stop-later".into()]);+ finish_stop_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop-live", &["sub-stop-later".into()]);record(w,"sess-stop",@@ -364,13 +364,13 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {// A child that was spawned before Stop but registers after the registry// sweep gets its own tombstone before the thread can be reopened.- assert!(mark_stopped_task_if_thread_stopped(+ assert!(mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-stop-live","sub-stop-registered-late"));- resume_stopped_thread("thread-stop-live");+ resume_stopped_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop-live");record(w,"sess-stop",@@ -398,12 +398,12 @@ fn a_stop_before_a_restart_is_lifted_by_the_first_new_spawn() {let ws = workspace();let w = ws.path();record(w, "sess-rs", "sub-1", "x", Some("thread-restart-stop"));- assert_eq!(discard_pending_for_thread("thread-restart-stop"), 1);+ assert_eq!(discard_pending_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-restart-stop"), 1);// A restart: the in-memory gate is gone, the durable cancelled-parent// marker is not.forget_workspace_for_test(w);- assert!(!mark_stopped_task_if_thread_stopped(+ assert!(!mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-restart-stop","sub-new"@@ -449,7 +449,7 @@ fn undelivered_completions_are_found_again_after_a_restart() {drop(router);forget_workspace_for_test(w);- let threads = recover_pending_threads(w);+ let threads = recover_pending_threads(&crate::core::runtime::DispatchCtx::ambient(), w);assert_eq!(threads,@@ -460,7 +460,7 @@ fn undelivered_completions_are_found_again_after_a_restart() {pending_for(w, "thread-boot")[0].result.text,"unseen result");- assert!(router_for_thread("thread-boot").is_some());+ assert!(router_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-boot").is_some());}#[test]@@ -469,13 +469,13 @@ fn a_delete_survives_a_restart_and_is_not_lifted_by_a_new_spawn() {let ws = workspace();let w = ws.path();record(w, "sess-dr", "sub-1", "x", Some("thread-del-restart"));- assert_eq!(discard_for_thread(w, "thread-del-restart"), 1);+ assert_eq!(discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-del-restart"), 1);// A restart: memory is gone, the durable markers are not. A late child for// the deleted thread must be aborted rather than treated as a user returning// to a stopped thread, and its result must stay dropped.forget_workspace_for_test(w);- assert!(mark_stopped_task_if_thread_stopped(+ assert!(mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-del-restart","sub-late"@@ -536,12 +536,12 @@ fn clear_all_also_withdraws_a_completion_a_delivery_has_leased() {fn the_session_cache_evicts_its_oldest_mapping_only() {let _guard = test_guard();for i in 0..(SESSION_THREADS_CAP + 5) {- note_session_thread(&format!("evict-sess-{i}"), &format!("evict-thread-{i}"));+ note_session_thread(&crate::core::runtime::DispatchCtx::ambient(), &format!("evict-sess-{i}"), &format!("evict-thread-{i}"));}- assert_eq!(thread_for_session("evict-sess-0"), None, "oldest evicted");+ assert_eq!(thread_for_session(&crate::core::runtime::DispatchCtx::ambient(), "evict-sess-0"), None, "oldest evicted");for survivor in [5, SESSION_THREADS_CAP / 2, SESSION_THREADS_CAP + 4] {assert_eq!(- thread_for_session(&format!("evict-sess-{survivor}")).as_deref(),+ thread_for_session(&crate::core::runtime::DispatchCtx::ambient(), &format!("evict-sess-{survivor}")).as_deref(),Some(format!("evict-thread-{survivor}").as_str()),"a surviving session still resolves to its own thread");@@ -554,14 +554,14 @@ fn a_delete_marker_outlives_compaction() {let ws = workspace();let w = ws.path();record(w, "sess-cm", "sub-1", "x", Some("thread-compact"));- discard_for_thread(w, "thread-compact");+ discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-compact");// Settled records expire; the deletion must not.router_for_workspace(w).compact(std::time::Duration::ZERO).unwrap();forget_workspace_for_test(w);- assert!(mark_stopped_task_if_thread_stopped(+ assert!(mark_stopped_task_if_thread_stopped(&crate::core::runtime::DispatchCtx::ambient(),w,"thread-compact","sub-late"@@ -573,7 +573,7 @@ fn deleting_a_thread_that_never_used_background_work_writes_nothing() {let _guard = test_guard();let ws = workspace();let w = ws.path();- assert_eq!(discard_for_thread(w, "thread-plain"), 0);+ assert_eq!(discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-plain"), 0);assert!(entry_for(w).store.list(None).is_empty(),"no marker is persisted for an ordinary thread"@@ -589,7 +589,7 @@ fn a_late_record_for_a_deleted_thread_is_dropped_by_the_durable_marker_alone() {let ws = workspace();let w = ws.path();record(w, "sess-dm", "sub-1", "x", Some("thread-dm"));- discard_for_thread(w, "thread-dm");+ discard_for_thread(&crate::core::runtime::DispatchCtx::ambient(), w, "thread-dm");// A restart empties the in-memory gates; the marker on disk still decides.forget_workspace_for_test(w);record(w, "sess-dm", "sub-late", "stale", Some("thread-dm"));@@ -601,7 +601,7 @@ async fn release_all_closes_every_router_and_the_log_stays_replayable() {let _guard = crate::config::TEST_ENV_LOCK.lock().await;let ws = workspace();let w = ws.path();- record_completion(+ record_completion(&crate::core::runtime::DispatchCtx::ambient(),w,"sess-rel","sub-1",@@ -617,12 +617,12 @@ async fn release_all_closes_every_router_and_the_log_stays_replayable() {"the router (and its log handle) is dropped");assert!(- workspace_for_thread("thread-rel").is_none(),+ workspace_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-rel").is_none(),"process-local maps are cleared");// The next boot finds the undelivered completion from the log alone.- assert_eq!(recover_pending_threads(w), ["thread-rel"]);+ assert_eq!(recover_pending_threads(&crate::core::runtime::DispatchCtx::ambient(), w), ["thread-rel"]);}#[tokio::test(start_paused = true)]@@ -662,16 +662,16 @@ async fn release_all_keeps_the_stop_and_delete_gates() {let _guard = crate::config::TEST_ENV_LOCK.lock().await;let ws = workspace();let w = ws.path();- discard_pending_for_thread("thread-keep-stop");+ discard_pending_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-keep-stop");state().deleted_threads.insert("thread-keep-del".into());release_all().await;// A detached child finishing after the release is still refused.- record_completion(w, "s", "sub-1", "r", "x", Some("thread-keep-stop".into())).await;- record_completion(w, "s", "sub-2", "r", "x", Some("thread-keep-del".into())).await;+ record_completion(&crate::core::runtime::DispatchCtx::ambient(), w, "s", "sub-1", "r", "x", Some("thread-keep-stop".into())).await;+ record_completion(&crate::core::runtime::DispatchCtx::ambient(), w, "s", "sub-2", "r", "x", Some("thread-keep-del".into())).await;assert!(pending_ids(w, "thread-keep-stop").is_empty());assert!(pending_ids(w, "thread-keep-del").is_empty());- resume_stopped_thread("thread-keep-stop");+ resume_stopped_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-keep-stop");state().deleted_threads.remove("thread-keep-del");}@@ -708,7 +708,7 @@ async fn a_store_that_keeps_failing_degrades_to_memory_instead_of_losing_the_reslet w = ws.path();install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));- record_completion(+ record_completion(&crate::core::runtime::DispatchCtx::ambient(),w,"sess-fd","sub-1",diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_recovery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_recovery_tests.rsindex 9ebbe88ca9..b5614e37ee 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_recovery_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_recovery_tests.rs@@ -8,7 +8,7 @@ async fn a_mixed_batch_that_partly_gives_up_still_retries_the_rest() {record(w, "bd-mixed", "sub-old", "old", "thread-mixed").await;let router = router_for_workspace(w);for _ in 0..(DEFAULT_MAX_ATTEMPTS - 1) {- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-mixed".into(),router.clone(),|_t, _n| async move { Err::<String, String>("checkout failed".to_string()) },@@ -21,7 +21,7 @@ async fn a_mixed_batch_that_partly_gives_up_still_retries_the_rest() {let gave_up = Arc::new(Mutex::new(String::new()));let sink = Arc::clone(&gave_up);- let retry = try_deliver_with(+ let retry = try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-mixed".into(),router,|_t, _n| async move { Err::<String, String>("checkout failed".to_string()) },diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_slots_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_slots_tests.rsindex c7bf099b0b..5c2f6b72e8 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_slots_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_slots_tests.rs@@ -49,7 +49,7 @@ async fn pair() -> Pair {for (ctx, ws, task) in [(&alice, &ws_a, "task-alice"), (&bob, &ws_b, "task-bob")] {CoreContext::scope(Arc::clone(ctx),- record_completion(+ record_completion(&crate::core::runtime::DispatchCtx::ambient(),ws.path(),&session,task,@@ -78,22 +78,22 @@ fn in_scope<R>(ctx: &Arc<CoreContext>, f: impl FnOnce() -> R) -> R {async fn one_profiles_busy_turn_does_not_block_anothers_thread() {let _guard = crate::config::TEST_ENV_LOCK.lock().await;let p = pair().await;- let turn = in_scope(&p.alice, || TurnBusy::start(&p.session));+ let turn = in_scope(&p.alice, || TurnBusy::start(&crate::core::runtime::DispatchCtx::ambient(), &p.session));- assert!(in_scope(&p.alice, || is_busy(&p.thread)));- assert!(!in_scope(&p.bob, || is_busy(&p.thread)));+ assert!(in_scope(&p.alice, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &p.thread)));+ assert!(!in_scope(&p.bob, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &p.thread)));let router_b = router_for_workspace(p.ws_b.path());- let batch = in_scope(&p.bob, || claim_ready(&router_b, &p.thread))+ let batch = in_scope(&p.bob, || claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router_b, &p.thread)).expect("bob's thread is idle while alice's turn runs");assert_eq!(batch[0].task_id, "task-bob");router_b.release(&["task-bob".to_string()]);// Bob's Stop clears only Bob's turns; Alice stays busy.- assert_eq!(in_scope(&p.bob, || clear_busy_for_thread(&p.thread)), 0);- assert!(in_scope(&p.alice, || is_busy(&p.thread)));+ assert_eq!(in_scope(&p.bob, || clear_busy_for_thread(&crate::core::runtime::DispatchCtx::ambient(), &p.thread)), 0);+ assert!(in_scope(&p.alice, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &p.thread)));drop(turn);- assert!(!in_scope(&p.alice, || is_busy(&p.thread)));+ assert!(!in_scope(&p.alice, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &p.thread)));}#[tokio::test]@@ -106,18 +106,18 @@ async fn a_delivery_in_flight_for_one_profile_does_not_take_anothers_slot() {);let held = in_scope(&p.alice, || {- DeliverySlot::claim(&p.thread, router_a.clone())+ DeliverySlot::claim(&crate::core::runtime::DispatchCtx::ambient(), &p.thread, router_a.clone())}).expect("alice claims her slot");assert!(- in_scope(&p.alice, || DeliverySlot::claim(+ in_scope(&p.alice, || DeliverySlot::claim(&crate::core::runtime::DispatchCtx::ambient(),&p.thread,router_a.clone())).is_none(),"one delivery per thread within a profile");- let bob_slot = in_scope(&p.bob, || DeliverySlot::claim(&p.thread, router_b.clone()));+ let bob_slot = in_scope(&p.bob, || DeliverySlot::claim(&crate::core::runtime::DispatchCtx::ambient(), &p.thread, router_b.clone()));assert!(bob_slot.is_some(),"alice's delivery does not hold bob's slot"@@ -146,7 +146,7 @@ async fn a_delivery_in_flight_for_one_profile_does_not_take_anothers_slot() {async move {let retry = CoreContext::scope(bob,- try_deliver_with(thread, router_bob, bob_log, |_t, _n| async {+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(), thread, router_bob, bob_log, |_t, _n| async {unreachable!("bob's delivery succeeds")}),)@@ -157,7 +157,7 @@ async fn a_delivery_in_flight_for_one_profile_does_not_take_anothers_slot() {};let retry = CoreContext::scope(Arc::clone(&p.alice),- try_deliver_with(p.thread.clone(), router_a, alice_deliver, |_t, _n| async {+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(), p.thread.clone(), router_a, alice_deliver, |_t, _n| async {unreachable!("alice's delivery succeeds")}),)@@ -182,18 +182,18 @@ async fn desktop_keys_are_the_bare_ids() {let thread = unique("t-desk");let session = unique("desk-session");in_scope(&desktop, || {- background_completions::note_session_thread(&session, &thread)+ background_completions::note_session_thread(&crate::core::runtime::DispatchCtx::ambient(), &session, &thread)});- let turn = in_scope(&desktop, || TurnBusy::start(&session));+ let turn = in_scope(&desktop, || TurnBusy::start(&crate::core::runtime::DispatchCtx::ambient(), &session));assert_eq!(turn.key, session);assert!(busy().lock().unwrap().contains_key(&session));- assert!(in_scope(&desktop, || is_busy(&thread)));+ assert!(in_scope(&desktop, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &thread)));drop(turn);assert!(!busy().lock().unwrap().contains_key(&session));let router = router_for_workspace(ws.path());- let slot = in_scope(&desktop, || DeliverySlot::claim(&thread, router)).expect("free");+ let slot = in_scope(&desktop, || DeliverySlot::claim(&crate::core::runtime::DispatchCtx::ambient(), &thread, router)).expect("free");assert_eq!(slot.key, thread);assert!(delivering().lock().unwrap().contains(&thread));drop(slot);@@ -207,13 +207,13 @@ async fn an_older_guard_dropping_keeps_a_replacement_turn_busy() {let thread = unique("t-interrupt");let session = web_session(&thread);- let old = in_scope(&desktop, || TurnBusy::start(&session));- let new = in_scope(&desktop, || TurnBusy::start(&session));+ let old = in_scope(&desktop, || TurnBusy::start(&crate::core::runtime::DispatchCtx::ambient(), &session));+ let new = in_scope(&desktop, || TurnBusy::start(&crate::core::runtime::DispatchCtx::ambient(), &session));drop(old);assert!(- in_scope(&desktop, || is_busy(&thread)),+ in_scope(&desktop, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &thread)),"replacement still running");drop(new);- assert!(!in_scope(&desktop, || is_busy(&thread)));+ assert!(!in_scope(&desktop, || is_busy(&crate::core::runtime::DispatchCtx::ambient(), &thread)));}diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tenant_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tenant_tests.rsindex 5b46763d78..26c37f076e 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tenant_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tenant_tests.rs@@ -45,7 +45,7 @@ fn seen_by(drain: &Drain) -> (Option<String>, String, Vec<String>) {let ctx = drain.owner.clone().expect("a SaaS drain carries its owner");let profile = ctx.profile().map(str::to_owned);let pending = CoreContext::sync_scope(ctx, || {- let ws = workspace_for_thread(&drain.thread_id).expect("owner knows its thread");+ let ws = workspace_for_thread(&crate::core::runtime::DispatchCtx::ambient(), &drain.thread_id).expect("owner knows its thread");pending_for(&ws, &drain.thread_id).into_iter().map(|r| r.task_id)@@ -69,7 +69,7 @@ async fn an_off_task_completion_drains_only_its_owners_thread() {for (ctx, ws, task) in [(&alice, &ws_a, &task_a), (&bob, &ws_b, &task_b)] {CoreContext::scope(Arc::clone(ctx),- record_completion(+ record_completion(&crate::core::runtime::DispatchCtx::ambient(),ws.path(),&session,task.as_str(),diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rsindex 200e30c682..d2764396f0 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs@@ -16,7 +16,7 @@ fn workspace() -> TestWorkspace {}async fn record(ws: &Path, session: &str, task: &str, summary: &str, thread: &str) {let thread = Some(thread.to_owned());- record_completion(ws, session, task, "researcher", summary, thread).await;+ record_completion(&crate::core::runtime::DispatchCtx::ambient(), ws, session, task, "researcher", summary, thread).await;}fn pending_ids(ws: &Path, thread: &str) -> Vec<String> {pending_for(ws, thread)@@ -47,14 +47,14 @@ async fn claim_takes_the_ready_batch_when_idle() {record(w, "bd-ready", "sub-2", "beta", "thread-ready").await;let router = router_for_workspace(w);- let batch = claim_ready(&router, "thread-ready").expect("claims a batch");+ let batch = claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router, "thread-ready").expect("claims a batch");assert_eq!(batch.len(), 2);let notice = router.formatter().format_batch(&batch);assert!(notice.contains("sub-1") && notice.contains("sub-2"));// The records stay pending (leased) until the turn lands.assert_eq!(pending_ids(w, "thread-ready").len(), 2);assert!(- claim_ready(&router, "thread-ready").is_none(),+ claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router, "thread-ready").is_none(),"a held lease is not claimed twice");}@@ -68,10 +68,10 @@ async fn claim_skips_a_busy_thread_and_leaves_the_queue_intact() {let router = router_for_workspace(w);mark_busy("bd-busy");- assert!(claim_ready(&router, "thread-busy").is_none());+ assert!(claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router, "thread-busy").is_none());clear_busy("bd-busy");assert!(- claim_ready(&router, "thread-busy").is_some(),+ claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router, "thread-busy").is_some(),"a deferral leaves the record claimable");assert_eq!(@@ -86,7 +86,7 @@ async fn claim_is_none_when_nothing_is_pending() {let _g = test_guard().await;let ws = workspace();let router = router_for_workspace(ws.path());- assert!(claim_ready(&router, "bd-empty-unique").is_none());+ assert!(claim_ready(&crate::core::runtime::DispatchCtx::ambient(), &router, "bd-empty-unique").is_none());}#[tokio::test]@@ -99,7 +99,7 @@ async fn a_delivered_batch_is_settled_and_not_redelivered() {let turns = Arc::new(AtomicU32::new(0));let seen = Arc::clone(&turns);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-ok".into(),router.clone(),move |thread, notice| {@@ -133,7 +133,7 @@ async fn persistence_failure_releases_batch_without_terminal_announcement() {let announced = Arc::new(AtomicBool::new(false));let announced_for_delivery = Arc::clone(&announced);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-persist".into(),router.clone(),move |_thread_id, _notice| {@@ -173,10 +173,10 @@ async fn persistence_failure_releases_batch_without_terminal_announcement() {async fn a_turn_is_busy_until_its_guard_drops() {let sid = r#"{"client_id":"c","thread_id":"bd-turn-thread"}"#.to_string();- let turn = TurnBusy::start(&sid);- assert!(is_busy("bd-turn-thread"));+ let turn = TurnBusy::start(&crate::core::runtime::DispatchCtx::ambient(), &sid);+ assert!(is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-turn-thread"));drop(turn);- assert!(!is_busy("bd-turn-thread"));+ assert!(!is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-turn-thread"));// The bus events no longer mark busy: the subscriber runs off-task and// cannot tell which profile a session belongs to.@@ -186,7 +186,7 @@ async fn a_turn_is_busy_until_its_guard_drops() {channel: "test".into(),}).await;- assert!(!is_busy("bd-turn-thread"));+ assert!(!is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-turn-thread"));}/// Drive the real delivery loop with a turn executor that always fails, the@@ -206,7 +206,7 @@ async fn drain_until_empty_or(}let turns_for_delivery = Arc::clone(&turns);let sink = Arc::clone(&undelivered);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),thread.to_string(),router.clone(),move |_thread_id, _notice| {@@ -307,7 +307,7 @@ async fn transient_failure_under_the_ceiling_keeps_the_result() {record(w, "bd-transient", "sub-1", "alpha", "thread-transient").await;let router = router_for_workspace(w);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-transient".into(),router.clone(),|_t, _n| async move { Err::<String, String>("blip".to_string()) },@@ -341,7 +341,7 @@ async fn busy_deferral_does_not_consume_the_failure_budget() {for _ in 0..(DEFAULT_MAX_ATTEMPTS * 2) {mark_busy("bd-busy-defer");- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-busy-defer".into(),router.clone(),|_t, _n| async move { unreachable!("must not run a delivery turn while busy") },@@ -415,13 +415,13 @@ async fn a_pending_completion_survives_a_restart_and_is_delivered() {drop(router);forget_workspace_for_test(w);- let threads = background_completions::recover_pending_threads(w);+ let threads = background_completions::recover_pending_threads(&crate::core::runtime::DispatchCtx::ambient(), w);assert_eq!(threads, ["thread-restart"]);- let router = background_completions::router_for_thread("thread-restart").expect("recovered");+ let router = background_completions::router_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-restart").expect("recovered");let delivered = Arc::new(Mutex::new(Vec::<String>::new()));let sink = Arc::clone(&delivered);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-restart".into(),router,move |thread, notice| {@@ -447,7 +447,7 @@ async fn a_pending_completion_survives_a_restart_and_is_delivered() {);forget_workspace_for_test(w);- assert!(background_completions::recover_pending_threads(w).is_empty());+ assert!(background_completions::recover_pending_threads(&crate::core::runtime::DispatchCtx::ambient(), w).is_empty());}#[tokio::test]@@ -525,7 +525,7 @@ async fn a_delivered_batch_restores_the_full_failure_budget() {router_for_workspace(w)};for _ in 0..(DEFAULT_MAX_ATTEMPTS - 1) {- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-budget".into(),router.clone(),|_t, _n| async move { Err::<String, String>("blip".to_string()) },@@ -533,7 +533,7 @@ async fn a_delivered_batch_restores_the_full_failure_budget() {).await;}- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-budget".into(),router.clone(),|_t, _n| async move { Ok::<String, String>("delivered".to_string()) },@@ -567,7 +567,7 @@ async fn a_dropped_delivery_releases_its_slot_and_lease() {let in_flight = tokio::spawn({let router = router.clone();async move {- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-drop".into(),router,move |_t, _n| {@@ -587,7 +587,7 @@ async fn a_dropped_delivery_releases_its_slot_and_lease() {let delivered = Arc::new(Mutex::new(false));let flag = Arc::clone(&delivered);- try_deliver_with(+ try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-drop".into(),router,move |_t, _n| {@@ -617,7 +617,7 @@ async fn a_failed_turn_under_the_ceiling_asks_for_a_backoff_retry() {record(w, "bd-retry", "sub-1", "alpha", "thread-retry").await;let router = router_for_workspace(w);- let retry = try_deliver_with(+ let retry = try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-retry".into(),router.clone(),|_t, _n| async move { Err::<String, String>("session checkout failed".to_string()) },@@ -626,7 +626,7 @@ async fn a_failed_turn_under_the_ceiling_asks_for_a_backoff_retry() {.await;assert_eq!(retry, Some(retry_backoff(1)));- let delivered = try_deliver_with(+ let delivered = try_deliver_with(&crate::core::runtime::DispatchCtx::ambient(),"thread-retry".into(),router,|_t, _n| async move { Ok::<String, String>("presented".to_string()) },@@ -658,13 +658,13 @@ async fn boot_recovery_schedules_a_delivery_for_every_thread_with_undelivered_reforget_workspace_for_test(w);scheduled_for_test().lock().expect("scheduled").clear();- assert_eq!(recover_on_boot(w), 1);+ assert_eq!(recover_on_boot(&crate::core::runtime::DispatchCtx::ambient(), w), 1);assert!(scheduled_for_test().lock().expect("scheduled").contains(&("thread-boot-sched".to_string(), RECOVERY_DELAY)));assert_eq!(- recover_on_boot(w),+ recover_on_boot(&crate::core::runtime::DispatchCtx::ambient(), w),0,"a workspace is scanned once per process");@@ -677,10 +677,10 @@ async fn recover_on_open_rescans_a_workspace_already_recovered() {let w = ws.path();record(w, "bd-open", "sub-1", "left pending", "thread-open-resc").await;forget_workspace_for_test(w);- assert_eq!(recover_on_boot(w), 1);- assert_eq!(recover_on_boot(w), 0, "boot recovery claims once");+ assert_eq!(recover_on_boot(&crate::core::runtime::DispatchCtx::ambient(), w), 1);+ assert_eq!(recover_on_boot(&crate::core::runtime::DispatchCtx::ambient(), w), 0, "boot recovery claims once");assert_eq!(- recover_on_open(w, DrainFence::none()),+ recover_on_open(&crate::core::runtime::DispatchCtx::ambient(), w, DrainFence::none()),1,"a re-open scans again");@@ -694,12 +694,12 @@ async fn a_cancelled_turn_does_not_leave_the_thread_busy() {let other = r#"{"client_id":"c","thread_id":"bd-other-thread"}"#;mark_busy(session);mark_busy(other);- assert!(is_busy("bd-stale-thread"));+ assert!(is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-stale-thread"));- assert_eq!(clear_busy_for_thread("bd-stale-thread"), 1);+ assert_eq!(clear_busy_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "bd-stale-thread"), 1);- assert!(!is_busy("bd-stale-thread"));- assert!(is_busy("bd-other-thread"), "other threads are untouched");+ assert!(!is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-stale-thread"));+ assert!(is_busy(&crate::core::runtime::DispatchCtx::ambient(), "bd-other-thread"), "other threads are untouched");clear_busy(other);}diff --git a/crates/openhuman-core/src/agent/orchestration/delivery_drain_tests.rs b/crates/openhuman-core/src/agent/orchestration/delivery_drain_tests.rsindex 71d5175c26..e385371da5 100644--- a/crates/openhuman-core/src/agent/orchestration/delivery_drain_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/delivery_drain_tests.rs@@ -38,7 +38,7 @@ async fn drain() -> (DrainOutcome, bool) {let ran = Arc::new(AtomicBool::new(false));let flag = Arc::clone(&ran);- let outcome = run_drain(thread, delay, wait_idle, fence, SHORT, || async move {+ let outcome = run_drain(&crate::core::runtime::DispatchCtx::ambient(), thread, delay, wait_idle, fence, SHORT, || async move {flag.store(true, Ordering::SeqCst);}).await;@@ -113,7 +113,7 @@ async fn an_expired_grant_fences_the_drain_without_a_latch() {async fn losing_the_lease_while_waiting_for_an_idle_thread_drops_the_drain() {let _g = crate::config::TEST_ENV_LOCK.lock().await;let (_leases, fence) = live_fence();- let turn = TurnBusy::start_on_thread("dd-busy-fenced");+ let turn = TurnBusy::start_on_thread(&crate::core::runtime::DispatchCtx::ambient(), "dd-busy-fenced");let latch = Arc::clone(&fence);tokio::spawn(async move {tokio::time::sleep(SHORT * 3).await;@@ -129,8 +129,8 @@ async fn losing_the_lease_while_waiting_for_an_idle_thread_drops_the_drain() {async fn a_recovered_drain_waits_for_a_relayed_turn_on_its_thread() {let _g = crate::config::TEST_ENV_LOCK.lock().await;let thread = "dd-relayed-thread";- let turn = TurnBusy::start_on_thread(thread);- assert!(is_busy(thread), "a relayed turn marks its thread busy");+ let turn = TurnBusy::start_on_thread(&crate::core::runtime::DispatchCtx::ambient(), thread);+ assert!(is_busy(&crate::core::runtime::DispatchCtx::ambient(), thread), "a relayed turn marks its thread busy");let release = tokio::spawn(async move {tokio::time::sleep(SHORT * 3).await;drop(turn);@@ -139,7 +139,7 @@ async fn a_recovered_drain_waits_for_a_relayed_turn_on_its_thread() {release.await.unwrap();assert_eq!(outcome, DrainOutcome::Ran);assert!(ran);- assert!(!is_busy(thread));+ assert!(!is_busy(&crate::core::runtime::DispatchCtx::ambient(), thread));}#[tokio::test]@@ -148,7 +148,7 @@ async fn a_delivery_waits_while_a_relayed_turn_runs_on_its_thread() {let ws = TestWorkspace::new();let w = ws.path();let thread = "dd-relay-deliver";- record_completion(+ record_completion(&crate::core::runtime::DispatchCtx::ambient(),w,"dd-relay-session","sub-relay",@@ -160,14 +160,14 @@ async fn a_delivery_waits_while_a_relayed_turn_runs_on_its_thread() {let router = router_for_workspace(w);let turns = Arc::new(AtomicU32::new(0));let attempt = |turns: Arc<AtomicU32>| {- super::super::background_delivery::try_deliver_for_test(+ super::super::background_delivery::try_deliver_for_test(&crate::core::runtime::DispatchCtx::ambient(),thread.to_string(),Arc::clone(&router),turns,)};- let relayed = TurnBusy::start_on_thread(thread);+ let relayed = TurnBusy::start_on_thread(&crate::core::runtime::DispatchCtx::ambient(), thread);attempt(Arc::clone(&turns)).await;assert_eq!(turns.load(Ordering::SeqCst),diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rsindex fd17f341fe..09dc46a376 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rs@@ -227,7 +227,7 @@ async fn saas_dispatch_exposes_only_the_callers_detached_worker_controls() {}).await;CoreContext::scope(pair.alice.clone(), async {- assert!(resume_ref_for_task(&pair.a.task, PARENT).is_ok());+ assert!(resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok());}).await;for function in ["steer", "cancel"] {@@ -322,7 +322,7 @@ async fn unscoped_async_spawn_refuses_before_persisting_a_running_session() {sessions.is_empty(),"refused spawn must not create durable sessions: {sessions:?}");- assert!(snapshot_for_parent(PARENT).is_empty());+ assert!(snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), PARENT).is_empty());assert!(std::fs::read_dir(workspace.path()).unwrap()@@ -339,7 +339,7 @@ async fn same_parent_rosters_are_profile_isolated() {}let pair = Pair::new();for (ctx, own) in [(&pair.alice, &pair.a), (&pair.bob, &pair.b)] {- let tasks = CoreContext::sync_scope(ctx.clone(), || snapshot_for_parent(PARENT));+ let tasks = CoreContext::sync_scope(ctx.clone(), || snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), PARENT));assert_eq!(tasks.iter().map(|t| t.task_id.as_str()).collect::<Vec<_>>(),[own.task.as_str()]@@ -358,11 +358,11 @@ async fn same_parent_resolution_and_wait_refuse_foreign_workers() {let pair = Pair::new();CoreContext::scope(pair.bob.clone(), async {assert!(matches!(- task_id_for_session(&pair.a.session, PARENT),+ task_id_for_session(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.session, PARENT),Err(WaitError::NotOwned)));assert!(matches!(- resume_ref_for_task(&pair.a.task, PARENT),+ resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT),Err(WaitError::NotOwned)));assert!(matches!(@@ -370,7 +370,7 @@ async fn same_parent_resolution_and_wait_refuse_foreign_workers() {Err(WaitError::NotOwned)));assert_eq!(- task_id_for_session(&pair.b.session, PARENT).unwrap(),+ task_id_for_session(&crate::core::runtime::DispatchCtx::ambient(), &pair.b.session, PARENT).unwrap(),pair.b.task);})@@ -435,7 +435,7 @@ async fn public_cancellation_refuses_another_profiles_task() {field(&control("cancel", &pair.a.task).await, "cancelled"),Some(false));- assert!(resume_ref_for_task(&pair.b.task, PARENT).is_ok());+ assert!(resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.b.task, PARENT).is_ok());assert_eq!(field(&control("cancel", &pair.b.task).await, "cancelled"),Some(true)@@ -444,7 +444,7 @@ async fn public_cancellation_refuses_another_profiles_task() {.await;CoreContext::scope(pair.alice.clone(), async {assert!(- resume_ref_for_task(&pair.a.task, PARENT).is_ok(),+ resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok(),"foreign cancel leaves original worker live");})@@ -461,9 +461,9 @@ async fn missing_saas_scope_cannot_observe_or_control_workers() {}let pair = Pair::new();assert!(CoreContext::scoped().is_none());- assert!(snapshot_for_parent(PARENT).is_empty());+ assert!(snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), PARENT).is_empty());assert!(matches!(- resume_ref_for_task(&pair.a.task, PARENT),+ resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT),Err(WaitError::NotOwned)));assert_eq!(@@ -480,13 +480,13 @@ async fn missing_saas_scope_cannot_observe_or_control_workers() {);assert_eq!(pair.a.queue.status().await.steers, 0);CoreContext::sync_scope(pair.alice.clone(), || {- assert!(resume_ref_for_task(&pair.a.task, PARENT).is_ok())+ assert!(resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok())});// A scoped kernel context without an admitted profile is not authority.CoreContext::scope(CoreContext::for_test(DomainSet::full(), None), async {- assert!(snapshot_for_parent(PARENT).is_empty());+ assert!(snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), PARENT).is_empty());assert!(matches!(- resume_ref_for_task(&pair.a.task, PARENT),+ resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), &pair.a.task, PARENT),Err(WaitError::NotOwned)));assert_eq!(@@ -511,7 +511,7 @@ async fn desktop_public_controls_remain_available_without_parent_scope() {}let directory = tempfile::tempdir().unwrap();let worker = Worker::register(directory.path());- assert_eq!(snapshot_for_parent(PARENT).len(), 1);+ assert_eq!(snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), PARENT).len(), 1);assert_eq!(field(&control("steer", &worker.task).await, "steered"),Some(true)diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rsindex c3fb46a1a8..f79a3debf0 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs@@ -146,7 +146,7 @@ async fn task_store_records_spawn_complete_and_cancel() {// A second sub-agent that gets cancelled is recorded Cancelled.let _tx2 = register_test("task-ledger-2", "ledger-parent", run_queue());- assert!(cancel_by_task("task-ledger-2").is_some());+ assert!(cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "task-ledger-2").is_some());let cancelled = task_records(None).into_iter().find(|r| r.spec.task_id.as_str() == "task-ledger-2")@@ -176,11 +176,11 @@ async fn task_id_for_session_enforces_parent_ownership() {.expect("fixture registration admitted");assert_eq!(- task_id_for_session("subsess-1", "session-owner").unwrap(),+ task_id_for_session(&crate::core::runtime::DispatchCtx::ambient(), "subsess-1", "session-owner").unwrap(),"task-session");assert!(matches!(- task_id_for_session("subsess-1", "session-other"),+ task_id_for_session(&crate::core::runtime::DispatchCtx::ambient(), "subsess-1", "session-other"),Err(WaitError::NotOwned)));let _ = tx.send(DetachedSubagentStatus::Completed {@@ -243,7 +243,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {}).unwrap();- let snap = snapshot_for_parent("fleet-parent");+ let snap = snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), "fleet-parent");assert_eq!(snap.len(), 2, "only this parent's workers: {snap:?}");// Ordered by agent_id then task_id → code_executor before researcher.assert_eq!(snap[0].agent_id, "code_executor");@@ -252,7 +252,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {assert_eq!(snap[1].status, "running");let block =- active_subagents_context_block("fleet-parent", &test_workspace(), &FleetToolSet::all())+ active_subagents_context_block(&crate::core::runtime::DispatchCtx::ambient(), "fleet-parent", &test_workspace(), &FleetToolSet::all()).expect("block present");assert!(block.contains("[active_subagents]"));assert!(block.contains("use wait_subagent to collect"));@@ -263,7 +263,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {// A parent with no registered workers gets no block (no perturbation).assert!(- active_subagents_context_block("nobody-here", &test_workspace(), &FleetToolSet::all())+ active_subagents_context_block(&crate::core::runtime::DispatchCtx::ambient(), "nobody-here", &test_workspace(), &FleetToolSet::all()).is_none());@@ -274,7 +274,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {let registry = AgentDefinitionRegistry::builtins_only();let def = registry.get("orchestrator").expect("built-in orchestrator");let fleet = FleetToolSet::from_scope(&def.tools, &def.disallowed_tools);- let block = active_subagents_context_block("fleet-parent", &test_workspace(), &fleet)+ let block = active_subagents_context_block(&crate::core::runtime::DispatchCtx::ambient(), "fleet-parent", &test_workspace(), &fleet).expect("block present");for name in ["wait_subagent",@@ -335,13 +335,13 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {.expect("mark idle");let block =- active_subagents_context_block("cold-parent", durable_ws.path(), &FleetToolSet::all())+ active_subagents_context_block(&crate::core::runtime::DispatchCtx::ambient(), "cold-parent", durable_ws.path(), &FleetToolSet::all()).expect("durable-only roster present");assert!(block.contains(&format!("session={}", session.subagent_session_id)));assert!(block.contains("status=idle"));assert!(block.contains("about: Daily X trending email workflow"));// Other parents' durable sessions must not leak in.- assert!(active_subagents_context_block(+ assert!(active_subagents_context_block(&crate::core::runtime::DispatchCtx::ambient(),"unrelated-parent",durable_ws.path(),&FleetToolSet::all()@@ -380,7 +380,7 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {).expect("fixture registration admitted");- let reference = resume_ref_for_task("task-resume", "session-owner").expect("resume reference");+ let reference = resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), "task-resume", "session-owner").expect("resume reference");assert_eq!(reference.task_id, "task-resume");assert_eq!(reference.agent_id, "researcher");assert_eq!(@@ -388,7 +388,7 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {Some("subsess-resume"));assert!(matches!(- resume_ref_for_task("task-resume", "session-other"),+ resume_ref_for_task(&crate::core::runtime::DispatchCtx::ambient(), "task-resume", "session-other"),Err(WaitError::NotOwned)));@@ -436,7 +436,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {.expect("fixture registration admitted");assert_eq!(- task_id_for_session("subsess-live", "session-owner").unwrap(),+ task_id_for_session(&crate::core::runtime::DispatchCtx::ambient(), "subsess-live", "session-owner").unwrap(),"task-new");prune("task-old");@@ -513,7 +513,7 @@ async fn cancel_for_thread_aborts_only_matching_entries() {// Headless (no parent thread) — must survive.let _d = register_test_with_thread("task-headless", "session-A", None, rq);- let cancelled = cancel_for_thread("thread-X");+ let cancelled = cancel_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-X");assert_eq!(cancelled, 2, "both thread-X entries should be cancelled");// The two cancelled entries are gone (steer can't find them).@@ -537,7 +537,7 @@ async fn cancel_for_thread_aborts_only_matching_entries() {);// Idempotent: a second pass cancels nothing.- assert_eq!(cancel_for_thread("thread-X"), 0);+ assert_eq!(cancel_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-X"), 0);prune("task-tB");prune("task-headless");@@ -551,7 +551,7 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {let task_id = TaskId::new("task-cbt");shared_steering_registry().register(task_id.clone(), SteeringHandle::allow_all());- let meta = cancel_by_task("task-cbt").expect("known task should cancel");+ let meta = cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "task-cbt").expect("known task should cancel");assert_eq!(meta.already_finished, None,"a running task is a real cancel"@@ -569,9 +569,9 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {steer("task-cbt", "session-Z", "x".into(), QueueLane::Steer).await,Err(SteerError::Unknown));- assert!(cancel_by_task("task-cbt").is_none());+ assert!(cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "task-cbt").is_none());// Unknown ids are simply None.- assert!(cancel_by_task("never-existed").is_none());+ assert!(cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "never-existed").is_none());}/// A finished run stays registered until the terminal sweep, so a late@@ -608,7 +608,7 @@ async fn cancel_by_task_flags_a_run_that_already_finished() {for (task_id, status, finished) in cases {let tx = register_test(task_id, "session-F", run_queue());tx.send(status).expect("status channel open");- let meta = cancel_by_task(task_id).expect("registered task is found");+ let meta = cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), task_id).expect("registered task is found");assert_eq!(meta.already_finished, finished, "{task_id}");}}@@ -668,7 +668,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {let _other =register_test_with_thread("task-stop-other", "session-stop", Some("thread-keep"), rq);- let stopped = stop_for_thread("thread-stop");+ let stopped = stop_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop");assert_eq!(stopped, vec!["task-stop-1".to_string()]);let joined = tokio::time::timeout(Duration::from_secs(2), child)@@ -693,7 +693,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {.is_ok(),"a different thread's sub-agent is untouched");- assert!(stop_for_thread("thread-stop").is_empty(), "idempotent");+ assert!(stop_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop").is_empty(), "idempotent");prune("task-stop-other");}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rsindex bbd6f74985..bbc85a30a0 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rs@@ -66,7 +66,7 @@ async fn roster_status_labels_are_literal() {_ => {}}}- let labels: Vec<(String, &str)> = snapshot_for_parent("wire-parent")+ let labels: Vec<(String, &str)> = snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), "wire-parent").into_iter().map(|s| (s.task_id, s.status)).collect();@@ -127,7 +127,7 @@ async fn durable_fallback_maps_every_store_status_to_literal_wait_outcome() {"wire-d-running","wire-d-pending",] {- let outcome = wait_in_workspace(id, parent, &ws, timeout).await;+ let outcome = wait_in_workspace(&crate::core::runtime::DispatchCtx::ambient(), id, parent, &ws, timeout).await;seen.push(format!("{id}: {outcome:?}"));}assert_eq!(@@ -143,13 +143,13 @@ async fn durable_fallback_maps_every_store_status_to_literal_wait_outcome() {);// A different parent is refused, an unknown id is unknown.assert_eq!(- wait_in_workspace("wire-d-failed", "someone-else", &ws, timeout)+ wait_in_workspace(&crate::core::runtime::DispatchCtx::ambient(), "wire-d-failed", "someone-else", &ws, timeout).await.unwrap_err(),WaitError::NotOwned);assert_eq!(- wait_in_workspace("wire-d-nope", parent, &ws, timeout)+ wait_in_workspace(&crate::core::runtime::DispatchCtx::ambient(), "wire-d-nope", parent, &ws, timeout).await.unwrap_err(),WaitError::Unknowndiff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rsindex c0f3573c5f..be22762e35 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs@@ -76,7 +76,7 @@ async fn late_registration_refusal_aborts_the_worker_and_settles_its_durable_ses// synthetic error or an accepted worker under another actor.let join = tokio::spawn(std::future::pending::<()>());let (_tx, rx) = running_subagents::status_channel();- let refused = running_subagents::register(+ let refused = running_subagents::register(&crate::core::runtime::DispatchCtx::ambient(),"late-refusal-task".into(),"task_manager_agent".into(),"late-parent".into(),diff --git a/crates/openhuman-core/src/agent/session_store/mod_tests.rs b/crates/openhuman-core/src/agent/session_store/mod_tests.rsindex 52a486de65..6a916b8125 100644--- a/crates/openhuman-core/src/agent/session_store/mod_tests.rs+++ b/crates/openhuman-core/src/agent/session_store/mod_tests.rs@@ -68,7 +68,7 @@ async fn transcripts_come_from_the_store_only_when_one_is_in_effect() {async fn without_a_store_transcripts_are_workspace_files() {let dir = std::path::Path::new("/nonexistent-openhuman-workspace");assert_eq!(- transcripts_or_files("u1", dir).destination_key(),+ transcripts_or_files(&crate::core::runtime::DispatchCtx::ambient(), "u1", dir).destination_key(),// tinyagents keys the file destination on the resolved `session_raw`// directory under the workspace (tinyagents#06ad95ea).Some(dir.join("session_raw").to_string_lossy().into_owned())@@ -76,7 +76,7 @@ async fn without_a_store_transcripts_are_workspace_files() {let provider: Arc<dyn SessionStoreProvider> = Arc::new(InMemorySessionStores::new());let expected = provider.for_agent("u1").transcripts.destination_key();let found = scope(provider, async {- transcripts_or_files("u1", dir).destination_key()+ transcripts_or_files(&crate::core::runtime::DispatchCtx::ambient(), "u1", dir).destination_key()}).await;assert_eq!(found, expected);@@ -126,10 +126,10 @@ async fn under<T>(ctx: Arc<crate::core::runtime::CoreContext>, f: impl FnOnce()#[tokio::test]async fn desktop_session_keys_and_transcript_roots_are_unchanged() {let ws = std::path::Path::new("/ws");- assert_eq!(current_agent_key_or("orchestrator"), "orchestrator");- assert_eq!(transcript_root(ws), ws.to_path_buf());+ assert_eq!(current_agent_key_or(&crate::core::runtime::DispatchCtx::ambient(), "orchestrator"), "orchestrator");+ assert_eq!(transcript_root(&crate::core::runtime::DispatchCtx::ambient(), ws), ws.to_path_buf());let (key, root) = under(derived(None, Some("alpha")), || {- (current_agent_key_or("orchestrator"), transcript_root(ws))+ (current_agent_key_or(&crate::core::runtime::DispatchCtx::ambient(), "orchestrator"), transcript_root(&crate::core::runtime::DispatchCtx::ambient(), ws))}).await;assert_eq!(key, "alpha");@@ -140,11 +140,11 @@ async fn desktop_session_keys_and_transcript_roots_are_unchanged() {async fn two_profiles_default_agents_keep_separate_session_keys_and_stores() {let ws = std::path::Path::new("/ws-profile");let (alice_key, alice_root) = under(derived(Some("alice"), None), || {- (current_agent_key_or("orchestrator"), transcript_root(ws))+ (current_agent_key_or(&crate::core::runtime::DispatchCtx::ambient(), "orchestrator"), transcript_root(&crate::core::runtime::DispatchCtx::ambient(), ws))}).await;let bob_key = under(derived(Some("bob"), None), || {- current_agent_key_or("orchestrator")+ current_agent_key_or(&crate::core::runtime::DispatchCtx::ambient(), "orchestrator")}).await;assert_eq!(alice_key, "alice~default");diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rsindex 4213c61da9..d9d7569827 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs@@ -21,7 +21,7 @@ fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call()source: tinyagents_harness::cost::CostSource::Charged,},};- super::transcript::persist_subagent_transcript(+ super::transcript::persist_subagent_transcript(&crate::core::runtime::DispatchCtx::ambient(),workspace.path(),"root__usage","worker",@@ -35,7 +35,7 @@ fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call()"test",2,);- let root = crate::agent::session_store::transcript_root(workspace.path());+ let root = crate::agent::session_store::transcript_root(&crate::core::runtime::DispatchCtx::ambient(), workspace.path());let path = tinyagents_session::transcript::resolve_keyed_transcript_path(&root, "root__usage").unwrap();let transcript = tinyagents_session::transcript::read_transcript(&path).unwrap();diff --git a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rsindex 94b723eeca..70a3197275 100644--- a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs+++ b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs@@ -104,7 +104,7 @@ async fn a_relayed_turn_runs_as_an_external_channel_and_keeps_its_thread() {let _bus = mock_agent_run_turn(move |req: AgentTurnRequest| {let mut seen = stub_seen.lock().unwrap();seen.busy- .push(crate::agent::orchestration::busy_guard::is_busy(+ .push(crate::agent::orchestration::busy_guard::is_busy(&crate::core::runtime::DispatchCtx::ambient(),&relayed_thread,));seen.histories.push(@@ -155,7 +155,7 @@ async fn a_relayed_turn_runs_as_an_external_channel_and_keeps_its_thread() {"a relayed turn marks its thread busy, so a background result waits");assert!(- !crate::agent::orchestration::busy_guard::is_busy(¶ms("m1", "x").thread_id()),+ !crate::agent::orchestration::busy_guard::is_busy(&crate::core::runtime::DispatchCtx::ambient(), ¶ms("m1", "x").thread_id()),"the thread is idle once the turn ends");for origin in &seen.origins {diff --git a/crates/openhuman-core/src/cron/limits_tests.rs b/crates/openhuman-core/src/cron/limits_tests.rsindex 0554ef0668..1847c63418 100644--- a/crates/openhuman-core/src/cron/limits_tests.rs+++ b/crates/openhuman-core/src/cron/limits_tests.rs@@ -163,10 +163,10 @@ async fn run_now_refuses_a_stored_job_that_breaks_the_limits() {let shell =add_shell_job(&config, None, Schedule::Every { every_ms: 600_000 }, "echo").unwrap();config.cron.agent_jobs_only = true;- assert!(crate::cron::ops::run_job_now(&config, &shell.id)+ assert!(crate::cron::ops::run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &shell.id).await.is_err());- assert!(crate::cron::ops::cron_run(&config, &shell.id)+ assert!(crate::cron::ops::cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &shell.id).await.is_err());assert!(crate::cron::list_runs(&config, &shell.id, 10)diff --git a/crates/openhuman-core/src/cron/ops_tests.rs b/crates/openhuman-core/src/cron/ops_tests.rsindex 80a25077ce..723d4ae7b6 100644--- a/crates/openhuman-core/src/cron/ops_tests.rs+++ b/crates/openhuman-core/src/cron/ops_tests.rs@@ -371,7 +371,7 @@ async fn cron_runs_returns_empty_history_for_new_job() {async fn cron_run_rejects_empty_job_id() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- let err = cron_run(&config, "").await.unwrap_err();+ let err = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, "").await.unwrap_err();assert!(err.contains("Missing 'job_id'"));}@@ -379,7 +379,7 @@ async fn cron_run_rejects_empty_job_id() {async fn cron_run_rejects_whitespace_job_id() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- let err = cron_run(&config, " ").await.unwrap_err();+ let err = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, " ").await.unwrap_err();assert!(err.contains("Missing 'job_id'"));}@@ -387,7 +387,7 @@ async fn cron_run_rejects_whitespace_job_id() {async fn cron_run_errors_when_cron_disabled() {let tmp = TempDir::new().unwrap();let config = disabled_cron_config(&tmp);- let err = cron_run(&config, "some-id").await.unwrap_err();+ let err = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, "some-id").await.unwrap_err();assert!(err.contains("cron is disabled"));}@@ -397,7 +397,7 @@ async fn cron_run_returns_queued_immediately_for_valid_job() {let config = test_config(&tmp);let job = make_job(&config, "*/5 * * * *", None, "echo hello");- let out = cron_run(&config, &job.id).await.unwrap();+ let out = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap();assert_eq!(out.value["job_id"], json!(job.id));assert_eq!(out.value["status"], json!("queued"));assert!(out.logs.iter().any(|l| l.contains("enqueued")));@@ -418,7 +418,7 @@ async fn cron_run_response_conforms_to_its_declared_schema() {let config = test_config(&tmp);let job = make_job(&config, "*/5 * * * *", None, "echo hello");- let out = cron_run(&config, &job.id).await.unwrap();+ let out = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap();let result = out.value.as_object().expect("result payload is an object");let schema = cron_schemas("run");@@ -483,7 +483,7 @@ async fn cron_run_rejects_duplicate_concurrent_execution() {// Hold the run claim directly to simulate an in-flight execution without// spawning a real long-running subprocess (deterministic, no timing dependency).let running = try_acquire_run(&job.id).expect("the job is free");- let err = cron_run(&config, &job.id).await.unwrap_err();+ let err = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap_err();drop(running);assert!(@@ -527,7 +527,7 @@ async fn run_job_now_runs_and_records_the_handler_result() {std::sync::Arc::new(|_ctx| Box::pin(async { Err("nope".to_string()) })),);let job = single_flight_system_job(&config, "ops-run-now");- let (success, output) = run_job_now(&config, &job.id).await.unwrap();+ let (success, output) = run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap();assert!(!success);assert!(output.contains("nope"), "{output}");let runs = cron::list_runs(&config, &job.id, 10).unwrap();@@ -548,9 +548,9 @@ async fn run_job_now_refuses_a_job_that_is_already_running() {let config = test_config(&tmp);let job = single_flight_system_job(&config, "ops-run-now-busy");let _running = try_acquire_run(&job.id).expect("the job is free");- let err = run_job_now(&config, &job.id).await.unwrap_err();+ let err = run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap_err();assert!(err.contains("already running"), "{err}");- let err = cron_run(&config, &job.id).await.unwrap_err();+ let err = cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap_err();assert!(err.contains("already running"), "{err}");}@@ -558,5 +558,5 @@ async fn run_job_now_refuses_a_job_that_is_already_running() {async fn run_job_now_reports_an_unknown_job() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- assert!(run_job_now(&config, "no-such-job").await.is_err());+ assert!(run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, "no-such-job").await.is_err());}diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rsindex bc2502f2da..263fbfbdc1 100644--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs@@ -90,7 +90,7 @@ async fn no_reply_is_suppressed_without_writing_anything() {let tmp = tempfile::TempDir::new().unwrap();let cfg = config(&tmp);seed_thread(&cfg, "t-1");- let status = deliver_to_origin(&cfg, &job(Some(web("t-1"))), "run-1", " NO_REPLY ")+ let status = deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &job(Some(web("t-1"))), "run-1", " NO_REPLY ").await.unwrap();assert_eq!(status, DeliveryStatus::Suppressed);@@ -111,7 +111,7 @@ async fn web_delivery_stores_one_row_under_the_run_reply_id_and_is_idempotent()let j = job(Some(web("t-1")));for _ in 0..2 {- let status = deliver_to_origin(&cfg, &j, "run-1", " Drink water! ")+ let status = deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &j, "run-1", " Drink water! ").await.unwrap();assert_eq!(status, DeliveryStatus::Delivered);@@ -130,7 +130,7 @@ async fn web_delivery_stores_one_row_under_the_run_reply_id_and_is_idempotent()assert_eq!(messages[0].content, "Drink water!");assert_eq!(messages[0].sender, "agent");- deliver_to_origin(&cfg, &j, "run-2", "Again!")+ deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &j, "run-2", "Again!").await.unwrap();assert_eq!(@@ -149,7 +149,7 @@ async fn web_delivery_stores_one_row_under_the_run_reply_id_and_is_idempotent()async fn web_delivery_to_a_missing_thread_fails() {let tmp = tempfile::TempDir::new().unwrap();let cfg = config(&tmp);- let err = deliver_to_origin(&cfg, &job(Some(web("gone"))), "run-1", "hi")+ let err = deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &job(Some(web("gone"))), "run-1", "hi").await.unwrap_err();assert!(err.to_string().contains("origin thread"));@@ -159,7 +159,7 @@ async fn web_delivery_to_a_missing_thread_fails() {async fn origin_mode_without_an_origin_is_an_error() {let tmp = tempfile::TempDir::new().unwrap();let cfg = config(&tmp);- assert!(deliver_to_origin(&cfg, &job(None), "run-1", "hi")+ assert!(deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &job(None), "run-1", "hi").await.is_err());}@@ -220,10 +220,10 @@ async fn web_delivery_appends_to_the_resumed_agent_transcript() {agent_id: Some("orchestrator".into()),}));j.id = "job-1".into();- deliver_to_origin(&cfg, &j, "run-1", "Drink water!")+ deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &j, "run-1", "Drink water!").await.unwrap();- deliver_to_origin(&cfg, &j, "run-1", "Drink water!")+ deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(), &cfg, &j, "run-1", "Drink water!").await.unwrap();@@ -249,7 +249,7 @@ async fn transcript_append_waits_for_a_live_turn() {let workspace = cfg.workspace_dir.clone();let task = tokio::spawn(async move {- append_to_origin_transcript(+ append_to_origin_transcript(&crate::core::runtime::DispatchCtx::ambient(),&workspace,&TranscriptAppend {thread_id: "t-1",diff --git a/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rsindex a9f1d975e5..b90bd15cd7 100644--- a/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs@@ -13,7 +13,7 @@ async fn deliver_if_configured_skips_empty_mode() {let config = test_config(&tmp).await;let mut job = test_job("echo ok");job.delivery.mode = "".into();- assert!(deliver_if_configured(&config, &job, "output", true)+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "output", true).await.is_ok());}@@ -29,7 +29,7 @@ async fn deliver_if_configured_announce_missing_channel_errors() {to: Some("target".into()),best_effort: true,};- let result = deliver_if_configured(&config, &job, "out", true).await;+ let result = deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "out", true).await;assert!(result.is_err());}@@ -44,7 +44,7 @@ async fn deliver_if_configured_announce_missing_target_errors() {to: None,best_effort: true,};- let result = deliver_if_configured(&config, &job, "out", true).await;+ let result = deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "out", true).await;assert!(result.is_err());}@@ -59,7 +59,7 @@ async fn deliver_if_configured_proactive_mode_succeeds() {to: None,best_effort: true,};- assert!(deliver_if_configured(&config, &job, "hello", true)+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "hello", true).await.is_ok());}@@ -611,7 +611,7 @@ async fn deliver_if_configured_failure_skips_chat_but_alerts() {let job = proactive_job();// Failed run (non-empty canned error): no chat injection, but still alerts.assert!(- deliver_if_configured(&config, &job, "Something went wrong.", false)+ deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "Something went wrong.", false).await.is_ok());@@ -624,7 +624,7 @@ async fn deliver_if_configured_empty_failure_alerts_with_fallback_body() {let config = test_config(&tmp).await;let job = proactive_job();// Empty failed run: still surfaces in /notifications with a fallback body.- assert!(deliver_if_configured(&config, &job, "", false)+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "", false).await.is_ok());let items =diff --git a/crates/openhuman-core/src/cron/scheduler_frequency_tests.rs b/crates/openhuman-core/src/cron/scheduler_frequency_tests.rsindex 88569bd6a5..6febabc8d9 100644--- a/crates/openhuman-core/src/cron/scheduler_frequency_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_frequency_tests.rs@@ -10,7 +10,7 @@ async fn deliver_if_configured_empty_success_skips_chat_and_alert() {let config = test_config(&tmp).await;let job = proactive_job();// Successful but empty: nothing delivered anywhere.- assert!(deliver_if_configured(&config, &job, "", true).await.is_ok());+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "", true).await.is_ok());assert_eq!(cron_alerts(&config).await, 0);}diff --git a/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs b/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rsindex a54ef2bdfc..f550228750 100644--- a/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs@@ -542,7 +542,7 @@ async fn deliver_if_configured_skips_non_announce_mode() {let job = test_job("echo ok");// Default delivery mode is not "announce", so nothing is published.- assert!(deliver_if_configured(&config, &job, "x", true)+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "x", true).await.is_ok());}@@ -601,7 +601,7 @@ async fn deliver_if_configured_publishes_event_for_announce_mode() {assert_eq!(received.load(Ordering::SeqCst), 1);// Also verify the function itself succeeds.- assert!(deliver_if_configured(&config, &job, "hello", true)+ assert!(deliver_if_configured(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "hello", true).await.is_ok());}diff --git a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rsindex 3cbdd7fe1a..54ee069c29 100644--- a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs+++ b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs@@ -544,7 +544,7 @@ async fn a_noted_cron_completion_names_its_agent() {.session_agent("notif-owner-agent"),);crate::core::runtime::CoreContext::scope(context, async {- crate::cron::completion_owner::note("notif-owner-job");+ crate::cron::completion_owner::note(&crate::core::runtime::DispatchCtx::ambient(), "notif-owner-job");}).await;let event = DomainEvent::CronJobCompleted {diff --git a/crates/openhuman-core/src/profiles/recovery_tests.rs b/crates/openhuman-core/src/profiles/recovery_tests.rsindex 0dac5e49c1..8c9eac4395 100644--- a/crates/openhuman-core/src/profiles/recovery_tests.rs+++ b/crates/openhuman-core/src/profiles/recovery_tests.rs@@ -16,7 +16,7 @@ fn context_with_store() -> (Arc<CoreContext>, Arc<dyn SessionStoreProvider>) {let provider: Arc<dyn SessionStoreProvider> = Arc::new(tinyagents_session::DriverSessionStores::new(backend).unwrap()- .recover_on_open(false),+ .recover_on_open(&crate::core::runtime::DispatchCtx::ambient(), false),);let mut overrides = crate::agent::host_overrides::HostOverrides::default();overrides.session_store = Some(Arc::clone(&provider));diff --git a/crates/openhuman-core/src/threads/ops_conversion_tests.rs b/crates/openhuman-core/src/threads/ops_conversion_tests.rsindex c22943978e..27102f67d1 100644--- a/crates/openhuman-core/src/threads/ops_conversion_tests.rs+++ b/crates/openhuman-core/src/threads/ops_conversion_tests.rs@@ -368,7 +368,7 @@ async fn thread_delete_removes_persisted_turn_state_snapshot() {// Queue a finished background sub-agent result for this thread; deleting the// thread must discard it so it's never delivered into a dead thread.use crate::agent::orchestration::background_completions as bg;- bg::record_completion(+ bg::record_completion(&crate::core::runtime::DispatchCtx::ambient(),&dir,"sess-del","sub-del-1",@@ -430,7 +430,7 @@ async fn threads_purge_removes_every_turn_state_snapshot() {// Queue background sub-agent results across sessions; a full purge must wipe// them all since no parent thread survives.use crate::agent::orchestration::background_completions as bg;- bg::record_completion(+ bg::record_completion(&crate::core::runtime::DispatchCtx::ambient(),&dir,"sess-p1","sub-p1",@@ -439,7 +439,7 @@ async fn threads_purge_removes_every_turn_state_snapshot() {Some("thread-a".into()),).await;- bg::record_completion(+ bg::record_completion(&crate::core::runtime::DispatchCtx::ambient(),&dir,"sess-p2","sub-p2",diff --git a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rsindex 2aa7e41431..2b92993e4c 100644--- a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs@@ -619,7 +619,7 @@ async fn unscoped_cancel_stops_the_threads_detached_subagents() {let workspace = tempfile::tempdir().expect("workspace");let child = tokio::spawn(std::future::pending::<()>());let (_status_tx, status_rx) = running_subagents::status_channel();- running_subagents::register(+ running_subagents::register(&crate::core::runtime::DispatchCtx::ambient(),"task-web-stop-1".into(),"researcher".into(),"session-web-stop".into(),diff --git a/tests/support/cron_policy_failure.rs b/tests/support/cron_policy_failure.rsindex 8a4850ea29..69dc7f1270 100644--- a/tests/support/cron_policy_failure.rs+++ b/tests/support/cron_policy_failure.rs@@ -355,8 +355,8 @@ pub(super) async fn policy_reads_refuse_execution_without_consuming_a_slot(case:let scheduled_calls = calls.load(Ordering::SeqCst);let (manual, queued, tool) = CoreContext::scope(Arc::clone(&alpha), async {assert!(policy::get_policy(&config, &job.id).is_err());- let manual = cron::ops::run_job_now(&config, &job.id).await;- let queued = cron::ops::cron_run(&config, &job.id).await;+ let manual = cron::ops::run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await;+ let queued = cron::ops::cron_run(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await;let tool = cron::tools::CronRunTool::new(Arc::new(config.clone())).execute(json!({"job_id": job.id})).await@@ -424,7 +424,7 @@ pub(super) async fn policy_reads_refuse_execution_without_consuming_a_slot(case:policy::get_policy(&config, &job.id).unwrap(),JobPolicy::default());- assert!(cron::ops::run_job_now(&config, &job.id).await.unwrap().0);+ assert!(cron::ops::run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.unwrap().0);}).await;assert_eq!(@@ -482,7 +482,7 @@ pub(super) async fn malformed_policy_rows_refuse_execution(case: Case) {policy::get_policy(&config, &job.id).is_err(),"a malformed existing row became a usable policy");- let refused = cron::ops::run_job_now(&config, &job.id)+ let refused = cron::ops::run_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job.id).await.expect_err("a malformed policy must refuse Run now");assert!(!refused.contains("private-payload"));