Skip to content

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

fix(memory): close the summarization consent hole; scope detached tasks

Shanu2da786930825
diff --git a/src/openhuman/agent/hooks.rs b/src/openhuman/agent/hooks.rs
index 5a53dcea5a..1ae331b7c8 100644
--- a/src/openhuman/agent/hooks.rs
+++ b/src/openhuman/agent/hooks.rs
@@ -284,9 +284,20 @@ pub fn fire_hooks(hooks: &[Arc<dyn PostTurnHook>], ctx: TurnContext) {
ctx.tool_calls.len(),
ctx.assistant_response.chars().count()
);
+ // Capture the ambient CoreContext before detaching: a bare `tokio::spawn`
+ // does not inherit the `CURRENT_CONTEXT` task-local, so under a scoped
+ // multi-tenant dispatch a detached hook would fall back to the process
+ // default context — and anything context-derived inside the hook (the
+ // archivist's `active_memory_guard`, goals enrichment) would read and
+ // write another tenant's workspace. Re-entering the scope inside the task
+ // keeps the hook on the dispatch it belongs to; when there is no scoped
+ // context (the desktop's single-tenant path), `current()` already answers
+ // the process default and re-scoping it is a no-op.
+ let core_ctx = crate::core::runtime::context::CoreContext::current();
for (idx, hook) in hooks.iter().enumerate() {
let hook = Arc::clone(hook);
let ctx = ctx.clone();
+ let core_ctx = core_ctx.clone();
log::trace!(
"[learning] scheduling hook {}/{}: '{}'",
idx + 1,
@@ -294,22 +305,30 @@ pub fn fire_hooks(hooks: &[Arc<dyn PostTurnHook>], ctx: TurnContext) {
hook.name()
);
tokio::spawn(async move {
- let started = std::time::Instant::now();
- match hook.on_turn_complete(&ctx).await {
- Ok(()) => {
- log::debug!(
- "[learning] hook '{}' completed in {}ms",
- hook.name(),
- started.elapsed().as_millis()
- );
+ let run = async move {
+ let started = std::time::Instant::now();
+ match hook.on_turn_complete(&ctx).await {
+ Ok(()) => {
+ log::debug!(
+ "[learning] hook '{}' completed in {}ms",
+ hook.name(),
+ started.elapsed().as_millis()
+ );
+ }
+ Err(e) => {
+ log::warn!(
+ "[learning] hook '{}' failed after {}ms: {e:#}",
+ hook.name(),
+ started.elapsed().as_millis()
+ );
+ }
}
- Err(e) => {
- log::warn!(
- "[learning] hook '{}' failed after {}ms: {e:#}",
- hook.name(),
- started.elapsed().as_millis()
- );
+ };
+ match core_ctx {
+ Some(scope_ctx) => {
+ crate::core::runtime::context::CoreContext::scope(scope_ctx, run).await
}
+ None => run.await,
}
});
}
diff --git a/src/openhuman/agent/hooks_tests.rs b/src/openhuman/agent/hooks_tests.rs
index 2f45662e2d..b565fcdd6d 100644
--- a/src/openhuman/agent/hooks_tests.rs
+++ b/src/openhuman/agent/hooks_tests.rs
@@ -113,3 +113,71 @@ async fn fire_hooks_accepts_empty_hook_list() {
// Should not panic
fire_hooks(&[], ctx);
}
+
+// ── Detached hooks keep the dispatch's CoreContext ────────────────────────────
+
+/// A detached hook task must observe the same ambient [`CoreContext`] as the
+/// dispatch that fired it. A bare `tokio::spawn` loses the `CURRENT_CONTEXT`
+/// task-local — under a scoped multi-tenant dispatch that meant the hook fell
+/// back to the process default context, and the archivist/goals paths behind
+/// it read and wrote another tenant's workspace. `fire_hooks` now re-enters
+/// the captured scope inside the spawned task; this pins that.
+#[tokio::test]
+async fn fired_hooks_observe_the_firing_dispatchs_core_context() {
+ use crate::core::runtime::context::CoreContext;
+
+ struct ContextProbe {
+ seen: tokio::sync::Mutex<
+ Option<tokio::sync::oneshot::Sender<Option<std::sync::Arc<CoreContext>>>>,
+ >,
+ }
+
+ #[async_trait::async_trait]
+ impl PostTurnHook for ContextProbe {
+ fn name(&self) -> &str {
+ "context-probe"
+ }
+ async fn on_turn_complete(&self, _ctx: &TurnContext) -> anyhow::Result<()> {
+ if let Some(tx) = self.seen.lock().await.take() {
+ let _ = tx.send(CoreContext::current());
+ }
+ Ok(())
+ }
+ }
+
+ let tenant_ctx = CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(std::path::PathBuf::from("/tmp/tenant-a")),
+ None,
+ );
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let probe: std::sync::Arc<dyn PostTurnHook> = std::sync::Arc::new(ContextProbe {
+ seen: tokio::sync::Mutex::new(Some(tx)),
+ });
+ let turn = TurnContext {
+ user_message: String::new(),
+ assistant_response: String::new(),
+ tool_calls: Vec::new(),
+ turn_duration_ms: 0,
+ session_id: None,
+ agent_id: None,
+ entrypoint: None,
+ iteration_count: 0,
+ };
+
+ CoreContext::scope(std::sync::Arc::clone(&tenant_ctx), async {
+ fire_hooks(&[probe], turn);
+ })
+ .await;
+
+ let seen = tokio::time::timeout(std::time::Duration::from_secs(5), rx)
+ .await
+ .expect("hook must run")
+ .expect("probe sender must fire");
+ let seen = seen.expect("the hook must observe SOME ambient context");
+ assert!(
+ std::sync::Arc::ptr_eq(&seen, &tenant_ctx),
+ "the detached hook must observe the dispatch's scoped context, \
+ not the process default"
+ );
+}
diff --git a/src/openhuman/memory/goals/enrich.rs b/src/openhuman/memory/goals/enrich.rs
index f0b4b01b39..b04aa7cee8 100644
--- a/src/openhuman/memory/goals/enrich.rs
+++ b/src/openhuman/memory/goals/enrich.rs
@@ -61,9 +61,10 @@ fn build_prompt(context_input: &str, first_run: bool) -> String {
///
/// Resolved here rather than passed in because of [`spawn_enrich_goals`]: that
/// entry point detaches a `'static` task, which cannot hold a borrowed
-/// `&dyn MemoryGoals` across the spawn. `active_memory_guard` works inside a
-/// spawned task — `CoreContext::current` falls back to the process default
-/// context, which a detached task still sees.
+/// `&dyn MemoryGoals` across the spawn. Inside that task, `CoreContext::current`
+/// answers the scope [`spawn_enrich_goals`] re-enters — the context captured at
+/// the spawn site — so a scoped multi-tenant dispatch resolves its own tenant's
+/// guard rather than the process default it would otherwise fall back to.
///
/// # Errors
///
@@ -151,10 +152,26 @@ pub fn spawn_enrich_goals(
workspace_dir: std::path::PathBuf,
context_input: String,
) {
+ // Capture the ambient CoreContext before detaching: `tokio::spawn` does
+ // not inherit the `CURRENT_CONTEXT` task-local, so under a scoped
+ // multi-tenant dispatch the detached task's `active_memory_guard` (see
+ // [`read_goals`]) would fall back to the process default context and
+ // enrich another tenant's goals document with this tenant's recap.
+ // Re-entering the scope keeps the task on the dispatch that spawned it;
+ // with no scoped context (the desktop path) this is a no-op.
+ let core_ctx = crate::core::runtime::context::CoreContext::current();
tokio::spawn(async move {
- match enrich_goals(&config, &workspace_dir, &context_input).await {
- Ok(_) => log::debug!("[memory_goals] background enrich finished"),
- Err(e) => log::warn!("[memory_goals] background enrich failed: {e}"),
+ let run = async move {
+ match enrich_goals(&config, &workspace_dir, &context_input).await {
+ Ok(_) => log::debug!("[memory_goals] background enrich finished"),
+ Err(e) => log::warn!("[memory_goals] background enrich failed: {e}"),
+ }
+ };
+ match core_ctx {
+ Some(scope_ctx) => {
+ crate::core::runtime::context::CoreContext::scope(scope_ctx, run).await
+ }
+ None => run.await,
}
});
}
diff --git a/src/openhuman/memory/tree/tree_runtime/ops.rs b/src/openhuman/memory/tree/tree_runtime/ops.rs
index 8acc61b37d..08aa2a7c0a 100644
--- a/src/openhuman/memory/tree/tree_runtime/ops.rs
+++ b/src/openhuman/memory/tree/tree_runtime/ops.rs
@@ -295,21 +295,19 @@ pub async fn tree_summarizer_rebuild(
/// The two handlers therefore resolve a provider and drop it, purely for the
/// refusal.
///
-/// **One consequence is not preserved and should be fixed upstream:** with
-/// local AI enabled this returns a local Ollama model, but the driver still
-/// builds the cloud-routed `"summarization"` model, so an explicit run no
-/// longer folds locally. `MemoryTree::seal` has behaved that way since it
-/// landed — this makes `run`/`rebuild` consistent with it rather than
-/// introducing the divergence — and the fix belongs where the fold is: the
-/// driver resolving its summariser through the host's ladder (which
-/// [`summarizer_available`] already crosses the seam to answer) rather than
-/// through role routing alone.
+/// **The fold does consult this ladder — through the seam, not this call.**
+/// The model resolved here is dropped; the one the fold actually runs on is
+/// resolved when the driver's `"summarization"`-role chat call crosses back
+/// into `modules::memory_host::resolve_chat_model`, which routes that role
+/// through this same function. So an explicit run folds locally when local AI
+/// is enabled, the scheduled `seal`/`cascade` passes do too, and the cloud
+/// route stays behind `memory_tree.cloud_summarization_opt_in` everywhere.
+/// The precondition here is still worth its construction cost: it refuses
+/// before any driver work begins, with an error that names the setting.
///
-/// Visibility note: `pub(crate)` is historical. It was widened so an in-process
-/// embedded driver's `seal`/`cascade` could reach the same resolver; there is
-/// no embedded driver (`memory::driver` is a doc-only namespace and
-/// `memory::binding` refuses `DriverClass::Embedded`), so the only callers are
-/// in this module.
+/// Visibility note: `pub(crate)` is load-bearing — `modules::memory_host`'s
+/// chat seam is the second caller, so the module's folds and this handler's
+/// precondition resolve through one ladder that cannot drift apart.
pub(crate) fn create_provider(
config: &Config,
) -> Result<
diff --git a/src/openhuman/modules/memory_host.rs b/src/openhuman/modules/memory_host.rs
index 1500cfba59..0d8c7f3585 100644
--- a/src/openhuman/modules/memory_host.rs
+++ b/src/openhuman/modules/memory_host.rs
@@ -89,16 +89,48 @@ impl ChatCallbacks {
role: String,
request: ModelRequest,
) -> tinybus::Result<ModelResponse> {
- let (model, _) = crate::openhuman::inference::provider::create_chat_model_with_model_id(
- &role,
- &self.0,
- self.0.default_temperature,
- )
- .map_err(method_error)?;
+ let model = resolve_chat_model(&role, &self.0).map_err(method_error)?;
model.invoke(&(), request).await.map_err(method_error)
}
}
+/// Resolve the model a module-side chat call runs on, by role.
+///
+/// The `"summarization"` role is special-cased through the tree summarizer's
+/// provider ladder (`tree_runtime::ops::create_provider`) rather than the
+/// role factory, because every memory fold the module performs — an explicit
+/// `tree_summarizer_run`/`rebuild`, the scheduled `seal`/`cascade` passes, and
+/// the archivist's recap `summarise` — reaches the host through this one seam,
+/// and the ladder is where the host's routing *policy* lives: local Ollama
+/// when `local_ai.runtime_enabled`, the configured cloud provider only under
+/// `memory_tree.cloud_summarization_opt_in`, and a refusal otherwise.
+///
+/// Routing the role factory directly here was a consent hole, not just a
+/// preference miss: with local AI enabled and the cloud opt-in `false`, the
+/// host-side `create_provider` precondition in `tree_runtime::ops` succeeds
+/// (a local model is constructible), and the blind role factory then resolved
+/// `"summarization"` to the configured cloud provider anyway — memory content
+/// leaving the machine against an explicit opt-out. The ladder cannot make
+/// that move: local wins while it is enabled, and cloud requires the opt-in.
+///
+/// Every other role keeps the role factory unchanged.
+fn resolve_chat_model(
+ role: &str,
+ config: &Config,
+) -> anyhow::Result<std::sync::Arc<dyn tinyinference::model::ChatModel<()>>> {
+ if role == "summarization" {
+ let (model, _) = crate::openhuman::memory::tree::tree_runtime::ops::create_provider(config)
+ .map_err(anyhow::Error::msg)?;
+ return Ok(model);
+ }
+ let (model, _) = crate::openhuman::inference::provider::create_chat_model_with_model_id(
+ role,
+ config,
+ config.default_temperature,
+ )?;
+ Ok(model)
+}
+
/// Composio, as the engine's sync pipelines need it.
///
/// # Why the `&Config` argument is not on the wire
diff --git a/src/openhuman/modules/memory_host_tests.rs b/src/openhuman/modules/memory_host_tests.rs
index 7c0fa19219..c01b9abf23 100644
--- a/src/openhuman/modules/memory_host_tests.rs
+++ b/src/openhuman/modules/memory_host_tests.rs
@@ -337,3 +337,59 @@ async fn embed_takes_its_four_arguments_in_the_order_the_module_sends_them() {
"a malformed call must be refused at decode, not inside the host: {error}"
);
}
+
+// ── The summarization role resolves through the consent ladder ───────────────
+
+/// A model the role factory can hand back through the test override, so the
+/// tests below prove the ladder refuses *despite* a resolvable factory.
+struct StubModel;
+
+#[async_trait::async_trait]
+impl tinyinference::model::ChatModel<()> for StubModel {
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: tinyinference::model::ModelRequest,
+ ) -> tinyinference::Result<tinyinference::model::ModelResponse> {
+ Ok(tinyinference::model::ModelResponse::assistant("stub"))
+ }
+}
+
+/// With local AI off and no cloud opt-in, a module-side `"summarization"`
+/// chat call must be refused by the ladder — even while the role factory
+/// demonstrably CAN hand back a model (the override is installed). This is
+/// the consent hole the ladder plugs: before it, the blind role factory
+/// resolved `"summarization"` to the configured cloud provider regardless of
+/// `memory_tree.cloud_summarization_opt_in`.
+#[test]
+fn summarization_role_is_refused_without_local_ai_or_cloud_opt_in() {
+ let _guard =
+ crate::openhuman::inference::provider::factory::test_provider_override::install_model(
+ std::sync::Arc::new(StubModel),
+ );
+ let mut config = Config::default();
+ config.local_ai.runtime_enabled = false;
+ config.memory_tree.cloud_summarization_opt_in = false;
+
+ let error = match super::resolve_chat_model("summarization", &config) {
+ Err(error) => error,
+ Ok(_) => panic!("no local AI and no cloud opt-in must refuse the fold"),
+ };
+ assert!(
+ error.to_string().contains("cloud_summarization_opt_in"),
+ "the refusal must name the setting that unlocks it: {error}"
+ );
+}
+
+/// Any other role keeps the role factory unchanged — the ladder is scoped to
+/// the summarization role, not to the seam.
+#[test]
+fn non_summarization_roles_keep_the_role_factory() {
+ let _guard =
+ crate::openhuman::inference::provider::factory::test_provider_override::install_model(
+ std::sync::Arc::new(StubModel),
+ );
+ let config = Config::default();
+ super::resolve_chat_model("chat", &config)
+ .expect("a non-summarization role resolves through the factory (test override)");
+}
diff --git a/src/openhuman/modules/memory_part_02.rs b/src/openhuman/modules/memory_part_02.rs
index 52179f00e3..273fb55bfe 100644
--- a/src/openhuman/modules/memory_part_02.rs
+++ b/src/openhuman/modules/memory_part_02.rs
@@ -128,7 +128,7 @@ impl MemoryTree for ModuleMemoryProvider {
inputs: &[SummaryInput],
context: &SummaryContext,
) -> Result<SummaryOutput, MemoryError> {
- module_call!(self, "summarise", "Summarise", (inputs, context))
+ module_call!(self, "summarise", methods::SUMMARISE, (inputs, context))
}
/// The wire member is `RootSummaries`; the caps are in the signature on
/// both sides, so the name carries only what distinguishes the call.
@@ -140,7 +140,7 @@ impl MemoryTree for ModuleMemoryProvider {
module_call!(
self,
"root_summaries_with_caps",
- "RootSummaries",
+ methods::ROOT_SUMMARIES,
(per_namespace_cap, total_cap)
)
}
@@ -516,7 +516,7 @@ impl MemoryMaintenance for ModuleMemoryProvider {
/// light polls this, and `Diagnose` runs an aggregate scan of the chunk
/// table.
async fn degraded_state(&self) -> Result<DegradedCapabilities, MemoryError> {
- module_call!(self, "degraded_state", "DegradedState", ())
+ module_call!(self, "degraded_state", methods::DEGRADED_STATE, ())
}
}
diff --git a/src/openhuman/modules/memory_part_03.rs b/src/openhuman/modules/memory_part_03.rs
index e50d075f0b..08af50b0d9 100644
--- a/src/openhuman/modules/memory_part_03.rs
+++ b/src/openhuman/modules/memory_part_03.rs
@@ -199,7 +199,7 @@ impl MemoryChunks for ModuleMemoryProvider {
/// chunk that scored zero, which is why the response is an `Option` rather
/// than a zeroed row.
async fn chunk_score(&self, chunk_id: &str) -> Result<Option<ChunkScore>, MemoryError> {
- module_call!(self, "chunk_score", "ChunkScore", (chunk_id,))
+ module_call!(self, "chunk_score", methods::CHUNK_SCORE, (chunk_id,))
}
/// One row per query, in the order asked. The prefixes are derived from the
/// **host's** source registry — the module has no access to it — so they
@@ -211,7 +211,7 @@ impl MemoryChunks for ModuleMemoryProvider {
module_call!(
self,
"source_ingest_status",
- "SourceIngestStatus",
+ methods::SOURCE_INGEST_STATUS,
(source_prefixes,)
)
}