Skip to content

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

docs(learning): update README to reflect async cache, memory guard, and split modules

Steven Enamakel16a70bf3b8f8
diff --git a/crates/openhuman-core/src/agent/learning/README.md b/crates/openhuman-core/src/agent/learning/README.md
index c15cab4c63..d4c2eebb78 100644
--- a/crates/openhuman-core/src/agent/learning/README.md
+++ b/crates/openhuman-core/src/agent/learning/README.md
@@ -24,14 +24,14 @@ The subsystem is organised in phases (issue #566): **Phase 1** the candidate tax
| `cache.rs` | `FacetCache` — typed wrapper over `user_profile_facets`; class↔key helpers (`class_from_key`, `key_with_class`, `class_prefix`). Delegates to the `MemoryProfile` family via `crate::memory::guard::MemoryGuard`. |
| `stability_detector.rs` | Phase 3 `StabilityDetector::rebuild` — the scoring/budget/state-assignment cycle; thresholds, half-lives, budgets, and the `stability()` formula. Publishes `CacheRebuilt`. |
| `scheduler.rs` | Periodic rebuild loop (`spawn_rebuild_loop`, default 30 min) + event-driven debounced trigger (`register_event_trigger`) subscribing to memory/tree-summarizer events. |
-| `schemas.rs` | `include!`s `schemas_part_01.rs` (controller schema list) and `schemas_part_02.rs` (the `handle_*` async handlers) for the `learning.*` namespace. |
+| `schemas.rs` | `include!`s `schemas_part_01.rs` (controller schema list, `RegisteredController` table, the `linkedin_enrichment` / `save_profile` / `rebuild_cache` / `cache_stats` handlers, and the `get_cache()` helper) and `schemas_part_02.rs` (the facet handlers: `list_facets`, `get_facet`, `update_facet`, `pin_facet`, `unpin_facet`, `forget_facet`, `reset_cache`) for the `learning.*` namespace. |
| `tools.rs` | The 11 `Learning*Tool`s mirroring the RPC surface (see "Agent tools" below). |
| `reflection.rs` | `ReflectionHook` post-turn hook: heuristic reflection-cue capture + LLM reflection, stores observations/patterns/preferences/reflections, emits Goal/Style candidates. |
| `tool_tracker.rs` | `ToolTrackerHook` post-turn hook + `ToolStats`; per-tool running success/failure/duration tallies in the `tool_effectiveness` memory category. |
| `user_profile.rs` | `UserProfileHook` post-turn hook; Aho-Corasick DFA over curated preference phrases, stores matches in the `user_profile` category. |
-| `prompt_sections.rs` | `LearnedContextSection`, `UserProfileSection`, `MemoryAccessSection` (+ `MEMORY_ACCESS_INSTRUCTION`), and `load_learned_from_cache` (synchronous cache→prompt loader, cap 25). |
+| `prompt_sections.rs` | `LearnedContextSection`, `UserProfileSection`, `MemoryAccessSection` (+ `MEMORY_ACCESS_INSTRUCTION`), `MemoryWriteSection` / `memory_write_instruction`, the memory tool-name constants + `any_tool_offered` (used by the harness to decide whether to inject the memory sections), and the async `load_learned_from_cache` (cache→prompt loader, cap 25). |
| `profile_md_renderer.rs` | `ProfileMdRenderer` — subscribes to `CacheRebuilt`, re-renders 5 managed `PROFILE.md` blocks (style/identity/tooling/vetoes/goals) from Active facets. |
-| `linkedin_enrichment.rs` | Gmail→LinkedIn→Apify enrichment pipeline; `run_linkedin_enrichment`, `summarise_profile_with_llm`, `render_profile_markdown`, `scrape_linkedin_profile`. |
+| `linkedin_enrichment.rs` | Gmail→LinkedIn→Apify enrichment pipeline, `include!`-split into `linkedin_enrichment_part_01.rs` (`run_linkedin_enrichment`, `summarise_profile_with_llm`, `render_profile_markdown`, `scrape_linkedin_profile`) and `linkedin_enrichment_part_02.rs` (guard lookup + `put_profile_document` persistence). |
| `extract/` | Phase 2 producers (`mod.rs` + `signature.rs`, `heuristics.rs`, `summary_facets.rs`). |
| `extract/signature.rs` | Email-signature parser → Identity candidates; subscribes to `DocumentCanonicalized` (email). |
| `extract/heuristics.rs` | `LengthRatioDetector` / `EditWindowDetector` / `CorrectionRepeatDetector` → Style + Veto candidates via `record_turn`. |
@@ -48,7 +48,7 @@ Re-exported from `mod.rs`:
- **Candidate types**: `Buffer`, `CueFamily`, `EvidenceRef`, `FacetClass`, `LearningCandidate`.
- **Cache / detector**: `FacetCache`, `StabilityDetector`.
- **Hooks**: `ReflectionHook`, `ToolTrackerHook`, `UserProfileHook` (all impl `PostTurnHook`).
-- **Prompt**: `LearnedContextSection`, `UserProfileSection`, `MemoryAccessSection`, `MEMORY_ACCESS_INSTRUCTION`, `load_learned_from_cache`.
+- **Prompt**: `LearnedContextSection`, `UserProfileSection`, `MemoryAccessSection`, `MemoryWriteSection`, `MEMORY_ACCESS_INSTRUCTION`, `memory_write_instruction`, `any_tool_offered`, `load_learned_from_cache`, and the tool-name constants `MEMORY_READ_TOOLS`, `MEMORY_WRITE_TOOLS`, `MEMORY_STORE_TOOL`, `MEMORY_WRITE_DELEGATE_TOOL`, `SAVE_PREFERENCE_TOOL`.
- **Profile**: `ProfileMdRenderer`.
- **Schemas**: `all_learning_controller_schemas`, `all_learning_registered_controllers`, `learning_schemas`.
@@ -71,15 +71,15 @@ Namespace `learning` (wired into `crates/openhuman-core/src/core/all.rs`; 11 con
| `learning.forget_facet` | Mark `Dropped` + `user_state = Forgotten` (blocks re-promotion). |
| `learning.reset_cache` | Delete all `Auto` rows, preserve `Pinned`. |
-All handlers go through the memory client's `profile_store()` and a `FacetCache`; `linkedin_enrichment` / `save_profile` load config via `config::rpc::load_config_with_timeout`.
+Facet handlers build a `FacetCache` over `crate::memory::ops::guard::active_memory_guard()` (`get_cache()` in `schemas_part_01.rs`); `linkedin_enrichment` / `save_profile` load config via `config::rpc::load_config_with_timeout`.
## Agent tools
-`tools.rs` (~617 production lines) defines 11 LLM-callable tools mirroring the RPC surface above: `LearningListFacetsTool`, `LearningGetFacetTool`, `LearningCacheStatsTool`, `LearningUpdateFacetTool`, `LearningPinFacetTool`, `LearningUnpinFacetTool`, `LearningForgetFacetTool`, `LearningRebuildCacheTool`, `LearningResetCacheTool`, `LearningSaveProfileTool`, `LearningEnrichProfileTool`. Re-exported via `crates/openhuman-core/src/tools/mod.rs` (`pub use crate::agent::learning::tools::*;`). Separately, the `tool_effectiveness` stats this module writes are surfaced by the cross-cutting `tool_stats` tool in `crates/openhuman-core/src/tools/impl/system/tool_stats.rs`, and `memory_tools` references learning namespaces.
+`tools.rs` defines 11 LLM-callable tools mirroring the RPC surface above: `LearningListFacetsTool`, `LearningGetFacetTool`, `LearningCacheStatsTool`, `LearningUpdateFacetTool`, `LearningPinFacetTool`, `LearningUnpinFacetTool`, `LearningForgetFacetTool`, `LearningRebuildCacheTool`, `LearningResetCacheTool`, `LearningSaveProfileTool`, `LearningEnrichProfileTool`. Re-exported via `crates/openhuman-core/src/tools/mod.rs` (`pub use crate::agent::learning::tools::*;`). Separately, the `tool_effectiveness` stats this module writes are surfaced by the cross-cutting `tool_stats` tool in `crates/openhuman-core/src/tools/impl/system/tool_stats.rs`, and `memory_tools` references learning namespaces.
## Events
-Uses the typed event bus (`crates/openhuman-core/src/core/bus.rs`, the process-wide `BUS` singleton, and `core/events.rs` for `DomainEvent` / `EventHandler`):
+Uses the typed event bus (`crates/openhuman-core/src/core/bus.rs`, the process-wide `BUS` singleton; `core/events.rs` for `DomainEvent`; handlers implement `tinybus::EventHandler<DomainEvent>`):
- **Publishes**: `DomainEvent::CacheRebuilt { added, evicted, kept, total_size, rebuilt_at }` after each rebuild (`stability_detector.rs`).
- **Subscribes**:
@@ -91,17 +91,17 @@ These are subscriber registrations rather than a single `bus.rs`; subscriptions
## Persistence
-- **`user_profile_facets`** (the ambient cache) — accessed via `FacetCache`, backed by `memory_store::profile` helpers (`profile_select_active/all`, `profile_get_by_key`, `profile_upsert_full`, `profile_set_user_state`, `profile_delete_*`). Stores `ProfileFacet { key, value, state, user_state, stability, confidence, evidence_count, evidence_refs, class, cue_families, first/last_seen_at, … }`.
-- **KV memory namespaces** (via the `Memory` trait): `learning_observations`, `learning_patterns`, `learning_reflections`, `user_profile`, `tool_effectiveness`, plus transcript-ingest `conversation_memory` / `conversation_reflections`. LinkedIn enrichment also persists via `MemoryClient::store_skill_sync` and writes `{workspace_dir}/PROFILE.md`.
+- **`user_profile_facets`** (the ambient cache) — accessed via `FacetCache`, which delegates to the `MemoryProfile` family of the active `MemoryGuard` (`list_active`, `list_all`, `get`, `upsert`, `set_user_state`, `delete`, `drop_below_threshold`; `reset_non_pinned` is a free fn in `cache.rs`). The SQL lives in the memory driver, not in this crate. Rows are `tinymemory_api::provider::ProfileFacet { key, value, state, user_state, stability, confidence, evidence_count, evidence_refs, class, cue_families, first/last_seen_at, … }`.
+- **KV memory namespaces** (via the `Memory` trait): `learning_observations`, `learning_patterns`, `learning_reflections`, `user_profile`, `tool_effectiveness`, plus transcript-ingest `conversation_memory` / `conversation_reflections`. LinkedIn enrichment also upserts the scraped profile through the guard's documents family (`put_profile_document` in `linkedin_enrichment_part_02.rs`) and writes `{workspace_dir}/PROFILE.md`.
- **In-memory**: the global `candidate::Buffer` (transient evidence, not persisted) and per-session state in `extract/heuristics.rs`.
## Dependencies
-- `tinymemory_core::store::profile` — the `ProfileFacet` / `FacetState` / `UserState` types and the SQL helpers backing `FacetCache` (heaviest dependency).
-- `crate::memory` / `memory_store` — the `Memory` trait, `MemoryClient`, categories; all KV persistence and the global memory client used by RPC handlers.
+- `tinymemory_api` — `provider::{MemoryProfile, ProfileFacet, FacetState, FacetType, UserState}` behind `FacetCache`, and the candidate taxonomy re-exported by `candidate.rs` (`learning::{CueFamily, FacetClass, LearningCandidate}`, `host::EvidenceRef`).
+- `crate::memory` — the `Memory` trait + `MemoryCategory` for KV persistence (hooks, transcript ingest), `guard::MemoryGuard` and `ops::guard::active_memory_guard` for the facet store, and `memory::api::provider::MemoryProvider` / `api::types` for the enrichment document upsert.
- `crate::agent::hooks` — `PostTurnHook` / `TurnContext` / `ToolCallRecord` implemented by the three hooks.
- `crate::agent::harness::session::transcript` — `SessionTranscript` parsing for transcript ingestion.
-- `crate::inference::provider` / `inference::local` — LLM calls for reflection and profile summarisation.
+- `crate::inference::provider::create_chat_model_from_string_with_model_id` (profile summarisation) and `crate::inference::local::global` (local reflection route); `ReflectionHook` also accepts an optional `tinyinference::model::ChatModel` for the cloud fallback.
- `crate::config` — `Config` / `LearningConfig` / `ReflectionSource` feature flags and `config::rpc` loader.
- `crate::agent::context::prompt` — `PromptContext` / `PromptSection` / `LearnedContextData` for prompt injection.
- `crate::integrations::composio` — `composio::client` (Gmail fetch for enrichment) and `composio::profile_md` (`replace_managed_block` for `PROFILE.md`).
@@ -112,8 +112,8 @@ These are subscriber registrations rather than a single `bus.rs`; subscriptions
## Used by
- `crates/openhuman-core/src/core/all.rs` — registers the `learning.*` controllers + schemas.
-- `crates/openhuman-core/src/agent/harness/session/{builder,turn}/` and `memory/agent/memory_loader.rs` — wire the post-turn hooks, prompt sections, and learned-context loading into the agent loop.
-- `learning::startup::register_learning_subscribers` is the entry point that wires the Phase 2/3/4 subscribers; it is invoked from `crates/openhuman-core/src/core/jsonrpc.rs` (`register_domain_subscribers`, the unconditional `DomainGroup::Platform` boot block), not from the (skippable) `channels::runtime::startup` path — see the "why" note in `startup.rs` (#5003).
+- `crates/openhuman-core/src/agent/harness/session/builder/factory.rs` (registers `LearnedContextSection` / `UserProfileSection` and the `ReflectionHook` when `config.learning.enabled`), `builder/helpers.rs` (`MemoryAccessSection` / `MemoryWriteSection` gated by `any_tool_offered`), `turn/context.rs` (reads the `learning_observations` / `learning_patterns` / reflections namespaces into `PromptContext.learned`), `turn/session_io_impl_01_part_02.rs` (`transcript_ingest::ingest_transcript_path`), and `agent/tinyagents/host/learning_sink.rs` (`ToolTrackerHook` + `UserProfileHook` post-turn fan-out).
+- `learning::startup::register_learning_subscribers` is the entry point that wires the Phase 2/3/4 subscribers; it is invoked from `crates/openhuman-core/src/core/jsonrpc.rs` (`register_domain_subscribers`, inside the `plan.agent` block — i.e. whenever the `DomainSet` allows `DomainGroup::Agent` — guarded by `learning_first_time()`), not from the skippable `channels::runtime::startup` path — see the "why" note in `startup.rs` (#5003).
- `crates/openhuman-core/src/modules/memory_part_01.rs` / `memory_part_03.rs` (the loadable memory module's `MemoryProfile` impl backing `FacetCache`), `integrations/composio/profile_md.rs` (`replace_managed_block`, used by `profile_md_renderer.rs`), `tools/impl/system/tool_stats.rs`, `tools/schemas.rs` — consume facet/learning types.
## Notes / gotchas
@@ -122,8 +122,8 @@ These are subscriber registrations rather than a single `bus.rs`; subscriptions
- **Class is encoded in the key prefix** (`style/verbosity`, `goal/learn_rust`). `candidate.key` carries no prefix; the detector prepends `class_prefix`. Legacy rows without a recognised prefix are skipped by rebuild.
- **`emit_candidates_*` uses the global buffer length as a synthetic `episodic_id`** (a Phase-2 placeholder noted to be replaced by a real `episodic_log` row id).
- **Goal facets render value-only** (full sentence, no key prefix) in both prompt injection and `PROFILE.md`; other classes render `**key**: value`.
-- **Prompt loaders are synchronous SQLite reads** — `load_learned_from_cache` runs in the sync prompt-build path and degrades to empty on error. Both the cache path and the legacy KV-namespace path are still active (KV slated for later removal).
-- **Reflection has a local/cloud gate.** Local route requires `local_ai.usage.learning` flag; if off it falls back to a cloud provider or no-ops (empty string), and an empty response is a clean-skip sentinel that rolls back the throttle counter. Per-session reflections are throttled by `max_reflections_per_session`.
+- **`load_learned_from_cache` is async** — the facet store sits behind the memory driver, so it is a driver call (it used to be a synchronous SQLite read) and degrades to empty on error. Both the cache path and the legacy KV-namespace path are still active (KV slated for later removal).
+- **Reflection has a local/cloud gate.** The `ReflectionSource::Local` route requires `Config::workload_uses_local("learning")` (an `ollama:` `learning_provider`); if off it falls back to the optional cloud `ChatModel` or no-ops (empty string), and an empty response is a clean-skip sentinel that rolls back the throttle counter. Per-session reflections are throttled by `max_reflections_per_session`.
- **LinkedIn enrichment short-circuits** if `PROFILE.md` already exists, and the Composio-only Gmail-search stage is documented as currently erroring (Gmail-via-Composio removed) — callers should pass `preset_profile_url` obtained via the frontend's webview Gmail helper.
- **Transcript ingestion is heuristic-only by design** (no hard LLM dependency) so it can run as a background task without provider credentials.
- The `profile_md_renderer` deliberately does **not** touch the `connected-accounts` block — that's owned by the Composio provider path.