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(scope): correct memory scope resolution for nested contexts
Steven Enamakel35cd832fa592
diff --git a/crates/openhuman-core/src/memory/scope.rs b/crates/openhuman-core/src/memory/scope.rsindex f96eca72db..c57d1ac871 100644--- a/crates/openhuman-core/src/memory/scope.rs+++ b/crates/openhuman-core/src/memory/scope.rs@@ -8,13 +8,15 @@//! (`team:<id>/agent:<id>`). Inside each node, learnings, documents and//! conversations are kept as separate scopes by the engine.//!-//! A [`MemoryIdentity`] is the acting agent and its node. The host scopes one-//! around every agent turn ([`within`]): the session host for top-level-//! turns, the sub-agent runner for children ([`MemoryIdentity::child`]), the-//! team runtime for members. Memory then reads it ([`current`]) to stamp what-//! an agent learns and to confine what it recalls to its [`Reach`]: its own-//! node and, unless `[memory.agents.<id>] inherit = false`, the nodes above-//! it. A sibling agent's memory is never in reach.+//! A [`MemoryIdentity`] is the acting agent, the agents that spawned it and+//! its team. The host scopes one around every agent turn ([`within_agent`]):+//! the session host and channel dispatch for top-level turns, the sub-agent+//! runner for children (nested automatically), the team runtime for members.+//! Memory then reads it ([`current`]) and resolves it against its config+//! ([`MemoryIdentity::namespace`]) to stamp what an agent learns and to+//! confine what it recalls to its [`Reach`]: its own node and, unless+//! `[memory.agents.<id>] inherit = false`, the nodes above it. A sibling+//! agent's memory is never in reach.//!//! The identity is never taken from model arguments.@@ -28,122 +30,125 @@ tokio::task_local! {static CURRENT: MemoryIdentity;}-/// The agent acting on memory and the node it owns.-#[derive(Debug, Clone, PartialEq, Eq)]+/// Who is acting on memory: the agent, the agents that spawned it, and its+/// team. Scoping one needs no config; the node it maps to is resolved+/// against the config of whoever reads or writes ([`Self::namespace`]).+#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct MemoryIdentity {/// The agent definition id; `None` outside any agent (RPC, sync jobs).pub agent_id: Option<String>,- /// The node the agent writes to.- pub namespace: Namespace,- /// Whether the agent also reads the nodes above its own.- pub inherit: bool,+ /// The agents that spawned this one, outermost first.+ pub lineage: Vec<String>,+ /// The team the agent works in.+ pub team: Option<String>,}impl MemoryIdentity {/// The root identity: no agent, the shared node.#[must_use]pub fn root() -> Self {- Self {- agent_id: None,- namespace: Namespace::ROOT,- inherit: true,- }+ Self::default()}- /// The identity of a top-level agent run as `agent_id`, resolved from- /// `config` ([`namespace_for`]).+ /// A top-level agent.#[must_use]- pub fn for_agent(config: &Config, agent_id: &str) -> Self {- let settings = config.memory.agents.get(agent_id);+ pub fn agent(agent_id: &str) -> Self {Self {agent_id: Some(agent_id.to_string()).filter(|id| !id.trim().is_empty()),- namespace: namespace_for(config, agent_id, None),- inherit: settings.is_none_or(|settings| settings.inherit),+ ..Self::default()}}- /// The identity of `agent_id` run by this agent: a sub-agent, nested- /// under this agent's node. An agent the config pins to a node keeps it,- /// and a root agent spawned anywhere stays at the root.+ /// `agent_id` as a member of `team`.#[must_use]- pub fn child(&self, config: &Config, agent_id: &str) -> Self {- let settings = config.memory.agents.get(agent_id);- let pinned = settings.and_then(|settings| parse_namespace(settings.namespace.as_deref()));- let namespace = match pinned {- Some(pinned) => pinned,- None if is_root_agent(config, agent_id) => self.namespace.clone(),- None => nest(&self.namespace, SegmentKind::Agent, agent_id),- };+ pub fn team_member(team: &str, agent_id: &str) -> Self {Self {- agent_id: Some(agent_id.to_string()).filter(|id| !id.trim().is_empty()),- namespace,- inherit: settings.is_none_or(|settings| settings.inherit),+ team: Some(team.to_string()).filter(|team| !team.trim().is_empty()),+ ..Self::agent(agent_id)}}- /// The identity of `agent_id` as a member of `team`: its node under the- /// team's (`team:<team>/agent:<id>`), so members share the team node.+ /// `agent_id` run by this agent: a sub-agent, nested under this agent.#[must_use]- pub fn team_member(config: &Config, team: &str, agent_id: &str) -> Self {- let settings = config.memory.agents.get(agent_id);+ pub fn child(&self, agent_id: &str) -> Self {+ let mut lineage = self.lineage.clone();+ lineage.extend(self.agent_id.clone());Self {agent_id: Some(agent_id.to_string()).filter(|id| !id.trim().is_empty()),- namespace: namespace_for(config, agent_id, Some(team)),- inherit: settings.is_none_or(|settings| settings.inherit),+ lineage,+ team: self.team.clone(),}}- /// What this agent reads: its node, and its ancestors when it inherits.+ /// The node this agent writes to under `config`. Walking from the team's+ /// node (or the root) down the lineage to the agent: an agent the config+ /// pins (`[memory.agents.<id>] namespace`) moves to its pinned node, a+ /// root agent stays where it is, and any other agent nests one level+ /// (`agent:<id>`).#[must_use]- pub fn reach(&self) -> Reach {- if self.inherit {- Reach::of(self.namespace.clone())- } else {- Reach::exact(self.namespace.clone())+ pub fn namespace(&self, config: &Config) -> Namespace {+ let mut node = self.team.as_deref().map_or(Namespace::ROOT, |team| {+ nest(&Namespace::ROOT, SegmentKind::Team, team)+ });+ for agent in self.lineage.iter().chain(self.agent_id.iter()) {+ node = step(config, &node, agent);}+ node}- /// Where this agent's shared learnings go: the nearest node above it- /// that is not an agent's (its team's, else the root).+ /// Whether this agent also reads the nodes above its own+ /// (`[memory.agents.<id>] inherit`, on by default).#[must_use]- pub fn shared_namespace(&self) -> Namespace {- self.namespace.shared_ancestor()+ pub fn inherit(&self, config: &Config) -> bool {+ self.agent_id+ .as_deref()+ .and_then(|id| config.memory.agents.get(id))+ .is_none_or(|settings| settings.inherit)+ }++ /// What this agent reads: its node, and its ancestors when it inherits.+ #[must_use]+ pub fn reach(&self, config: &Config) -> Reach {+ let node = self.namespace(config);+ if self.inherit(config) {+ Reach::of(node)+ } else {+ Reach::exact(node)+ }}}-/// The node `agent_id` owns, optionally as a member of `team`:-///-/// - `[memory.agents.<id>] namespace`, when set and valid;-/// - the team's node (or the root) for a root agent (`[memory]-/// root_agents`, the main chat agent by default);-/// - `team:<team>/agent:<id>`, or `agent:<id>` outside a team.-#[must_use]-pub fn namespace_for(config: &Config, agent_id: &str, team: Option<&str>) -> Namespace {+/// One step down from `node` for `agent_id`.+fn step(config: &Config, node: &Namespace, agent_id: &str) -> Namespace {let pinned = config.memory.agents.get(agent_id).and_then(|settings| parse_namespace(settings.namespace.as_deref()));- if let Some(pinned) = pinned {- return pinned;+ match pinned {+ Some(pinned) => pinned,+ None if agent_id.trim().is_empty() || is_root_agent(config, agent_id) => node.clone(),+ None => nest(node, SegmentKind::Agent, agent_id),}- let base = team.map_or(Namespace::ROOT, |team| {- nest(&Namespace::ROOT, SegmentKind::Team, team)- });- if agent_id.trim().is_empty() || is_root_agent(config, agent_id) {- return base;+}++/// The node `agent_id` owns at the top level, optionally as a member of+/// `team`: its pinned `[memory.agents.<id>] namespace`, the team's node (or+/// the root) for a root agent (`[memory] root_agents`, the main chat agent+/// by default), else `team:<team>/agent:<id>` or `agent:<id>`.+#[must_use]+pub fn namespace_for(config: &Config, agent_id: &str, team: Option<&str>) -> Namespace {+ match team {+ Some(team) => MemoryIdentity::team_member(team, agent_id),+ None => MemoryIdentity::agent(agent_id),}- nest(&base, SegmentKind::Agent, agent_id)+ .namespace(config)}/// Whether `agent_id` reads and writes the root node.#[must_use]pub fn is_root_agent(config: &Config, agent_id: &str) -> bool {- config- .memory- .root_agents- .iter()- .any(|root| root == agent_id)+ config.memory.root_agents.iter().any(|root| root == agent_id)}/// `namespace` with a sanitized `kind:id` segment appended; past the depth@@ -171,7 +176,8 @@ fn parse_namespace(raw: Option<&str>) -> Option<Namespace> {pub async fn within<F: Future>(identity: MemoryIdentity, fut: F) -> F::Output {tracing::debug!(agent_id = identity.agent_id.as_deref().unwrap_or("-"),- namespace = %identity.namespace,+ depth = identity.lineage.len(),+ team = identity.team.as_deref().unwrap_or("-"),"[memory:scope] acting as");CURRENT.scope(identity, fut).await@@ -183,31 +189,18 @@ pub fn current() -> Option<MemoryIdentity> {CURRENT.try_with(Clone::clone).ok()}-/// Runs a top-level turn of `agent_id`: as a sub-agent of the identity-/// already in scope when another agent is running, otherwise as the agent-/// itself. A turn of the agent already in scope keeps its identity.-pub async fn within_agent<F: Future>(config: &Config, agent_id: &str, fut: F) -> F::Output {+/// Runs a turn of `agent_id`: as a sub-agent of the identity already in+/// scope when another agent is running, otherwise as the agent itself. A+/// turn of the agent already in scope keeps its identity.+pub async fn within_agent<F: Future>(agent_id: &str, fut: F) -> F::Output {let identity = match current() {Some(outer) if outer.agent_id.as_deref() == Some(agent_id) => outer,- Some(outer) => outer.child(config, agent_id),- None => MemoryIdentity::for_agent(config, agent_id),+ Some(outer) => outer.child(agent_id),+ None => MemoryIdentity::agent(agent_id),};within(identity, fut).await}-/// [`within_agent`] with the host's config when it has one, else the-/// defaults (the main agent at the root, every other agent on its own node).-pub async fn within_agent_in<F: Future>(- config: Option<&Config>,- agent_id: &str,- fut: F,-) -> F::Output {- match config {- Some(config) => within_agent(config, agent_id, fut).await,- None => within_agent(&Config::default(), agent_id, fut).await,- }-}-#[cfg(test)]#[path = "scope_tests.rs"]mod tests;