The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): handle missing runtime snapshot in context preparation
Steven Enamakelb24f398589d7
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rsnew file mode 100644index 0000000000..e2c4f4b678--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs@@ -0,0 +1,215 @@+//! The `agent_prepare_context` [`Tool`] wrapper: schema, permission level,+//! and the parent tool-catalogue / scout-prompt / proposed-goal rendering+//! the scout engine (see [`super::scout_run`]) is built from.++use std::fmt::Write as _;++use crate::agent::harness::fork_context::{current_agent_context_prepared_sources, current_parent};+use crate::tools::traits::{PermissionLevel, Tool, ToolCallOptions, ToolResult};+use async_trait::async_trait;+use serde_json::json;+use tinytools::ToolRunContext;++use super::scout_run::{already_prepared_context_bundle, run_context_scout_with_catalog_and_workspace};++/// Spawns the `context_scout` sub-agent to collect context and propose a plan.+pub struct AgentPrepareContextTool;++impl Default for AgentPrepareContextTool {+ fn default() -> Self {+ Self::new()+ }+}++impl AgentPrepareContextTool {+ pub fn new() -> Self {+ Self+ }++ /// Render the parent agent's tool catalogue into a compact+ /// `- name: description` list the scout can recommend *back* to the+ /// parent. Excludes this tool itself (recommending another scout pass+ /// would be circular). Returns an empty string when there's no parent+ /// context (e.g. a direct CLI/RPC tool call outside an agent turn) — the+ /// subsequent `run_subagent` call surfaces the no-parent error.+ ///+ /// Restricted to the parent's **visible** tool set (what it actually+ /// advertises and will execute this turn), not the full registry —+ /// otherwise the scout could recommend hidden direct-exec/spawn tools+ /// the parent can't call, which the runtime would reject or which would+ /// bypass specialist routing. Read from `visible_tool_specs`, the parent's+ /// own advertised list, because `all_tool_specs` describes what a *child*+ /// may inherit and deliberately carries none of the parent's synthesised+ /// `delegate_*` tools — the very tools the scout most often recommends.+ /// Falls back to that registry, name-filtered, when a context does not+ /// carry the visible list, to preserve behaviour for builders that don't+ /// populate it.+ pub(super) fn render_parent_tool_catalog() -> String {+ let Some(parent) = current_parent() else {+ return String::new();+ };+ let visible = &parent.visible_tool_names;+ let specs: &[std::sync::Arc<crate::tools::ToolSpec>] =+ if parent.visible_tool_specs.is_empty()+ {+ &parent.all_tool_specs+ } else {+ &parent.visible_tool_specs+ };+ let mut out = String::with_capacity(2048);+ for spec in specs.iter() {+ if spec.name == "agent_prepare_context" {+ continue;+ }+ if !visible.is_empty() && !visible.contains(&spec.name) {+ continue;+ }+ // One line per tool; trim the description to keep the catalogue+ // from dwarfing the scout's own prompt.+ let desc: String = spec+ .description+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ let desc = if desc.chars().count() > 160 {+ let cut = desc+ .char_indices()+ .nth(160)+ .map(|(i, _)| i)+ .unwrap_or(desc.len());+ format!("{}…", &desc[..cut])+ } else {+ desc+ };+ let _ = writeln!(out, "- {}: {}", spec.name, desc);+ }+ out+ }++ /// Build the scout's task prompt: the request, optional focus, and the+ /// parent tool catalogue the scout draws its recommendations from.+ pub(super) fn build_scout_prompt(question: &str, focus: Option<&str>, tool_catalog: &str) -> String {+ let mut prompt = String::with_capacity(question.len() + tool_catalog.len() + 512);+ let _ = writeln!(prompt, "[Request]\n{question}\n");+ if let Some(focus) = focus.filter(|f| !f.trim().is_empty()) {+ let _ = writeln!(prompt, "[Focus]\n{}\n", focus.trim());+ }+ if tool_catalog.trim().is_empty() {+ prompt.push_str(+ "[Orchestrator tools]\n(none available — return an empty \+ recommended_tool_calls list)\n",+ );+ } else {+ let _ = writeln!(+ prompt,+ "[Orchestrator tools]\nThese are the tools the orchestrator can call next. \+ Every `recommended_tool_calls[].tool` MUST be one of these exact names:\n{tool_catalog}"+ );+ }+ prompt.push_str(+ "\nGather what you need, then emit the single [context_bundle] … \+ [/context_bundle] block as specified. Do not answer the request yourself.",+ );+ prompt+ }++ /// Extract the scout's `proposed_goal:` line from a `[context_bundle]`, if+ /// present and meaningful. Returns `None` for a missing line or an explicit+ /// `none`. The prefix is matched case-insensitively; its byte length is+ /// fixed (no multibyte), so slicing past it is safe.+ pub(super) fn parse_proposed_goal(bundle: &str) -> Option<String> {+ const PREFIX: &str = "proposed_goal:";+ // Boundary-safe prefix match: `get(..len)` returns None rather than+ // panicking when the line begins with a multibyte char before byte 14.+ let line = bundle.lines().map(str::trim).find(|l| {+ l.get(..PREFIX.len())+ .is_some_and(|p| p.eq_ignore_ascii_case(PREFIX))+ })?;+ let value = line[PREFIX.len()..].trim();+ if value.is_empty() || value.eq_ignore_ascii_case("none") {+ return None;+ }+ Some(value.to_string())+ }+}++#[async_trait]+impl Tool for AgentPrepareContextTool {+ fn name(&self) -> &str {+ "agent_prepare_context"+ }++ fn description(&self) -> &str {+ "Before answering or delegating, scout existing context. Runs a fast \+ read-only context-collector that checks memory, past conversations \+ (transcripts), your goals/profile, installed/registry skills, connected \+ integrations, and the web, then returns whether there's enough context \+ to answer, a compact context summary, an ordered list of recommended \+ next tool calls (parent tools, by exact name, with args), and any \+ skills worth running. Use only when a caller explicitly needs an \+ ad hoc scout pass. If the current prompt says agent context has \+ already been prepared, use the prepared context and do not call this \+ tool again."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "required": ["question"],+ "properties": {+ "question": {+ "type": "string",+ "description": "The user's request or goal to gather context for. Be specific — the scout has no memory of your conversation."+ },+ "focus": {+ "type": "string",+ "description": "Optional hint that narrows what to scout (e.g. a platform, time window, or sub-question)."+ }+ }+ })+ }++ fn permission_level(&self) -> PermissionLevel {+ // ReadOnly, not Execute: this tool only ever runs the read-only+ // `context_scout` (read_only sandbox, no write/exec tools). Marking it+ // Execute would make `ToolPolicyEngine` strip it from any+ // provider-visible set on a `ReadOnly`-capped channel, which would hide+ // the scout from callers that still expose it explicitly.+ PermissionLevel::ReadOnly+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let prepared_sources = current_agent_context_prepared_sources();+ if !prepared_sources.is_empty() {+ tracing::info!(+ target: "agent_prepare_context",+ sources = ?prepared_sources,+ "[agent_prepare_context] skipped because agent context is already prepared for this turn"+ );+ return Ok(ToolResult::success(already_prepared_context_bundle(+ &prepared_sources,+ )));+ }++ let question = args.get("question").and_then(|v| v.as_str()).unwrap_or("");+ let focus = args.get("focus").and_then(|v| v.as_str());+ let tool_catalog = AgentPrepareContextTool::render_parent_tool_catalog();+ run_context_scout_with_catalog_and_workspace(+ question,+ focus,+ &tool_catalog,+ tool_context.and_then(|ctx| ctx.workspace().cloned()),+ )+ .await+ }+}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/runtime_snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/runtime_snapshot.rsnew file mode 100644index 0000000000..4ec507dd4c--- /dev/null+++ b/crates/openhuman-core/src/desktop/app_state/ops/runtime_snapshot.rs@@ -0,0 +1,195 @@+//! Building the `runtime` half of `app_state_snapshot`: local-AI and service+//! status, fanned out concurrently and cached briefly so overlapping polls+//! collapse onto one rebuild instead of each re-running the sub-op fan-out.++use super::types::RuntimeSnapshot;+use super::LOG_PREFIX;+use crate::config::Config;+use crate::platform::service::ServiceState;+use crate::platform::service::ServiceStatus;+use log::{debug, warn};+use once_cell::sync::Lazy;+use parking_lot::Mutex;+use std::path::PathBuf;+use std::time::{Duration, Instant};++/// Runtime-status widgets (local AI / autocomplete / service) tolerate ~10s of+/// staleness. A short TTL (was 2s < the ~2.4s build+/// time) meant the cache was stale before it was even written, so the frontend's+/// ~4s `app_state_snapshot` poll never hit the fast path and every poll re-ran+/// the full 4-way fan-out (issue #4249 profiling: this, combined with the lack+/// of a single-flight gate, pegged ~2 cores and starved the shared tokio runtime+/// the agent harness runs on — the agent's turns stalled 50-100s between model+/// calls even though inference itself was idle).+const RUNTIME_SNAPSHOT_TTL: Duration = Duration::from_secs(10);+pub(super) const RUNTIME_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);+const SNAPSHOT_SUB_OP_TIMEOUT: Duration = Duration::from_secs(5);++#[derive(Debug, Clone)]+struct CachedRuntimeSnapshot {+ snapshot: RuntimeSnapshot,+ fetched_at: Instant,+ /// Config identity (`workspace_dir`) the snapshot was built for. The cache+ /// holds one entry process-wide, so a snapshot built for one config must+ /// never be served to another — otherwise a different user/workspace (or an+ /// E2E test with an injected service mock) reads a stale, foreign runtime.+ config_key: PathBuf,+}++static RUNTIME_SNAPSHOT_CACHE: Lazy<Mutex<Option<CachedRuntimeSnapshot>>> =+ Lazy::new(|| Mutex::new(None));+/// Single-flight gate for the runtime-snapshot rebuild. Concurrent callers whose+/// cache read missed serialize here so only ONE runs the expensive sub-op+/// fan-out; the rest wait, then re-read the cache the winner populated (see the+/// double-check in `build_runtime_snapshot`). This is an async mutex because the+/// guard is held across `.await` points (the sub-op `join`). Without it, every+/// overlapping `app_state_snapshot` poll launched its own build — the rebuild+/// stampede described on `RUNTIME_SNAPSHOT_TTL`.+static RUNTIME_SNAPSHOT_REBUILD: Lazy<tokio::sync::Mutex<()>> =+ Lazy::new(|| tokio::sync::Mutex::new(()));++/// Return the cached runtime snapshot when it is still within+/// `RUNTIME_SNAPSHOT_TTL`, else `None`. Kept as a small helper so both the+/// fast-path read and the post-lock double-check share identical freshness logic.+/// A service-status mock is injected via `OPENHUMAN_SERVICE_MOCK` (test-only env+/// hook that production `service` status already honors). While it is active the+/// runtime snapshot must never be served from — or written to — the process-+/// global cache: the mock's state changes between calls, so caching it would+/// both mask the freshly-injected value and poison later (non-mocked) reads.+fn service_status_mock_active() -> bool {+ std::env::var_os("OPENHUMAN_SERVICE_MOCK").is_some()+}++fn fresh_cached_runtime_snapshot(config: &Config, req_id: u64) -> Option<RuntimeSnapshot> {+ if service_status_mock_active() {+ return None;+ }+ let cache = RUNTIME_SNAPSHOT_CACHE.lock();+ let entry = cache.as_ref()?;+ // A snapshot built for a different config identity is a miss: rebuild against+ // this config rather than serve another workspace's runtime.+ if entry.config_key != config.workspace_dir {+ return None;+ }+ let age = entry.fetched_at.elapsed();+ if age < RUNTIME_SNAPSHOT_TTL {+ debug!(+ "{LOG_PREFIX} build_runtime_snapshot: returning cached snapshot req_id={req_id} age_ms={}",+ age.as_millis()+ );+ Some(entry.snapshot.clone())+ } else {+ None+ }+}++pub(super) async fn build_runtime_snapshot(config: &Config, req_id: u64) -> RuntimeSnapshot {+ // Fast path: a fresh cached snapshot serves every poller without touching the+ // sub-op fan-out.+ if let Some(snapshot) = fresh_cached_runtime_snapshot(config, req_id) {+ return snapshot;+ }++ // Cache miss: single-flight the rebuild so only one caller runs the expensive+ // fan-out. Waiters re-check the cache the winner just populated (this+ // double-check) and return it instead of launching a duplicate build —+ // collapsing an N-way stampede into one build per TTL window.+ let _rebuild_guard = RUNTIME_SNAPSHOT_REBUILD.lock().await;+ if let Some(snapshot) = fresh_cached_runtime_snapshot(config, req_id) {+ debug!(+ "{LOG_PREFIX} build_runtime_snapshot: coalesced onto concurrent rebuild req_id={req_id}"+ );+ return snapshot;+ }++ let config_for_local_ai = config.clone();+ let config_for_service = config.clone();++ let t0 = Instant::now();++ let (local_ai, service) = tokio::join!(+ async {+ let t = Instant::now();+ let status = match tokio::time::timeout(+ SNAPSHOT_SUB_OP_TIMEOUT,+ crate::inference::rpc::inference_status(&config_for_local_ai),+ )+ .await+ {+ Ok(Ok(outcome)) => outcome.value,+ Ok(Err(error)) => {+ warn!("{LOG_PREFIX} local_ai status failed during snapshot: {error}");+ crate::inference::LocalAiStatus::disabled(&config_for_local_ai)+ }+ Err(_) => {+ warn!(+ "{LOG_PREFIX} local_ai timed out after {}s; using degraded sub-snapshot req_id={}",+ SNAPSHOT_SUB_OP_TIMEOUT.as_secs(),+ req_id,+ );+ crate::inference::LocalAiStatus::disabled(&config_for_local_ai)+ }+ };+ (status, t.elapsed().as_millis())+ },+ async {+ let t = Instant::now();+ let status = tokio::task::spawn_blocking(move || {+ crate::platform::service::status(&config_for_service)+ })+ .await+ .unwrap_or_else(|_| Err(anyhow::anyhow!("service status task panicked")));+ let status = match status {+ Ok(s) => s,+ Err(error) => {+ let message = error.to_string();+ warn!("{LOG_PREFIX} service status failed during snapshot: {message}");+ ServiceStatus {+ state: ServiceState::Unknown(message.clone()),+ unit_path: None,+ label: "OpenHuman".to_string(),+ details: Some(message),+ }+ }+ };+ (status, t.elapsed().as_millis())+ }+ );++ let total_ms = t0.elapsed().as_millis();+ debug!(+ "{LOG_PREFIX} build_runtime_snapshot timings req_id={} local_ai_ms={} service_ms={} total_ms={}",+ req_id,+ local_ai.1, service.1,+ total_ms,+ );++ let snapshot = RuntimeSnapshot {+ local_ai: local_ai.0,+ service: service.0,+ };++ // Don't cache a snapshot built under an injected service mock (see+ // `service_status_mock_active`) — it would poison later non-mocked reads.+ if !service_status_mock_active() {+ *RUNTIME_SNAPSHOT_CACHE.lock() = Some(CachedRuntimeSnapshot {+ snapshot: snapshot.clone(),+ fetched_at: Instant::now(),+ config_key: config.workspace_dir.clone(),+ });+ }++ snapshot+}++pub(super) fn degraded_runtime_snapshot(config: &Config) -> RuntimeSnapshot {+ RuntimeSnapshot {+ local_ai: crate::inference::LocalAiStatus::disabled(config),+ service: ServiceStatus {+ state: ServiceState::Unknown("snapshot timed out".to_string()),+ unit_path: None,+ label: "OpenHuman".to_string(),+ details: Some("runtime snapshot timed out".to_string()),+ },+ }+}diff --git a/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rs b/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rsnew file mode 100644index 0000000000..02e5b4bed9--- /dev/null+++ b/crates/openhuman-core/src/memory/guard/families/graph_and_bookkeeping.rs@@ -0,0 +1,621 @@+//! Guarded `Entities`, `Graph`, `Diff`, `Goals`, `ToolMemory`, `Sources`,+//! `Maintenance`, and `People` — the knowledge-graph and bookkeeping+//! families.+//!+//! Split out of `families.rs`; see [`super::types`] for the shared decorator+//! scaffolding these `impl` blocks build on.++use crate::memory::api::capabilities::Capability;+use crate::memory::api::error::MemoryError;+use crate::memory::api::goals::GoalsDoc;+use crate::memory::api::provider::diagnosis::{DegradedCapabilities, Diagnosis};+use crate::memory::api::provider::people::{+ AddressBookSeedOutcome, PersonHandle, PersonInteraction, PersonRecord, PersonScore,+ RankedPerson, ResolvedPerson,+};+use crate::memory::api::provider::types::{+ BackfillTreesOutcome, BackfillTreesRequest, ChunkEntityOccurrence, DiffReport, EntityHit,+ EntityOccurrence, ForgetOutcome, ForgetSelector, MaintenanceReport, PurgeOutcome, SnapshotRef,+ SourceItem,+};+use crate::memory::api::provider::{+ MemoryDiff, MemoryEntities, MemoryGoals, MemoryGraph, MemoryMaintenance, MemoryPeople,+ MemorySourceSink, MemoryToolMemory,+};+use crate::memory::api::tool_memory::ToolMemoryRule;+use crate::memory::api::types::{GraphRelationRecord, MemoryKvRecord};+use async_trait::async_trait;++use super::super::audit::{trace_allowed, NO_NAMESPACE};+use super::types::{+ GuardedDiff, GuardedEntities, GuardedGoals, GuardedGraph, GuardedMaintenance, GuardedPeople,+ GuardedSources, GuardedToolMemory,+};++// ── Entities ─────────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryEntities for GuardedEntities {+ async fn entities(+ &self,+ namespace: &str,+ query: Option<&str>,+ limit: usize,+ ) -> Result<Vec<EntityHit>, MemoryError> {+ self.policy.admit_read(+ Capability::Entities,+ "entities.entities",+ namespace,+ query.is_some(),+ )?;+ let redacted = query.map(|q| self.policy.redact_outbound(q).into_owned());+ self.family()?+ .entities(namespace, redacted.as_deref(), limit)+ .await+ }++ async fn entity_edges(+ &self,+ namespace: &str,+ entity_id: &str,+ limit: usize,+ ) -> Result<Vec<GraphRelationRecord>, MemoryError> {+ self.policy.admit_read(+ Capability::Entities,+ "entities.entity_edges",+ namespace,+ false,+ )?;+ self.family()?+ .entity_edges(namespace, entity_id, limit)+ .await+ }++ async fn touch_entities(+ &self,+ namespace: &str,+ entity_ids: &[String],+ ) -> Result<(), MemoryError> {+ self.policy.admit_write(+ Capability::Entities,+ "entities.touch_entities",+ namespace,+ false,+ )?;+ self.family()?.touch_entities(namespace, entity_ids).await+ }++ /// The occurrence index has no namespace and the contract gives this member+ /// no scope argument, so there is nothing to intersect — the tier check is+ /// the whole gate. Worth stating rather than leaving as an apparent+ /// omission beside the scoped members above.+ async fn top_entities(+ &self,+ kind: Option<&str>,+ limit: usize,+ ) -> Result<Vec<EntityOccurrence>, MemoryError> {+ self.policy.admit_read(+ Capability::Entities,+ "entities.top_entities",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.top_entities(kind, limit).await+ }++ /// Scoped by the chunk ids the caller already holds: it can only name+ /// chunks a previous, scoped read handed it, so this adds no reach beyond+ /// the read that produced them.+ async fn chunk_entities(+ &self,+ chunk_ids: &[String],+ kinds: Option<&[String]>,+ ) -> Result<Vec<ChunkEntityOccurrence>, MemoryError> {+ self.policy.admit_read(+ Capability::Entities,+ "entities.chunk_entities",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.chunk_entities(chunk_ids, kinds).await+ }++ /// Returns ids only, never content. A caller still has to read those chunks+ /// through [`MemoryChunks`] to see anything, and that path applies the+ /// scope intersection.+ async fn entity_chunk_ids(+ &self,+ entity_id: &str,+ limit: usize,+ ) -> Result<Vec<String>, MemoryError> {+ self.policy.admit_read(+ Capability::Entities,+ "entities.entity_chunk_ids",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.entity_chunk_ids(entity_id, limit).await+ }+}++// ── Graph ────────────────────────────────────────────────────────────────────++/// Namespace label for the graph family's `Option<&str>` namespace — `None`+/// addresses the global, namespace-less slice.+fn graph_ns(namespace: Option<&str>) -> &str {+ namespace.unwrap_or(NO_NAMESPACE)+}++#[async_trait]+impl MemoryGraph for GuardedGraph {+ async fn kv_get(+ &self,+ namespace: Option<&str>,+ key: &str,+ ) -> Result<Option<MemoryKvRecord>, MemoryError> {+ self.policy.admit_read(+ Capability::Graph,+ "graph.kv_get",+ graph_ns(namespace),+ false,+ )?;+ self.family()?.kv_get(namespace, key).await+ }++ async fn kv_put(+ &self,+ namespace: Option<&str>,+ key: &str,+ value: serde_json::Value,+ ) -> Result<(), MemoryError> {+ self.policy+ .admit_write(Capability::Graph, "graph.kv_put", graph_ns(namespace), true)?;+ let value = self.policy.redact_outbound_json(value);+ self.family()?.kv_put(namespace, key, value).await+ }++ async fn kv_delete(&self, namespace: Option<&str>, key: &str) -> Result<bool, MemoryError> {+ self.policy.admit_write(+ Capability::Graph,+ "graph.kv_delete",+ graph_ns(namespace),+ false,+ )?;+ self.family()?.kv_delete(namespace, key).await+ }++ async fn kv_list(+ &self,+ namespace: Option<&str>,+ prefix: Option<&str>,+ limit: usize,+ ) -> Result<Vec<MemoryKvRecord>, MemoryError> {+ self.policy.admit_read(+ Capability::Graph,+ "graph.kv_list",+ graph_ns(namespace),+ false,+ )?;+ self.family()?.kv_list(namespace, prefix, limit).await+ }++ async fn relations(+ &self,+ namespace: Option<&str>,+ subject: Option<&str>,+ predicate: Option<&str>,+ limit: usize,+ ) -> Result<Vec<GraphRelationRecord>, MemoryError> {+ self.policy.admit_read(+ Capability::Graph,+ "graph.relations",+ graph_ns(namespace),+ false,+ )?;+ self.family()?+ .relations(namespace, subject, predicate, limit)+ .await+ }++ async fn put_relation(&self, relation: GraphRelationRecord) -> Result<(), MemoryError> {+ self.policy.admit_write(+ Capability::Graph,+ "graph.put_relation",+ graph_ns(relation.namespace.as_deref()),+ true,+ )?;+ self.family()?.put_relation(relation).await+ }+}++// ── Diff ─────────────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryDiff for GuardedDiff {+ async fn capture_snapshot(&self, source_id: &str) -> Result<SnapshotRef, MemoryError> {+ self.policy.admit_write(+ Capability::Diff,+ "diff.capture_snapshot",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.capture_snapshot(source_id).await+ }++ async fn snapshots(+ &self,+ source_id: &str,+ limit: usize,+ ) -> Result<Vec<SnapshotRef>, MemoryError> {+ self.policy+ .admit_read(Capability::Diff, "diff.snapshots", NO_NAMESPACE, false)?;+ self.family()?.snapshots(source_id, limit).await+ }++ async fn diff(+ &self,+ source_id: &str,+ from: Option<&str>,+ to: &str,+ ) -> Result<DiffReport, MemoryError> {+ self.policy+ .admit_read(Capability::Diff, "diff.diff", NO_NAMESPACE, false)?;+ self.family()?.diff(source_id, from, to).await+ }+}++// ── Goals ────────────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryGoals for GuardedGoals {+ async fn goals(&self) -> Result<GoalsDoc, MemoryError> {+ self.policy+ .admit_read(Capability::Goals, "goals.goals", NO_NAMESPACE, false)?;+ self.family()?.goals().await+ }++ async fn set_goals(&self, goals: GoalsDoc) -> Result<(), MemoryError> {+ self.policy+ .admit_write(Capability::Goals, "goals.set_goals", NO_NAMESPACE, true)?;+ // The goals document's own validating mutation surface (the PII and+ // secret predicates) is host policy that already runs in+ // `memory::goals` before a document reaches the contract, so the guard+ // does not re-scrub item text here. If an external driver ever binds,+ // M6 must decide whether that upstream scrub is sufficient for egress+ // or whether item bodies need the same `redact_outbound` treatment the+ // document and ingest paths get.+ self.family()?.set_goals(goals).await+ }+}++// ── Tool memory ──────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryToolMemory for GuardedToolMemory {+ async fn tool_rules(&self, tool_name: &str) -> Result<Vec<ToolMemoryRule>, MemoryError> {+ self.policy.admit_read(+ Capability::ToolMemory,+ "tool_memory.tool_rules",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.tool_rules(tool_name).await+ }++ async fn put_tool_rule(&self, rule: ToolMemoryRule) -> Result<(), MemoryError> {+ self.policy.admit_write(+ Capability::ToolMemory,+ "tool_memory.put_tool_rule",+ NO_NAMESPACE,+ true,+ )?;+ self.family()?.put_tool_rule(rule).await+ }++ async fn delete_tool_rule(&self, tool_name: &str, rule_id: &str) -> Result<bool, MemoryError> {+ self.policy.admit_write(+ Capability::ToolMemory,+ "tool_memory.delete_tool_rule",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.delete_tool_rule(tool_name, rule_id).await+ }+}++// ── Sources ──────────────────────────────────────────────────────────────────++#[async_trait]+impl MemorySourceSink for GuardedSources {+ async fn accept_source_items(+ &self,+ source_id: &str,+ source_kind: &str,+ items: Vec<SourceItem>,+ taint: MemoryTaint,+ ) -> Result<IngestOutcome, MemoryError> {+ self.policy.admit_write(+ Capability::Sources,+ "sources.accept_source_items",+ NO_NAMESPACE,+ true,+ )?;+ // Step 3: the batch taint is the guard's to decide. `stamp_taint` never+ // downgrades, so a sync path that already asked for `ExternalSync` keeps+ // it whether or not a source scope is active.+ let taint = self.policy.stamp_taint(taint);+ let items: Vec<SourceItem> = items+ .into_iter()+ .map(|mut item| {+ item.title = self.policy.redact_outbound(&item.title).into_owned();+ item.content = self.policy.redact_outbound(&item.content).into_owned();+ item+ })+ .collect();+ trace_allowed(+ &self.policy,+ "sources.accept_source_items",+ NO_NAMESPACE,+ items.iter().map(|i| i.content.chars().count()).sum(),+ );+ self.family()?+ .accept_source_items(source_id, source_kind, items, taint)+ .await+ }++ async fn forget_source(&self, source_id: &str) -> Result<u64, MemoryError> {+ self.policy.admit_write(+ Capability::Sources,+ "sources.forget_source",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.forget_source(source_id).await+ }++ /// The one door for every scoped forget, so it takes the same write tier as+ /// [`Self::forget_source`]. The selector names what to remove rather than+ /// carrying content, which is why the egress flag is `false` — the same+ /// reading its single-source sibling makes.+ async fn forget_matching(+ &self,+ selector: &ForgetSelector,+ ) -> Result<ForgetOutcome, MemoryError> {+ self.policy.admit_write(+ Capability::Sources,+ "sources.forget_matching",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.forget_matching(selector).await+ }+}++// ── Maintenance ──────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryMaintenance for GuardedMaintenance {+ async fn reembed(&self) -> Result<MaintenanceReport, MemoryError> {+ self.policy.admit_write(+ Capability::Maintenance,+ "maintenance.reembed",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.reembed().await+ }++ async fn compact(&self) -> Result<MaintenanceReport, MemoryError> {+ self.policy.admit_write(+ Capability::Maintenance,+ "maintenance.compact",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.compact().await+ }++ async fn consolidate(&self) -> Result<MaintenanceReport, MemoryError> {+ self.policy.admit_write(+ Capability::Maintenance,+ "maintenance.consolidate",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.consolidate().await+ }++ /// Tiered by what the call actually does, not by what the member could do.+ ///+ /// Executing writes memory-tree rows for documents already stored, so it+ /// takes the **write** tier like every other mutating maintenance member: a+ /// `readonly` operator may inspect a store, and re-filing thousands of its+ /// documents is not inspection.+ ///+ /// A **dry run writes nothing** — it counts what a pass would examine — so+ /// it takes the **read** tier, the same trade [`Self::doctor`] makes below.+ /// Gating it behind the write tier would withhold the one safe way to size+ /// the job from precisely the tier that should be sizing rather than+ /// executing, and the preview is what the expensive control exists to be+ /// asked for first (review finding).+ async fn backfill_connector_trees(+ &self,+ request: BackfillTreesRequest,+ ) -> Result<BackfillTreesOutcome, MemoryError> {+ if request.dry_run {+ self.policy.admit_read(+ Capability::Maintenance,+ "maintenance.backfill_connector_trees",+ NO_NAMESPACE,+ false,+ )?;+ } else {+ self.policy.admit_write(+ Capability::Maintenance,+ "maintenance.backfill_connector_trees",+ NO_NAMESPACE,+ false,+ )?;+ }+ self.family()?.backfill_connector_trees(request).await+ }++ /// Read-only by contract, so this takes the **read** tier check: a+ /// `readonly` operator must still be able to run `doctor`, which is exactly+ /// the tier where diagnosing without mutating matters most.+ async fn doctor(&self) -> Result<MaintenanceReport, MemoryError> {+ self.policy.admit_read(+ Capability::Maintenance,+ "maintenance.doctor",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.doctor().await+ }++ /// Empties the whole store, so it takes the write tier rather than+ /// `doctor`'s read one — and deliberately carries no scope, because there+ /// is no scoped reading of "purge everything". A source-restricted caller+ /// that reached this would be destroying rows it is not even allowed to+ /// read; the write tier is what stops it.+ async fn purge_all(&self) -> Result<PurgeOutcome, MemoryError> {+ self.policy.admit_write(+ Capability::Maintenance,+ "maintenance.purge_all",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.purge_all().await+ }++ /// [`Self::doctor`]'s findings in full, and read-only on the same terms —+ /// it inspects configuration, persisted state and counters and mutates+ /// nothing, so it takes the read tier for the reason `doctor` gives.+ ///+ /// Forwarded here rather than left to the trait's default: a defaulted+ /// method on a decorator answers `Unsupported` even when the driver below+ /// serves it, so the default would refuse every diagnosis reached through+ /// the guard.+ async fn diagnose(&self) -> Result<Diagnosis, MemoryError> {+ self.policy.admit_read(+ Capability::Maintenance,+ "maintenance.diagnose",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.diagnose().await+ }++ /// The degradation flags without the diagnosis around them — three+ /// booleans and at most one cause. Read tier for the same reason+ /// [`Self::doctor`] takes it, and for one more: this is what a status+ /// light polls, so refusing it under `readonly` would leave the surface+ /// that reports a reduced pipeline unable to say so.+ async fn degraded_state(&self) -> Result<DegradedCapabilities, MemoryError> {+ self.policy.admit_read(+ Capability::Maintenance,+ "maintenance.degraded_state",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.degraded_state().await+ }+}++// ── People ───────────────────────────────────────────────────────────────────++#[async_trait]+impl MemoryPeople for GuardedPeople {+ async fn list_people(&self, limit: Option<usize>) -> Result<Vec<RankedPerson>, MemoryError> {+ self.policy.admit_read(+ Capability::People,+ "people.list_people",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.list_people(limit).await+ }++ async fn get_person(&self, person_id: &str) -> Result<Option<PersonRecord>, MemoryError> {+ self.policy+ .admit_read(Capability::People, "people.get_person", NO_NAMESPACE, false)?;+ self.family()?.get_person(person_id).await+ }++ /// A read *unless* it may mint a person, which is a write.+ ///+ /// The tier check follows what the call can actually do rather than what it+ /// is named: with `create_if_missing` set this inserts a row, so a+ /// `readonly` operator must be refused. Classifying the whole method as a+ /// read would have handed `readonly` a working insert through the back+ /// door.+ async fn resolve_handle(+ &self,+ handle: &PersonHandle,+ create_if_missing: bool,+ ) -> Result<Option<ResolvedPerson>, MemoryError> {+ if create_if_missing {+ self.policy.admit_write(+ Capability::People,+ "people.resolve_handle",+ NO_NAMESPACE,+ true,+ )?;+ } else {+ self.policy.admit_read(+ Capability::People,+ "people.resolve_handle",+ NO_NAMESPACE,+ false,+ )?;+ }+ self.family()?+ .resolve_handle(handle, create_if_missing)+ .await+ }++ async fn add_handle_alias(+ &self,+ person_id: &str,+ handle: &PersonHandle,+ ) -> Result<(), MemoryError> {+ self.policy.admit_write(+ Capability::People,+ "people.add_handle_alias",+ NO_NAMESPACE,+ true,+ )?;+ self.family()?.add_handle_alias(person_id, handle).await+ }++ async fn score_person(&self, person_id: &str) -> Result<Option<PersonScore>, MemoryError> {+ self.policy.admit_read(+ Capability::People,+ "people.score_person",+ NO_NAMESPACE,+ false,+ )?;+ self.family()?.score_person(person_id).await+ }++ async fn record_interaction(&self, interaction: &PersonInteraction) -> Result<(), MemoryError> {+ self.policy.admit_write(+ Capability::People,+ "people.record_interaction",+ NO_NAMESPACE,+ true,+ )?;+ self.family()?.record_interaction(interaction).await+ }++ /// A write: it reads the platform address book and inserts what it finds.+ async fn seed_from_address_book(&self) -> Result<AddressBookSeedOutcome, MemoryError> {+ self.policy.admit_write(+ Capability::People,+ "people.seed_from_address_book",+ NO_NAMESPACE,+ true,+ )?;+ self.family()?.seed_from_address_book().await+ }+}diff --git a/crates/openhuman-core/src/tools/schemas/composio.rs b/crates/openhuman-core/src/tools/schemas/composio.rsnew file mode 100644index 0000000000..98a90d043a--- /dev/null+++ b/crates/openhuman-core/src/tools/schemas/composio.rs@@ -0,0 +1,76 @@+//! Handler for the `tools_composio_execute` controller schema.++use serde_json::{json, Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;+use crate::rpc::RpcOutcome;++fn handle_composio_execute(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let action = params+ .get("action")+ .and_then(Value::as_str)+ .map(str::to_string)+ .ok_or_else(|| "missing required `action`".to_string())?;+ let action_args = params.get("params").cloned();++ let config = config_rpc::load_config_with_timeout().await?;+ // Route through the mode-aware factory so direct-mode users+ // hit their personal Composio tenant when the Tauri shell+ // calls `tools.composio_execute` (e.g. onboarding-driven+ // flows). Pre-fix, the controller hard-bound to the+ // backend-only `build_composio_client` and silently 4xx'd for+ // direct-mode users (#1710). Mirrors+ // `composio::ops::composio_execute`.+ use crate::integrations::composio::client::{+ create_composio_client, direct_execute, ComposioClientKind,+ };+ let kind =+ create_composio_client(&config).map_err(|e| format!("tools.composio_execute: {e}"))?;+ tracing::debug!(+ action = %action,+ mode = %config.composio.mode,+ "[tools][composio_execute] executing action"+ );+ let resp = match kind {+ ComposioClientKind::Backend(client) => {+ tracing::debug!(action = %action, "[tools][composio_execute] branch=backend");+ client+ .execute_tool(&action, action_args)+ .await+ .map_err(|e| format!("composio execute_tool (backend) failed: {e:#}"))?+ }+ ComposioClientKind::Direct(direct) => {+ tracing::debug!(action = %action, "[tools][composio_execute] branch=direct");+ direct_execute(+ &direct,+ &action,+ action_args,+ &config.composio.entity_id,+ None,+ )+ .await+ .map_err(|e| format!("composio execute_tool (direct) failed: {e:#}"))?+ }+ };+ tracing::debug!(+ action = %action,+ successful = resp.successful,+ "[tools][composio_execute] complete"+ );++ let payload = json!({+ "successful": resp.successful,+ "data": resp.data,+ "error": resp.error,+ "cost_usd": resp.cost_usd,+ "markdown_formatted": resp.markdown_formatted,+ });+ let log = vec![format!(+ "tools.composio_execute: action={action} successful={}",+ resp.successful+ )];+ RpcOutcome::new(payload, log).into_cli_compatible_json()+ })+}