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
chore: remove profile-partitioning feature from agent experience memory
Steven Enamakel71ee9bcbba7a
diff --git a/crates/openhuman-core/src/agent/experience/README.md b/crates/openhuman-core/src/agent/experience/README.mdindex b3fe2f3aa0..60a63ff0e7 100644--- a/crates/openhuman-core/src/agent/experience/README.md+++ b/crates/openhuman-core/src/agent/experience/README.md@@ -4,9 +4,7 @@ Hermes-style **procedural experience memory** for agents. Captures what tool seq## Responsibilities-- Define the `AgentExperience` record (task summary, tool sequence, outcome, lesson, reuse/avoid hints, confidence, tags, optional owning `profile_id`).- Persist experiences (upsert by stable id) into the memory store under the `agent_experience` namespace, scrubbing free-text fields first.-- Retrieve and rank experiences for a given task query via lexical/tool/tag overlap scoring, partitioned by agent profile.- Mark experiences as dismissed so retrieval skips them.- Auto-derive experience candidates from a completed turn's tool calls (multi-tool success, repeated failures, partial recovery) via a `PostTurnHook`.- Render ranked hits into a byte-capped markdown block and prepend it to the enriched user message before a turn.@@ -18,9 +16,6 @@ Hermes-style **procedural experience memory** for agents. Captures what tool seq| File | Role || --- | --- || `crates/openhuman-core/src/agent/experience/mod.rs` | Export-focused module root; re-exports the public surface. |-| `crates/openhuman-core/src/agent/experience/types.rs` | Serde types (`AgentExperience`, `ExperienceHit`, `ExperienceSource`, `ExperienceOutcome`), `redact_text` (Bearer / `sk-` / `token=secret` masking), `stable_experience_id` (SHA-256 over summary + tool sequence + outcome) and `stable_experience_id_for_profile` (same digest with a domain-separated profile segment appended when a profile is set). |-| `crates/openhuman-core/src/agent/experience/store.rs` | `AgentExperienceStore` over `Arc<dyn Memory>`: `put`/`list`/`list_for_profile`/`dismiss`/`dismiss_for_profile`/`retrieve`, `ExperienceQuery`, `retrieve_across_stores` (merge + dedupe over several physical stores), `experience_matches_profile`, the `AGENT_EXPERIENCE_NAMESPACE` const, base64 payload encode/decode, and the lexical/tool/tag overlap scoring (`score_experience`). |-| `crates/openhuman-core/src/agent/experience/capture.rs` | `AgentExperienceCaptureHook` — a `PostTurnHook` that mines `TurnContext.tool_calls` into experience candidates (`successful_multi_tool_experience`, `repeated_failure_experiences`, `partial_success_experience`), stamps the active profile, and persists them. || `crates/openhuman-core/src/agent/experience/prompt.rs` | `render_experience_hits` (byte-capped markdown under `AGENT_EXPERIENCE_HEADING = "## Relevant Operating Experience"`) and `prepend_experience_block`. || `crates/openhuman-core/src/agent/experience/schemas.rs` | Controller schemas + `handle_*` dispatchers; `all_controller_schemas` / `all_registered_controllers`. |@@ -42,16 +37,10 @@ Namespace `agent_experience` (registered into `crates/openhuman-core/src/core/al| Method | Inputs | Output || --- | --- | --- |-| `agent_experience.capture` | `experience: AgentExperience` | Stored `AgentExperience` (upserted, redacted). Written to the memory subtree of `experience.profile_id` (shared `memory` when unset). |-| `agent_experience.retrieve` | `query` (req), `tools[]`, `tags[]`, `agent_id?`, `entrypoint?`, `profile_id?`, `max_hits?` (default 5) | `hits: ExperienceHit[]` ranked, merged across the shared store and the queried profile store(s). |-| `agent_experience.list` | `profile_id?` | `experiences: AgentExperience[]` ordered by most-recent update, deduped by id across stores. |-| `agent_experience.dismiss` | `id`, `profile_id?` | `{ id, dismissed }`. |-Profile semantics (shared by list and retrieve): `profile_id` omitted sees every record; `profile_id = P` sees records stamped `P` plus unstamped legacy records, never a sibling profile's. All handlers delegate to `ops.rs` and wrap results in `RpcOutcome::single_log`.## Agent hooks (not a tool)-This module owns no `tools.rs` agent tool. Instead it registers `AgentExperienceCaptureHook` as a **`PostTurnHook`** (`name() == "agent_experience_capture"`). On `on_turn_complete` it extracts candidates from the turn's tool calls, stamps each with the session's `profile_id`, re-derives the id with `stable_experience_id_for_profile`, and persists them. Candidate heuristics:- **Multi-tool success**: ≥2 successful tool calls → `ExperienceOutcome::Success`, confidence 0.72.- **Repeated failure**: a tool that failed ≥2 times in one turn → `Failure`, confidence 0.68, with an error class parsed from the output summary (`...(error_class)`).@@ -66,11 +55,7 @@ None — no `bus.rs`; this module does not publish or subscribe to `DomainEvent`Records are stored through the `Memory` trait (no dedicated DB), served by `DriverMemory` over the memory driver bound for the workspace subtree:- Namespace: `agent_experience` (`AGENT_EXPERIENCE_NAMESPACE`).-- Key: `experience/<id>`; id is `stable_experience_id_for_profile(...)` (`exp_<24 hex>`) when not supplied. `profile_id == None` reproduces the legacy digest byte-for-byte.- Value: **base64 of the `AgentExperience` JSON**, `MemoryCategory::Custom("agent_experience")`. Base64 keeps the memory layer's bare-numeric PII scrubber from rewriting a Luhn-valid millisecond timestamp and corrupting the JSON (#5209); reads fall back to plain JSON for legacy rows.-- `put` requires non-empty `task_summary` and `lesson`, preserves the original `created_at_ms` on update, stamps `updated_at_ms`, and runs `memory::safety::sanitize_text` over every free-text field (`task_fingerprint`, `task_summary`, `lesson`, `reuse_hint`, `avoid_hint`, `error_class`, `agent_id`, `entrypoint`, `tools_used`, `tool_sequence`, `tags`) before write. `id` and `profile_id` are keys and left intact.-- Dismiss is a soft flag (`dismissed = true`), retained in `list`, filtered out of `retrieve`. `dismiss_for_profile` refuses to flag a record owned by a different profile.-- Each memory subtree (`memory` for the shared tree, `memory<suffix>` such as `memory-1` for a profile with dedicated memory) is its own binding and therefore its own store.## Dependencies@@ -84,7 +69,6 @@ Records are stored through the `Memory` trait (no dedicated DB), served by `Driv- `crates/openhuman-core/src/core/all.rs` — registers controllers/schemas and the namespace description.- `crates/openhuman-core/src/agent/mod.rs` — declares `pub mod experience`.-- `crates/openhuman-core/src/agent/harness/session/builder/factory.rs` — binds the session's `Arc<dyn Memory>` with `DriverMemory::for_subtree`, resolves `shared_experience_memory` with `DriverMemory::for_config` for dedicated-memory profiles, and registers `AgentExperienceCaptureHook::with_profile(...)` when `config.learning.enabled && config.learning.tool_memory_capture_enabled`.- `crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs` — defines `Agent::inject_agent_experience_context`, which queries the session store plus the shared store with `retrieve_across_stores` (max 3 hits, 2048-byte block, gated on `learning_enabled`) and prepends the block to the enriched user message. Called from `turn/core_turn.rs`.- `crates/openhuman-core/src/agent/tinyagents/host/experience_store.rs` — host adapter implementing `tinyagents_harness::host::ExperienceStore` over `AgentExperienceStore`.- `crates/openhuman-core/src/config/migration_helpers/core.rs` — uses `DriverMemory::for_config` to bind the import target.diff --git a/crates/openhuman-core/src/agent/experience/capture.rs b/crates/openhuman-core/src/agent/experience/capture.rsindex 4280a70ab5..60a715060c 100644--- a/crates/openhuman-core/src/agent/experience/capture.rs+++ b/crates/openhuman-core/src/agent/experience/capture.rs@@ -4,7 +4,7 @@ use std::sync::Arc;use crate::agent::experience::store::AgentExperienceStore;use crate::agent::experience::types::{- redact_text, stable_experience_id, stable_experience_id_for_profile, AgentExperience,+ redact_text, stable_experience_id, AgentExperience,ExperienceOutcome, ExperienceSource,};use crate::agent::hooks::{PostTurnHook, ToolCallRecord, TurnContext};@@ -15,28 +15,13 @@ const MAX_SUMMARY_CHARS: usize = 280;pub struct AgentExperienceCaptureHook {store: AgentExperienceStore,enabled: bool,- /// Profile the session runs under (1c). Stamped onto every captured record- /// so retrieval can partition by profile. `None` for the profile-less- /// session — those records stay unstamped (shared/legacy).- profile_id: Option<String>,}impl AgentExperienceCaptureHook {pub fn new(memory: Arc<dyn Memory>, enabled: bool) -> Self {- Self::with_profile(memory, enabled, None)- }-- /// [`Self::new`] carrying the active profile id (1c). The session builder- /// passes the resolved profile so captured records are stamped with it.- pub fn with_profile(- memory: Arc<dyn Memory>,- enabled: bool,- profile_id: Option<String>,- ) -> Self {Self {store: AgentExperienceStore::new(memory),enabled,- profile_id,}}@@ -44,7 +29,6 @@ impl AgentExperienceCaptureHook {Self {store,enabled,- profile_id: None,}}@@ -84,23 +68,7 @@ impl PostTurnHook for AgentExperienceCaptureHook {return Ok(());}- for mut candidate in Self::extract_candidates(ctx) {- // Stamp the active profile (1c) so retrieval can partition. Left as- // `None` for the profile-less session — unstamped records read as- // shared/legacy and surface under any profile.- candidate.profile_id = self.profile_id.clone();- // Re-derive the storage key to include the profile now that it's- // stamped: `extract_candidates` builds the id profile-agnostically, so- // two profiles hitting the same task/tool/outcome triple would- // otherwise share one `experience/<id>` key and overwrite each other.- // `None` reproduces the legacy id byte-for-byte (see- // `stable_experience_id_for_profile`).- candidate.id = stable_experience_id_for_profile(- &candidate.task_summary,- &candidate.tool_sequence,- candidate.outcome,- candidate.profile_id.as_deref(),- );+ for candidate in Self::extract_candidates(ctx) {if let Err(err) = self.store.put(candidate).await {log::warn!("[agent-experience] failed to capture turn experience: {err}");}@@ -253,10 +221,6 @@ fn build_experience(source: ExperienceSource::ToolLoop,agent_id: clean_optional(agent_id),entrypoint: clean_optional(entrypoint),- // Stamped by the hook's `on_turn_complete` from the active profile;- // `extract_candidates` stays profile-agnostic so its unit tests need no- // profile context.- profile_id: None,task_fingerprint: stable_task_fingerprint(&task_summary),task_summary,tools_used,diff --git a/crates/openhuman-core/src/agent/experience/capture_tests.rs b/crates/openhuman-core/src/agent/experience/capture_tests.rsindex baaee3b98f..88e5a26845 100644--- a/crates/openhuman-core/src/agent/experience/capture_tests.rs+++ b/crates/openhuman-core/src/agent/experience/capture_tests.rs@@ -70,7 +70,6 @@ fn extract_candidates_records_repeated_failures() {assert!(repeated_failure.avoid_hint.is_some());}-#[tokio::test]async fn on_turn_complete_persists_candidates() {let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());let store = AgentExperienceStore::new(memory.clone());@@ -88,74 +87,4 @@ async fn on_turn_complete_persists_candidates() {assert_eq!(stored[0].outcome, ExperienceOutcome::Success);assert_eq!(stored[0].agent_id.as_deref(), Some("orchestrator"));assert_eq!(stored[0].entrypoint.as_deref(), Some("web_channel"));- // Profile-less hook leaves records unstamped (shared/legacy).- assert_eq!(stored[0].profile_id, None);-}--#[tokio::test]-async fn on_turn_complete_stamps_active_profile() {- let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());- let hook =- AgentExperienceCaptureHook::with_profile(memory.clone(), true, Some("alice".to_string()));-- hook.on_turn_complete(&ctx_with(vec![- call("grep", true, "grep: ok (20 chars)"),- call("file_read", true, "file_read: ok (100 chars)"),- ]))- .await- .unwrap();-- let stored = AgentExperienceStore::new(memory).list().await.unwrap();- assert_eq!(stored.len(), 1);- assert_eq!(- stored[0].profile_id.as_deref(),- Some("alice"),- "captured record must be stamped with the active profile id"- );-}--#[tokio::test]-async fn identical_candidates_under_different_profiles_do_not_collide() {- // Alice and Bob learn the same task/tool/outcome triple. Their records- // must land under distinct storage keys so neither overwrites the other,- // and the profile-less (None) key must match the legacy derivation.- let calls = || {- vec![- call("grep", true, "grep: ok (20 chars)"),- call("file_read", true, "file_read: ok (100 chars)"),- ]- };-- let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());- AgentExperienceCaptureHook::with_profile(memory.clone(), true, Some("alice".to_string()))- .on_turn_complete(&ctx_with(calls()))- .await- .unwrap();- AgentExperienceCaptureHook::with_profile(memory.clone(), true, Some("bob".to_string()))- .on_turn_complete(&ctx_with(calls()))- .await- .unwrap();- AgentExperienceCaptureHook::new(memory.clone(), true)- .on_turn_complete(&ctx_with(calls()))- .await- .unwrap();-- let stored = AgentExperienceStore::new(memory).list().await.unwrap();- // Three distinct records rather than one repeatedly-overwritten key.- assert_eq!(stored.len(), 3, "each profile keeps its own record");- let ids: std::collections::HashSet<&str> = stored.iter().map(|e| e.id.as_str()).collect();- assert_eq!(ids.len(), 3, "the three storage keys must be distinct");-- // The profile-less record's key matches the legacy (profile-agnostic)- // derivation for the same triple.- let none_record = stored- .iter()- .find(|e| e.profile_id.is_none())- .expect("a profile-less record");- let legacy_id = stable_experience_id(- &none_record.task_summary,- &none_record.tool_sequence,- none_record.outcome,- );- assert_eq!(none_record.id, legacy_id);}diff --git a/crates/openhuman-core/src/agent/experience/ops.rs b/crates/openhuman-core/src/agent/experience/ops.rsindex 1080b5c67b..596e41d5c0 100644--- a/crates/openhuman-core/src/agent/experience/ops.rs+++ b/crates/openhuman-core/src/agent/experience/ops.rs@@ -88,7 +88,6 @@ impl DriverMemory {/// The driver bound for one memory subtree of `config`'s workspace.///- /// `"memory"` is the shared tree; `"memory-<id>"` is a profile that opted/// into dedicated memory. Each subtree is its own binding and therefore its/// own store, which is what makes `dedicatedMemory` isolation hold.///@@ -268,26 +267,17 @@ pub struct RetrieveParams {pub agent_id: Option<String>,#[serde(default)]pub entrypoint: Option<String>,- /// Profile partition filter (1c). `None` (omitted) recalls the whole pool;- /// `Some(P)` recalls records stamped `P` plus unstamped legacy records.- #[serde(default)]- pub profile_id: Option<String>,#[serde(default)]pub max_hits: Option<usize>,}#[derive(Debug, Deserialize, Default)]pub struct ListParams {- /// Profile partition filter (1c), same semantics as `RetrieveParams`.- #[serde(default)]- pub profile_id: Option<String>,}#[derive(Debug, Deserialize)]pub struct DismissParams {pub id: String,- #[serde(default)]- pub profile_id: Option<String>,}#[derive(Debug, Serialize)]@@ -296,49 +286,13 @@ pub struct DismissResult {pub dismissed: bool,}-fn profile_memory_subdir(- _workspace_dir: &std::path::Path,- profile_id: Option<&str>,-) -> Result<String, String> {- let _ = profile_id;- Ok("memory".to_string())-}--/// The experience store for `profile_id`'s memory subtree.-///-/// Both arms used to resolve the in-process engine — `global::client_if_ready()`-/// with a `global::init` fallback for the shared tree, a freshly constructed-/// `UnifiedMemory` for a dedicated one. Neither exists any more (#5560): both-/// arms now go through [`DriverMemory::for_subtree`], with `"memory"` naming the-/// shared tree. That is the same workspace-and-subtree binding key the session-/// builder already resolves for the archivist, so the two cannot end up on-/// different stores for one profile.-async fn open_store(profile_id: Option<&str>) -> Result<AgentExperienceStore, String> {- let profile_id = profile_id.map(str::trim).filter(|id| !id.is_empty());+async fn open_store() -> Result<AgentExperienceStore, String> {let config = Config::load_or_init().await.map_err(|e| format!("load config: {e}"))?;- if profile_id.is_none() {- return open_store_in_subdir(&config, "memory").await;- }-- let memory_subdir = profile_memory_subdir(&config.workspace_dir, profile_id)?;-- open_store_in_subdir(&config, &memory_subdir).await+ open_store_in_subdir(&config, "memory").await}-/// The experience store over one named memory subtree of `config`'s workspace.-///-/// # The embedder moved with the store, and that is the intended delta-///-/// The dedicated-subtree arm used to build its own `UnifiedMemory` with a-/// config-scoped embedding provider, so that the experience store's managed-/// embedder read the signed-in user's session rather than the keyless-/// `default_state_dir()` scope (#5501). The bound driver embeds with the-/// embedder the module policy publishes — which is that same user-scoped one,-/// resolved once at boot instead of per store — so #5501's fix survives the-/// move. What is gone is this call site's ability to choose a *different*-/// embedder from the rest of the subsystem, which was never the point.async fn open_store_in_subdir(config: &Config,memory_subdir: &str,@@ -348,34 +302,18 @@ async fn open_store_in_subdir(Ok(AgentExperienceStore::new(memory))}-fn query_memory_subdirs(- _workspace_dir: &std::path::Path,- profile_id: Option<&str>,-) -> Result<Vec<String>, String> {- let _ = profile_id;- Ok(vec!["memory".to_string()])-}--async fn open_query_stores(profile_id: Option<&str>) -> Result<Vec<AgentExperienceStore>, String> {- let config = Config::load_or_init()- .await- .map_err(|e| format!("load config: {e}"))?;- let subdirs = query_memory_subdirs(&config.workspace_dir, profile_id)?;- let mut stores = Vec::with_capacity(subdirs.len());- for subdir in subdirs {- stores.push(open_store_in_subdir(&config, &subdir).await?);- }- Ok(stores)+async fn open_query_stores() -> Result<Vec<AgentExperienceStore>, String> {+ Ok(vec![open_store().await?])}pub async fn capture(params: CaptureParams) -> Result<RpcOutcome<AgentExperience>, String> {- let store = open_store(params.experience.profile_id.as_deref()).await?;+ let store = open_store().await?;let stored = store.put(params.experience).await?;Ok(RpcOutcome::single_log(stored, "agent experience captured"))}pub async fn retrieve(params: RetrieveParams) -> Result<RpcOutcome<Vec<ExperienceHit>>, String> {- let stores = open_query_stores(params.profile_id.as_deref()).await?;+ let stores = open_query_stores().await?;let max_hits = params.max_hits.unwrap_or(5);let query = ExperienceQuery {query: params.query,@@ -383,7 +321,6 @@ pub async fn retrieve(params: RetrieveParams) -> Result<RpcOutcome<Vec<Experienctags: params.tags,agent_id: params.agent_id,entrypoint: params.entrypoint,- profile_id: params.profile_id,max_hits,};let hits = retrieve_across_stores(&stores, query).await?;@@ -391,10 +328,10 @@ pub async fn retrieve(params: RetrieveParams) -> Result<RpcOutcome<Vec<Experienc}pub async fn list(params: ListParams) -> Result<RpcOutcome<Vec<AgentExperience>>, String> {- let stores = open_query_stores(params.profile_id.as_deref()).await?;+ let stores = open_query_stores().await?;let mut by_id: BTreeMap<String, AgentExperience> = BTreeMap::new();for store in stores {- for experience in store.list_for_profile(params.profile_id.as_deref()).await? {+ for experience in store.list().await? {let id = experience.id.clone();match by_id.get(&id) {Some(existing) if existing.updated_at_ms >= experience.updated_at_ms => {}@@ -417,11 +354,11 @@ pub async fn list(params: ListParams) -> Result<RpcOutcome<Vec<AgentExperience>>}pub async fn dismiss(params: DismissParams) -> Result<RpcOutcome<DismissResult>, String> {- let stores = open_query_stores(params.profile_id.as_deref()).await?;+ let stores = open_query_stores().await?;let mut dismissed = false;for store in stores {dismissed |= store- .dismiss_for_profile(¶ms.id, params.profile_id.as_deref())+ .dismiss(¶ms.id).await?;}Ok(RpcOutcome::single_log(diff --git a/crates/openhuman-core/src/agent/experience/ops_tests.rs b/crates/openhuman-core/src/agent/experience/ops_tests.rsindex 01ec176eab..7056973028 100644--- a/crates/openhuman-core/src/agent/experience/ops_tests.rs+++ b/crates/openhuman-core/src/agent/experience/ops_tests.rs@@ -58,7 +58,6 @@ async fn driver_memory_round_trips_through_the_bound_driver() {assert!(memory.health_check().await, "a bound driver is reachable");}-/// The experience store opened for a profile-less caller and the one opened/// for the `"memory"` subtree are the same store — the shared-tree arm has/// no special case any more.#[tokio::test]@@ -75,7 +74,6 @@ async fn experience_store_round_trips_over_the_bound_driver() {source: crate::agent::experience::types::ExperienceSource::ToolLoop,agent_id: None,entrypoint: None,- profile_id: None,task_fingerprint: "fp-adapter".into(),task_summary: "route the experience store onto the contract".into(),tools_used: Vec::new(),diff --git a/crates/openhuman-core/src/agent/experience/prompt_tests.rs b/crates/openhuman-core/src/agent/experience/prompt_tests.rsindex 3634e9105d..8aa1437f5c 100644--- a/crates/openhuman-core/src/agent/experience/prompt_tests.rs+++ b/crates/openhuman-core/src/agent/experience/prompt_tests.rs@@ -12,7 +12,6 @@ fn sample_hit(lesson: impl Into<String>) -> ExperienceHit {source: ExperienceSource::ToolLoop,agent_id: Some("orchestrator".into()),entrypoint: Some("chat".into()),- profile_id: None,task_fingerprint: "fp".into(),task_summary: "search docs".into(),tools_used: vec!["grep".into(), "file_read".into()],diff --git a/crates/openhuman-core/src/agent/experience/schemas.rs b/crates/openhuman-core/src/agent/experience/schemas.rsindex 26d68dae8f..7b4dbfe774 100644--- a/crates/openhuman-core/src/agent/experience/schemas.rs+++ b/crates/openhuman-core/src/agent/experience/schemas.rs@@ -91,14 +91,6 @@ pub fn schemas(function: &str) -> ControllerSchema {comment: "Optional turn entrypoint or event channel.",required: false,},- FieldSchema {- name: "profile_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional profile partition: returns records stamped with this \- profile plus unstamped legacy records; omit to recall the whole pool.",- required: false,- },FieldSchema {name: "max_hits",ty: TypeSchema::Option(Box::new(TypeSchema::U64)),@@ -117,14 +109,6 @@ pub fn schemas(function: &str) -> ControllerSchema {namespace: "agent_experience",function: "list",description: "List locally stored procedural operating experiences.",- inputs: vec![FieldSchema {- name: "profile_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional profile partition: lists records stamped with this profile plus \- unstamped legacy records; omit to list the whole pool.",- required: false,- }],outputs: vec![FieldSchema {name: "experiences",ty: TypeSchema::Array(Box::new(TypeSchema::Ref("AgentExperience"))),@@ -143,12 +127,6 @@ pub fn schemas(function: &str) -> ControllerSchema {comment: "Experience id to dismiss.",required: true,},- FieldSchema {- name: "profile_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional owning profile whose memory store contains the experience.",- required: false,- },],outputs: vec![FieldSchema {name: "result",diff --git a/crates/openhuman-core/src/agent/experience/store.rs b/crates/openhuman-core/src/agent/experience/store.rsindex 9bad54a1a6..5e8e4280ae 100644--- a/crates/openhuman-core/src/agent/experience/store.rs+++ b/crates/openhuman-core/src/agent/experience/store.rs@@ -1,5 +1,5 @@use crate::agent::experience::types::{- stable_experience_id_for_profile, AgentExperience, ExperienceHit,+ stable_experience_id, AgentExperience, ExperienceHit,};use crate::memory::safety::sanitize_text;use crate::memory::{Memory, MemoryCategory};@@ -58,35 +58,9 @@ pub struct ExperienceQuery {pub tags: Vec<String>,pub agent_id: Option<String>,pub entrypoint: Option<String>,- /// Profile partition (1c). When `Some(P)`, retrieval returns records stamped- /// `P` plus unstamped legacy records and excludes records stamped with a- /// different profile. When `None` (the profile-less session), every record- /// is in scope — see [`experience_matches_profile`].- pub profile_id: Option<String>,pub max_hits: usize,}-/// Profile partition predicate shared by retrieval and RPC list (1c).-///-/// - A **profile-less** query (`query_profile == None`) sees **everything**:-/// the default session historically owns the whole shared experience pool and-/// must keep recalling every record it and prior versions wrote, so narrowing-/// it would silently drop guidance the default agent still relies on.-/// - A **profiled** query (`Some(P)`) sees records stamped `P` plus unstamped-/// legacy/shared records (`record_profile == None`), and excludes records-/// stamped with a different profile `Q` — the isolation the feature adds.-pub fn experience_matches_profile(- record_profile: Option<&str>,- query_profile: Option<&str>,-) -> bool {- match query_profile {- None => true,- Some(active) => match record_profile {- None => true,- Some(owner) => owner == active,- },- }-}#[derive(Clone)]pub struct AgentExperienceStore {@@ -100,11 +74,10 @@ impl AgentExperienceStore {pub async fn put(&self, mut experience: AgentExperience) -> Result<AgentExperience, String> {if experience.id.trim().is_empty() {- experience.id = stable_experience_id_for_profile(+ experience.id = stable_experience_id(&experience.task_summary,&experience.tool_sequence,experience.outcome,- experience.profile_id.as_deref(),);}if experience.task_summary.trim().is_empty() {@@ -169,50 +142,19 @@ impl AgentExperienceStore {Ok(experiences)}- /// [`Self::list`] narrowed to a profile partition (1c). `profile_id == None`- /// returns everything (the profile-less view); `Some(P)` returns records- /// stamped `P` plus unstamped legacy records. Shares- /// [`experience_matches_profile`] with retrieval so the two never diverge.- pub async fn list_for_profile(- &self,- profile_id: Option<&str>,- ) -> Result<Vec<AgentExperience>, String> {- Ok(self- .list()- .await?- .into_iter()- .filter(|experience| {- experience_matches_profile(experience.profile_id.as_deref(), profile_id)- })- .collect())- }pub async fn dismiss(&self, id: &str) -> Result<bool, String> {- self.dismiss_for_profile(id, None).await- }-- /// Dismiss an experience only when it belongs to the caller's visible- /// profile partition. A profiled caller may dismiss its own or unstamped- /// legacy records, but never a sibling profile's record even if it knows- /// the storage id.- pub async fn dismiss_for_profile(- &self,- id: &str,- profile_id: Option<&str>,- ) -> Result<bool, String> {let key = storage_key(id);let Some(mut experience) = self.fetch(&key).await? else {return Ok(false);};- if !experience_matches_profile(experience.profile_id.as_deref(), profile_id) {- return Ok(false);- }experience.dismissed = true;experience.updated_at_ms = now_ms();self.put(experience).await?;Ok(true)}+pub async fn retrieve(&self, query: ExperienceQuery) -> Result<Vec<ExperienceHit>, String> {if query.max_hits == 0 {return Ok(Vec::new());@@ -227,12 +169,6 @@ impl AgentExperienceStore {.await?.into_iter().filter(|experience| !experience.dismissed)- .filter(|experience| {- experience_matches_profile(- experience.profile_id.as_deref(),- query.profile_id.as_deref(),- )- }).filter_map(|experience| {let (score, match_reasons) = score_experience(&experience,@@ -276,8 +212,6 @@ impl AgentExperienceStore {/// Retrieve one logical experience pool across multiple physical memory stores.///-/// Dedicated profiles write new experiences into their own memory subtree, but-/// still need to recall unstamped legacy experiences from the shared store./// Keep the merge, de-duplication, ordering, and final limit in one place so the/// RPC and live-turn paths cannot drift.pub async fn retrieve_across_stores(@@ -333,8 +267,7 @@ fn storage_key(id: &str) -> String {/// numbers is exactly what caused the corruption we fixed. `id` is the storage/// key (scrubbing it would desync key vs. content; a secret-bearing key is/// rejected up front by the memory layer's `has_likely_secret` guard) and-/// `profile_id` is a hard partition-filter key, so both are deliberately left-/// intact.+/// key (scrubbing it would desync key vs. content); it is left intact.fn redact_experience(mut experience: AgentExperience) -> AgentExperience {fn scrub(value: &str) -> String {sanitize_text(value).valuediff --git a/crates/openhuman-core/src/agent/experience/store_tests.rs b/crates/openhuman-core/src/agent/experience/store_tests.rsindex 543c10c097..0b475e7bbf 100644--- a/crates/openhuman-core/src/agent/experience/store_tests.rs+++ b/crates/openhuman-core/src/agent/experience/store_tests.rs@@ -30,7 +30,6 @@ fn sample_experience(source: ExperienceSource::ToolLoop,agent_id: Some("orchestrator".into()),entrypoint: Some("chat".into()),- profile_id: None,task_fingerprint: format!("fp-{id}"),task_summary: task_summary.to_string(),tools_used: tools.iter().map(|tool| (*tool).to_string()).collect(),@@ -82,202 +81,6 @@ async fn put_list_and_dismiss_round_trip() {assert!(listed[0].dismissed);}-#[tokio::test]-async fn generated_ids_partition_identical_experiences_by_profile() {- let (store, _) = fresh_store();- let mut alice = sample_experience("", "same task", vec!["grep"], vec!["docs"], 0.8);- alice.profile_id = Some("alice".into());- let mut bob = alice.clone();- bob.profile_id = Some("bob".into());-- let alice = store.put(alice).await.unwrap();- let bob = store.put(bob).await.unwrap();-- assert_ne!(alice.id, bob.id);- let listed = store.list().await.unwrap();- assert_eq!(listed.len(), 2);- assert!(listed- .iter()- .any(|item| item.profile_id.as_deref() == Some("alice")));- assert!(listed- .iter()- .any(|item| item.profile_id.as_deref() == Some("bob")));-}--#[tokio::test]-async fn retrieve_ranks_tool_and_query_matches() {- let (store, _) = fresh_store();- store- .put(sample_experience(- "exp_docs",- "search repository docs",- vec!["grep", "file_read"],- vec!["docs"],- 0.6,- ))- .await- .unwrap();- store- .put(sample_experience(- "exp_email",- "send a careful email",- vec!["email"],- vec!["mail"],- 1.0,- ))- .await- .unwrap();-- let hits = store- .retrieve(ExperienceQuery {- query: "search docs with grep".into(),- tools: vec!["grep".into()],- tags: vec!["docs".into()],- agent_id: Some("orchestrator".into()),- entrypoint: Some("chat".into()),- profile_id: None,- max_hits: 2,- })- .await- .unwrap();-- assert_eq!(hits.len(), 2);- assert_eq!(hits[0].experience.id, "exp_docs");- assert!(hits[0].score > hits[1].score);- assert!(hits[0].match_reasons.contains(&"tool_overlap".into()));- assert!(hits[0].match_reasons.contains(&"query_overlap".into()));-}--#[test]-fn experience_matches_profile_partition_rules() {- // Profile-less query sees everything.- assert!(experience_matches_profile(None, None));- assert!(experience_matches_profile(Some("p"), None));- // Profiled query: own + legacy in, sibling out.- assert!(experience_matches_profile(Some("p"), Some("p")));- assert!(experience_matches_profile(None, Some("p")));- assert!(!experience_matches_profile(Some("q"), Some("p")));-}--async fn seed_partitioned(store: &AgentExperienceStore) {- let mut own = sample_experience("exp_p", "task p", vec!["grep"], vec!["docs"], 0.8);- own.profile_id = Some("p".into());- store.put(own).await.unwrap();-- let mut sibling = sample_experience("exp_q", "task q", vec!["grep"], vec!["docs"], 0.8);- sibling.profile_id = Some("q".into());- store.put(sibling).await.unwrap();-- // Unstamped legacy record.- store- .put(sample_experience(- "exp_legacy",- "task legacy",- vec!["grep"],- vec!["docs"],- 0.8,- ))- .await- .unwrap();-}--#[tokio::test]-async fn retrieve_partitions_by_profile() {- let (store, _) = fresh_store();- seed_partitioned(&store).await;-- // Profile P: sees P + legacy, never Q.- let hits = store- .retrieve(ExperienceQuery {- query: "task".into(),- tools: vec!["grep".into()],- tags: vec!["docs".into()],- profile_id: Some("p".into()),- max_hits: 10,- ..Default::default()- })- .await- .unwrap();- let ids: BTreeSet<_> = hits.iter().map(|h| h.experience.id.clone()).collect();- assert!(ids.contains("exp_p"), "profile P must see its own record");- assert!(- ids.contains("exp_legacy"),- "profile P must see legacy records"- );- assert!(!ids.contains("exp_q"), "profile P must not see sibling Q");-- // Profile-less: sees everything.- let all = store- .retrieve(ExperienceQuery {- query: "task".into(),- tools: vec!["grep".into()],- tags: vec!["docs".into()],- profile_id: None,- max_hits: 10,- ..Default::default()- })- .await- .unwrap();- let all_ids: BTreeSet<_> = all.iter().map(|h| h.experience.id.clone()).collect();- assert!(all_ids.contains("exp_p"));- assert!(all_ids.contains("exp_q"));- assert!(all_ids.contains("exp_legacy"));-}--#[tokio::test]-async fn dismiss_for_profile_rejects_sibling_record() {- let (store, _) = fresh_store();- seed_partitioned(&store).await;-- assert!(!store.dismiss_for_profile("exp_q", Some("p")).await.unwrap());- assert!(store- .list()- .await- .unwrap()- .iter()- .find(|experience| experience.id == "exp_q")- .is_some_and(|experience| !experience.dismissed));-- assert!(store- .dismiss_for_profile("exp_legacy", Some("p"))- .await- .unwrap());- assert!(store.dismiss_for_profile("exp_p", Some("p")).await.unwrap());-}--#[tokio::test]-async fn list_for_profile_partitions() {- let (store, _) = fresh_store();- seed_partitioned(&store).await;-- let p_ids: BTreeSet<_> = store- .list_for_profile(Some("p"))- .await- .unwrap()- .into_iter()- .map(|e| e.id)- .collect();- assert_eq!(- p_ids,- BTreeSet::from(["exp_legacy".to_string(), "exp_p".to_string()])- );-- let all_ids: BTreeSet<_> = store- .list_for_profile(None)- .await- .unwrap()- .into_iter()- .map(|e| e.id)- .collect();- assert_eq!(- all_ids,- BTreeSet::from([- "exp_legacy".to_string(),- "exp_p".to_string(),- "exp_q".to_string()- ])- );-}#[tokio::test]async fn retrieve_ignores_dismissed_records() {@@ -301,7 +104,6 @@ async fn retrieve_ignores_dismissed_records() {tags: vec!["docs".into()],agent_id: None,entrypoint: None,- profile_id: None,max_hits: 5,}).awaitdiff --git a/crates/openhuman-core/src/agent/experience/types.rs b/crates/openhuman-core/src/agent/experience/types.rsindex d13003fa33..1586b280d6 100644--- a/crates/openhuman-core/src/agent/experience/types.rs+++ b/crates/openhuman-core/src/agent/experience/types.rs@@ -28,13 +28,6 @@ pub struct AgentExperience {pub source: ExperienceSource,pub agent_id: Option<String>,pub entrypoint: Option<String>,- /// Id of the agent profile the turn ran under when this experience was- /// captured (1c). `None` for the default profile-less session and for every- /// record written before profile scoping existed (legacy). Serde-defaulted- /// so older stored payloads deserialize unchanged; retrieval treats `None`- /// records as shared/legacy and surfaces them under any profile.- #[serde(default)]- pub profile_id: Option<String>,pub task_fingerprint: String,pub task_summary: String,pub tools_used: Vec<String>,@@ -74,29 +67,6 @@ pub fn stable_experience_id(task_summary: &str,tool_sequence: &[String],outcome: ExperienceOutcome,-) -> String {- stable_experience_id_for_profile(task_summary, tool_sequence, outcome, None)-}--/// Derive a stable experience id, partitioning the storage key by the capturing-/// profile when one is set.-///-/// The store keys records by this id, so two profiles that learn the *same*-/// task/tool/outcome triple must not collapse onto one key (the later-/// `store.put()` would otherwise overwrite the earlier profile's record — see-/// the 1c retrieval partition). Mixing the profile id into the digest keeps each-/// profile's procedural experience distinct.-///-/// `profile_id == None` (the profile-less / legacy session) is **byte-identical**-/// to the pre-1c derivation, so every record written before profile scoping keeps-/// its exact id and stays retrievable. A `Some` profile appends a-/// domain-separated segment, so profile A, profile B, and `None` yield three-/// different keys for the same triple.-pub fn stable_experience_id_for_profile(- task_summary: &str,- tool_sequence: &[String],- outcome: ExperienceOutcome,- profile_id: Option<&str>,) -> String {let mut hasher = Sha256::new();hasher.update(task_summary.trim().to_lowercase().as_bytes());@@ -106,17 +76,11 @@ pub fn stable_experience_id_for_profile(hasher.update(b"\0");}hasher.update(outcome_key(outcome).as_bytes());- // Only stamp the profile segment when a non-empty id is present: an absent or- // blank profile must reproduce the legacy digest byte-for-byte so existing- // stored records keep their identity.- if let Some(profile_id) = profile_id.map(str::trim).filter(|id| !id.is_empty()) {- hasher.update(b"\0profile\0");- hasher.update(profile_id.to_lowercase().as_bytes());- }let digest = format!("{:x}", hasher.finalize());format!("exp_{}", &digest[..24])}+fn outcome_key(outcome: ExperienceOutcome) -> &'static str {match outcome {ExperienceOutcome::Success => "success",diff --git a/crates/openhuman-core/src/agent/experience/types_tests.rs b/crates/openhuman-core/src/agent/experience/types_tests.rsindex ff9a328526..49359abea4 100644--- a/crates/openhuman-core/src/agent/experience/types_tests.rs+++ b/crates/openhuman-core/src/agent/experience/types_tests.rs@@ -1,6 +1,5 @@use super::*;-#[test]fn redact_text_masks_secret_like_values() {let redacted = redact_text("token=abc123 password: hunter2 normal");assert!(redacted.contains("token=[redacted]"));@@ -10,7 +9,6 @@ fn redact_text_masks_secret_like_values() {assert!(redacted.contains("normal"));}-#[test]fn redact_text_masks_bearer_tokens_and_openai_style_keys() {let redacted =redact_text("Authorization: Bearer secret-token sk-abcdefghijklmnopqrstuvwxyz123456");@@ -20,7 +18,6 @@ fn redact_text_masks_bearer_tokens_and_openai_style_keys() {assert!(redacted.contains("sk-[redacted]"));}-#[test]fn stable_experience_id_is_repeatable() {let sequence = vec!["grep".to_string(), "file_read".to_string()];let first = stable_experience_id("same task", &sequence, ExperienceOutcome::Success);@@ -29,61 +26,9 @@ fn stable_experience_id_is_repeatable() {assert!(first.starts_with("exp_"));}-#[test]fn stable_experience_id_changes_when_outcome_changes() {let sequence = vec!["grep".to_string(), "file_read".to_string()];let success = stable_experience_id("same task", &sequence, ExperienceOutcome::Success);let failure = stable_experience_id("same task", &sequence, ExperienceOutcome::Failure);assert_ne!(success, failure);}--#[test]-fn stable_experience_id_for_profile_none_matches_legacy_derivation() {- // `None` must be byte-identical to the pre-1c derivation so existing- // stored records keep their identity.- let sequence = vec!["grep".to_string(), "file_read".to_string()];- let legacy = stable_experience_id("same task", &sequence, ExperienceOutcome::Success);- let none =- stable_experience_id_for_profile("same task", &sequence, ExperienceOutcome::Success, None);- assert_eq!(legacy, none);- // An empty / whitespace-only profile id is treated as `None`.- let blank = stable_experience_id_for_profile(- "same task",- &sequence,- ExperienceOutcome::Success,- Some(" "),- );- assert_eq!(legacy, blank);-}--#[test]-fn stable_experience_id_for_profile_partitions_by_profile() {- // Same task/tool/outcome triple under profile A vs B vs None yields three- // distinct keys, so no profile can overwrite another's record.- let sequence = vec!["grep".to_string(), "file_read".to_string()];- let none =- stable_experience_id_for_profile("same task", &sequence, ExperienceOutcome::Success, None);- let alice = stable_experience_id_for_profile(- "same task",- &sequence,- ExperienceOutcome::Success,- Some("alice"),- );- let bob = stable_experience_id_for_profile(- "same task",- &sequence,- ExperienceOutcome::Success,- Some("bob"),- );- assert_ne!(none, alice);- assert_ne!(none, bob);- assert_ne!(alice, bob);- // Deterministic per profile.- let alice_again = stable_experience_id_for_profile(- "same task",- &sequence,- ExperienceOutcome::Success,- Some("alice"),- );- assert_eq!(alice, alice_again);-}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/experience_store.rs b/crates/openhuman-core/src/agent/tinyagents/host/experience_store.rsindex affe456788..4e8b61c81e 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/experience_store.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/experience_store.rs@@ -69,7 +69,7 @@ use crate::agent::experience::store::{retrieve_across_stores, AgentExperienceStore, ExperienceQuery,};use crate::agent::experience::types::{- redact_text, stable_experience_id, stable_experience_id_for_profile, AgentExperience,+ redact_text, stable_experience_id, AgentExperience,ExperienceHit, ExperienceOutcome, ExperienceSource,};use crate::memory::Memory;@@ -229,11 +229,10 @@ impl OpenHumanExperienceStore {// first agent's record. Using the one hashed field that is free// keeps identity per-agent without inventing a tool trace or// reaching into the domain's digest.- id: stable_experience_id_for_profile(+ id: stable_experience_id(&task_summary,std::slice::from_ref(&agent_key),outcome,- None,),// Left at zero so `put` stamps creation time itself, and preserves// the original `created_at_ms` when this id already exists.