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
docs: add README files for core modules and testing strategy
Steven Enamakelcf6c7e40c2e2
diff --git a/crates/openhuman-core/src/agent/learning/README.md b/crates/openhuman-core/src/agent/learning/README.mdindex 689bc0efb0..737ad3f13e 100644--- a/crates/openhuman-core/src/agent/learning/README.md+++ b/crates/openhuman-core/src/agent/learning/README.md@@ -21,8 +21,8 @@ The subsystem is organised in phases (issue #566): **Phase 1** the candidate tax| `mod.rs` | Export-focused module root; phase docstrings + `pub use` re-exports. || `startup.rs` | Registers the always-on Phase 2/3/4 subscribers (signature producer, rebuild trigger + 30-min loop, `ProfileMdRenderer`) on the global event bus; idempotent, `OnceLock`-guarded (#5003). || `candidate.rs` | Phase 1 taxonomy re-exported from the contract crate (`tinymemory_api::learning::{FacetClass, CueFamily, LearningCandidate}`, `tinymemory_api::host::EvidenceRef`), plus the bounded FIFO `Buffer` with a `global()` singleton (cap 1024). |-| `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`. |+| `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` + `schemas/` | `schemas.rs` holds the controller schema list and `RegisteredController` table; `schemas/profile_handlers.rs` has the `linkedin_enrichment` / `save_profile` / `rebuild_cache` / `cache_stats` handlers, `schemas/cache_helpers.rs` has the `get_cache()` helper, and `schemas/facet_handlers.rs` has 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). |@@ -30,7 +30,7 @@ The subsystem is organised in phases (issue #566): **Phase 1** the candidate tax| `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`), `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. |+| `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` + `linkedin_enrichment/` | Gmail→LinkedIn→Apify enrichment pipeline: `linkedin_enrichment.rs` (`run_linkedin_enrichment`), `linkedin_enrichment/gmail_discovery.rs` (`scrape_linkedin_profile`), `linkedin_enrichment/profile_markdown.rs` (`summarise_profile_with_llm`, `render_profile_markdown`), and `linkedin_enrichment/memory_persistence.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). |@@ -91,30 +91,30 @@ These are subscriber registrations rather than a single `bus.rs`; subscriptions## Persistence-- **`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, … }`.+- **`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/memory_persistence.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_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.-- `tinyagents_session::transcript` — `SessionTranscript` parsing for transcript ingestion.+- `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.+- `tinyagents_session::transcript`: `SessionTranscript` parsing for transcript ingestion.- `crate::inference::provider::create_chat_model_from_string_with_model_id` (profile summarisation) and `crate::inference::host_runtime::global` (local reflection route); `ReflectionHook` also accepts an optional `tinyinference_llm::model::ChatModel` for the cloud fallback.-- `crate::config` — `Config` / `LearningConfig` / `ReflectionSource` feature flags and `config::rpc` loader.-- `crate::agent::prompts` — `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`).-- `crate::integrations` — `build_client` / `IntegrationClient` for the Apify scrape call.-- `crate::core::bus` / `crate::core::events` / `tinybus` — `BUS.publish` / `BUS.subscribe`, `DomainEvent::CacheRebuilt`, and `tinybus::{EventHandler, SubscriptionHandle}`.-- `crate::core::all` / `crate::rpc` — controller registry types (`RegisteredController`, `ControllerFuture`) and `RpcOutcome` (the latter re-exported from the `openhuman-rpc` crate via `pub use openhuman_rpc as rpc` in `lib.rs`).+- `crate::config`: `Config` / `LearningConfig` / `ReflectionSource` feature flags and `config::rpc` loader.+- `crate::agent::prompts`: `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`).+- `crate::integrations`: `build_client` / `IntegrationClient` for the Apify scrape call.+- `crate::core::bus` / `crate::core::events` / `tinybus`: `BUS.publish` / `BUS.subscribe`, `DomainEvent::CacheRebuilt`, and `tinybus::{EventHandler, SubscriptionHandle}`.+- `crate::core::all` / `crate::rpc`: controller registry types (`RegisteredController`, `ControllerFuture`) and `RpcOutcome` (the latter re-exported from the `openhuman-rpc` crate via `pub use openhuman_rpc as rpc` in `lib.rs`).## Used by-- `crates/openhuman-core/src/core/all.rs` — registers the `learning.*` controllers + schemas.+- `crates/openhuman-core/src/core/all.rs`: registers the `learning.*` controllers + schemas.- `crates/openhuman-core/src/agent/session_host/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/background_tasks.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/people_chunks_retrieval.rs` (`impl MemoryProfile for ModuleMemoryProvider`, the driver `FacetCache` reaches through the guard), `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.+- `crates/openhuman-core/src/modules/memory/people_chunks_retrieval.rs` (`impl MemoryProfile for ModuleMemoryProvider`, the driver `FacetCache` reaches through the guard), `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`.-- **`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).+- **`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.+- **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.+- The `profile_md_renderer` deliberately does **not** touch the `connected-accounts` block, that's owned by the Composio provider path.diff --git a/crates/openhuman-core/src/config/ops/README.md b/crates/openhuman-core/src/config/ops/README.mdindex 0bfab96fd6..be7c804476 100644--- a/crates/openhuman-core/src/config/ops/README.md+++ b/crates/openhuman-core/src/config/ops/README.md@@ -80,7 +80,7 @@ TinySearch module is refreshed with a private configuration payload.lock and delegates to `apply_autonomy_settings`, so the same reloadhappens. `apply_agent_paths_settings` calls`crate::security::live_policy::set_action_dir` when `action_dir` changes.- Do not weaken these settings mutators — they gate the same autonomy+ Do not weaken these settings mutators; they gate the same autonomyinvariants AGENTS.md requires of `security/`.- `apply_privacy_settings` calls `crate::security::live_policy::reload_privacy`after saving, so the inference chokepoint enforces the new Privacy Modediff --git a/crates/openhuman-core/src/desktop/app_state/README.md b/crates/openhuman-core/src/desktop/app_state/README.mdindex b8537ff5e6..daf4feb4ce 100644--- a/crates/openhuman-core/src/desktop/app_state/README.md+++ b/crates/openhuman-core/src/desktop/app_state/README.md@@ -1,8 +1,8 @@# App State-Aggregator that the React shell polls every few seconds (`openhuman.app_state_snapshot`) to render the OS-level chrome: the stored credential and user, local-AI status, service health, onboarding tasks, keyring status, config-recovery notice. Owns the on-disk `app-state.json` and the merge/patch surface for shell-managed local fields. Does NOT own any of the underlying domain state — it assembles snapshots from peer domains and persists shell-side onboarding metadata.+Aggregator that the React shell polls every few seconds (`openhuman.app_state_snapshot`) to render the OS-level chrome: the stored credential and user, local-AI status, service health, onboarding tasks, keyring status, config-recovery notice. Owns the on-disk `app-state.json` and the merge/patch surface for shell-managed local fields. Does NOT own any of the underlying domain state, it assembles snapshots from peer domains and persists shell-side onboarding metadata.-The snapshot never talks to the backend. The user it reports is the payload the host handed the core with `auth.set_credential` (the host's own `/auth/me` answer); the *live* current user is the session owner's business — the Tauri shell's session cache (`openhuman_tinyhumans::session::CurrentUserCache`) — and the frontend merges it in (`app/src/services/coreStateApi.ts`).+The snapshot never talks to the backend. The user it reports is the payload the host handed the core with `auth.set_credential` (the host's own `/auth/me` answer); the *live* current user is the session owner's business, the Tauri shell's session cache (`openhuman_tinyhumans::session::CurrentUserCache`), and the frontend merges it in (`app/src/services/coreStateApi.ts`).## Key files@@ -20,30 +20,30 @@ The snapshot never talks to the backend. The user it reports is the payload the## Public surface-- `AppStateSnapshot` — composite payload: `auth` (`AuthStateResponse`: `isAuthenticated`, `userId`, `user`, `profileId`, `credential`, `expiresAt`), `session_token`, `current_user` (= `auth.user`), `onboarding_completed`, `chat_onboarding_completed`, `analytics_enabled`, `local_state`, `keyring_status`, `runtime` (`RuntimeSnapshot { local_ai: LocalAiStatus, service: ServiceStatus }`), `health`, `config_recovered`.-- `StoredAppState` — disk schema persisted to `<workspace_dir>/state/app-state.json` (`encryption_key`, `onboarding_tasks`, `keyring_consent`). `StoredOnboardingTasks` holds the shell-tracked onboarding flags plus `enabled_tools` and `connected_sources`.-- `StoredAppStatePatch` — partial update (`Option<Option<_>>` per field) applied by `update_local_state`.-- `pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String>` — full snapshot; one auth-profile load per call, no network.-- `pub async fn update_local_state(StoredAppStatePatch) -> Result<RpcOutcome<StoredAppState>, String>` — merge under `APP_STATE_FILE_LOCK` and save atomically.-- `pub(crate) fn load_stored_app_state(&Config)` / `pub fn save_app_state(&Config, &StoredAppState)` — direct disk access; a corrupt file is renamed to `app-state.json.corrupted.<ts>` and replaced with defaults.-- `latch_from_config(&Config)` / `config_recovered_this_session()` — recovery latch.+- `AppStateSnapshot`: composite payload: `auth` (`AuthStateResponse`: `isAuthenticated`, `userId`, `user`, `profileId`, `credential`, `expiresAt`), `session_token`, `current_user` (= `auth.user`), `onboarding_completed`, `chat_onboarding_completed`, `analytics_enabled`, `local_state`, `keyring_status`, `runtime` (`RuntimeSnapshot { local_ai: LocalAiStatus, service: ServiceStatus }`), `health`, `config_recovered`.+- `StoredAppState`: disk schema persisted to `<workspace_dir>/state/app-state.json` (`encryption_key`, `onboarding_tasks`, `keyring_consent`). `StoredOnboardingTasks` holds the shell-tracked onboarding flags plus `enabled_tools` and `connected_sources`.+- `StoredAppStatePatch`: partial update (`Option<Option<_>>` per field) applied by `update_local_state`.+- `pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String>`: full snapshot; one auth-profile load per call, no network.+- `pub async fn update_local_state(StoredAppStatePatch) -> Result<RpcOutcome<StoredAppState>, String>`: merge under `APP_STATE_FILE_LOCK` and save atomically.+- `pub(crate) fn load_stored_app_state(&Config)` / `pub fn save_app_state(&Config, &StoredAppState)`: direct disk access; a corrupt file is renamed to `app-state.json.corrupted.<ts>` and replaced with defaults.+- `latch_from_config(&Config)` / `config_recovered_this_session()`: recovery latch.- RPC `app_state.{snapshot, update_local_state}` via `all_app_state_controller_schemas` / `all_app_state_registered_controllers`.The signed-in identity for prompts and Sentry is `security::credentials::identity::peek_credential_user_identity()`, seeded from the same stored payload.## Calls into-- `crate::config` — `config::rpc::load_config_with_timeout`.-- `crate::security::credentials` — `session_support::{load_app_session_profile, session_state_from_profile, session_token_from_profile}`; `crate::security::keyring_consent` for `KeyringStatus` / `ConsentPreference`.-- `crate::inference` — `LocalAiStatus` via `inference::rpc::inference_status`.-- `crate::platform::service` — `ServiceState` / `ServiceStatus`; `crate::platform::health::snapshot`.+- `crate::config`: `config::rpc::load_config_with_timeout`.+- `crate::security::credentials`: `session_support::{load_app_session_profile, session_state_from_profile, session_token_from_profile}`; `crate::security::keyring_consent` for `KeyringStatus` / `ConsentPreference`.+- `crate::inference`: `LocalAiStatus` via `inference::rpc::inference_status`.+- `crate::platform::service`: `ServiceState` / `ServiceStatus`; `crate::platform::health::snapshot`.## Called by-- `crates/openhuman-core/src/core/all.rs` — registers `all_app_state_registered_controllers()`; the shell reaches them through `coreRpcClient` → `relay_http_rpc`.-- `crates/openhuman-core/src/core/jsonrpc.rs` — `latch_from_config` at runtime bootstrap.-- `crates/openhuman-core/src/agent/session_host/builder/factory.rs` — `load_stored_app_state` to read `onboarding_tasks.enabled_tools` for tool filtering.-- `crates/openhuman-core/src/security/keyring_consent/ops.rs` — persists the consent choice through `update_local_state`.+- `crates/openhuman-core/src/core/all.rs`: registers `all_app_state_registered_controllers()`; the shell reaches them through `coreRpcClient` → `relay_http_rpc`.+- `crates/openhuman-core/src/core/jsonrpc.rs`: `latch_from_config` at runtime bootstrap.+- `crates/openhuman-core/src/agent/session_host/builder/factory.rs`: `load_stored_app_state` to read `onboarding_tasks.enabled_tools` for tool filtering.+- `crates/openhuman-core/src/security/keyring_consent/ops.rs`: persists the consent choice through `update_local_state`.## Testsdiff --git a/crates/openhuman-core/src/desktop/dashboard/README.md b/crates/openhuman-core/src/desktop/dashboard/README.mdindex a53a597d0c..7f1b492948 100644--- a/crates/openhuman-core/src/desktop/dashboard/README.md+++ b/crates/openhuman-core/src/desktop/dashboard/README.md@@ -1,12 +1,12 @@# dashboard-Aggregate, operator-facing views over local config. Today it owns a single read-only view: the per-model health comparison table rendered in the desktop **Settings → Developer Options → Model Health** panel. The view joins the local `Config::model_registry` with the `dashboard.model_health` thresholds and emits one row per model. Telemetry-driven metric fields (`quality_score`, `hallucination_rate`, `agents_using`, `tasks_evaluated`) are intentional placeholders (`null` / `0`) until a local telemetry pipeline lands — the placeholder contract is documented in `ops.rs` and asserted in its tests. Stateless: no persistence, no event-bus subscribers, no agent tools.+Aggregate, operator-facing views over local config. Today it owns a single read-only view: the per-model health comparison table rendered in the desktop **Settings → Developer Options → Model Health** panel. The view joins the local `Config::model_registry` with the `dashboard.model_health` thresholds and emits one row per model. Telemetry-driven metric fields (`quality_score`, `hallucination_rate`, `agents_using`, `tasks_evaluated`) are intentional placeholders (`null` / `0`) until a local telemetry pipeline lands, the placeholder contract is documented in `ops.rs` and asserted in its tests. Stateless: no persistence, no event-bus subscribers, no agent tools.## Responsibilities- Build the model health comparison response by mapping each `model_registry` entry to a `ModelHealthEntry` (id, provider, cost per 1M output tokens, vision flag).- Surface the `dashboard.model_health` thresholds (`hallucination_threshold`, `min_tasks_for_rating`, `evaluation_window_tasks`) so the frontend can compute status badges.-- Emit telemetry metric fields as explicit placeholders (`None` / `0`) — to be populated here, not at the transport layer, once telemetry exists.+- Emit telemetry metric fields as explicit placeholders (`None` / `0`), to be populated here, not at the transport layer, once telemetry exists.- Reject the request with an error when `dashboard.model_health.enabled` is `false`.- Expose the view over JSON-RPC via the controller registry.@@ -21,8 +21,8 @@ Aggregate, operator-facing views over local config. Today it owns a single read-## Public surface-- `ops::model_health` — `fn model_health(config: &Config) -> Result<RpcOutcome<ModelHealthResponse>, String>`.-- `schemas::all_dashboard_controller_schemas`, `schemas::all_dashboard_registered_controllers`, `schemas::dashboard_schemas` — controller-registry entry points.+- `ops::model_health`: `fn model_health(config: &Config) -> Result<RpcOutcome<ModelHealthResponse>, String>`.+- `schemas::all_dashboard_controller_schemas`, `schemas::all_dashboard_registered_controllers`, `schemas::dashboard_schemas`: controller-registry entry points.- `types::ModelHealthEntry`, `types::ModelHealthConfigView`, `types::ModelHealthResponse`.## RPC / controllers@@ -42,17 +42,17 @@ None. The module reads from in-memory `Config`; it stores no state.## Dependencies-- `crate::config` (`Config`, `config::rpc::load_config_with_timeout`) — source of the model registry and `dashboard.model_health` thresholds. `DashboardConfig` / `ModelHealthConfig` are defined in `crates/openhuman-core/src/config/schema/dashboard.rs`.-- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`) — controller registry types.-- `crate::rpc::RpcOutcome` — standard RPC result wrapper.-- `serde` / `serde_json` — wire (de)serialization and handler params.+- `crate::config` (`Config`, `config::rpc::load_config_with_timeout`), source of the model registry and `dashboard.model_health` thresholds. `DashboardConfig` / `ModelHealthConfig` are defined in `crates/openhuman-core/src/config/schema/dashboard.rs`.+- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`), controller registry types.+- `crate::rpc::RpcOutcome`: standard RPC result wrapper.+- `serde` / `serde_json`: wire (de)serialization and handler params.## Used by-- `crates/openhuman-core/src/core/all.rs` — registers the controller and its schema into the global RPC/CLI registry (lines ~119 and ~297).+- `crates/openhuman-core/src/core/all.rs`: registers the controller and its schema into the global RPC/CLI registry (lines ~119 and ~297).## Notes / gotchas- **Placeholder contract is load-bearing.** `quality_score` / `hallucination_rate` are always `None` and `agents_using` / `tasks_evaluated` always `0`. The frontend treats null quality/hallucination as "no signal", collapsing badges to `staging`. When telemetry lands, populate these in `ops::model_health`, not in the transport layer.- Disabled feature (`dashboard.model_health.enabled == false`) returns `Err("model health disabled")`, which the handler surfaces as an RPC error.-- This is the only view in the domain so far; `mod.rs` is intentionally export-only per the canonical module shape (no `store.rs`, `tools.rs`, or `bus.rs` — the domain is stateless, owns no agent tools, and has no event subscribers).+- This is the only view in the domain so far; `mod.rs` is intentionally export-only per the canonical module shape (no `store.rs`, `tools.rs`, or `bus.rs`: the domain is stateless, owns no agent tools, and has no event subscribers).diff --git a/crates/openhuman-core/src/desktop/notifications/README.md b/crates/openhuman-core/src/desktop/notifications/README.mdindex e5f336a95e..6f6234a884 100644--- a/crates/openhuman-core/src/desktop/notifications/README.md+++ b/crates/openhuman-core/src/desktop/notifications/README.md@@ -7,7 +7,7 @@ The notifications domain owns two complementary sub-systems. The **core-bridge**- Subscribe to cross-domain `DomainEvent`s and republish a curated subset as user-facing `CoreNotificationEvent`s (with title/body/category/deep-link) onto an in-process broadcast bus consumed by the Socket.IO bridge.- Filter noise at the bridge: only failed webhooks surface; only `routed` triage actions (`escalate`/`react`) surface; `drop`/`acknowledge`/unrouted are silent.- Ingest integration notifications, dedup against identical content received in the last 60s, and persist them immediately.-- Spawn background triage per ingest; map the triage action to a 0.0–1.0 importance score and back-fill `importance_score`/`triage_action`/`triage_reason`/`scored_at` in place.+- Spawn background triage per ingest; map the triage action to a 0.0, 1.0 importance score and back-fill `importance_score`/`triage_action`/`triage_reason`/`scored_at` in place.- Auto-route high-importance (`escalate`/`react`) notifications to the orchestrator when the provider's settings allow (re-reading settings just before routing).- Persist and expose per-provider settings (enabled, importance threshold, route-to-orchestrator).- Track lifecycle state (`unread`/`read`/`acted`/`dismissed`) and aggregate pipeline stats.@@ -38,15 +38,15 @@ Namespace `notification` (10 controllers, registered via `all_notifications_regi| Function | Inputs | Output || --- | --- | --- |-| `ingest` | `provider`, `title`, `body`, `raw_payload` (req); `account_id` (opt) | `{ id?, skipped, reason? }` — persists then spawns background triage; skips when provider disabled or duplicate. |-| `list` | `provider?`, `limit?` (50), `offset?` (0), `min_score?` | `{ items, unread_count }` — ordered `received_at` DESC; unscored items pass the score filter. |+| `ingest` | `provider`, `title`, `body`, `raw_payload` (req); `account_id` (opt) | `{ id?, skipped, reason? }`: persists then spawns background triage; skips when provider disabled or duplicate. |+| `list` | `provider?`, `limit?` (50), `offset?` (0), `min_score?` | `{ items, unread_count }`: ordered `received_at` DESC; unscored items pass the score filter. || `mark_read` | `id` | `{ ok }` || `dismiss` | `id` | `{ ok }` (true when a row matched) || `mark_acted` | `id` | `{ ok }` (true when a row matched) || `settings_get` | `provider` | `{ settings }` (defaulted if absent) |-| `settings_set` | `provider`, `enabled`, `importance_threshold`, `route_to_orchestrator` | `{ ok, settings }` — threshold clamped to 0.0–1.0. |-| `stats` | — | `{ total, unread, unscored, by_provider, by_action }` |-| `core_list` | `only_unread?` (true), `limit?` (100) | `{ items, unread_count }` — persisted core notifications (#3805), newest first; sync-down for events fired while the app was closed. |+| `settings_set` | `provider`, `enabled`, `importance_threshold`, `route_to_orchestrator` | `{ ok, settings }`: threshold clamped to 0.0, 1.0. |+| `stats` |, | `{ total, unread, unscored, by_provider, by_action }` |+| `core_list` | `only_unread?` (true), `limit?` (100) | `{ items, unread_count }`: persisted core notifications (#3805), newest first; sync-down for events fired while the app was closed. || `core_mark_read` | `id` | `{ ok }` (true when a row matched) |Schemas + handlers are wired into the controller registry in `crates/openhuman-core/src/core/all.rs`.@@ -67,7 +67,7 @@ None. This domain owns no `tools.rs`.## Events-**Subscribes** (via `NotificationBridgeSubscriber`, no `domains()` filter — matches on variant): `DomainEvent::CronJobCompleted` (→ Agents), `WebhookProcessed` (failures only → System), `SubagentCompleted`/`SubagentFailed` (→ Agents), `NotificationTriaged` (only when `routed` and action is `escalate`/`react` → Agents), `ProviderApiKeyRejected` (→ System), and `McpServerReconnectFailed`/`McpServerReconnected`/`McpServerParked` (→ System). Each is translated to a `CoreNotificationEvent`, stamped with the event's workspace handle, persisted, then published on the broadcast bus.+**Subscribes** (via `NotificationBridgeSubscriber`, no `domains()` filter, matches on variant): `DomainEvent::CronJobCompleted` (→ Agents), `WebhookProcessed` (failures only → System), `SubagentCompleted`/`SubagentFailed` (→ Agents), `NotificationTriaged` (only when `routed` and action is `escalate`/`react` → Agents), `ProviderApiKeyRejected` (→ System), and `McpServerReconnectFailed`/`McpServerReconnected`/`McpServerParked` (→ System). Each is translated to a `CoreNotificationEvent`, stamped with the event's workspace handle, persisted, then published on the broadcast bus.**Workspace gating (#5931):** a workspace-bound event is persisted under its own workspace's DB (`store_target`), and announced only when that workspace is the active one (`should_announce` → `Announce::{Unbound, Active(revision), Suppressed}`); an active-workspace event carries `workspace_revision`.@@ -79,34 +79,34 @@ The bridge bus is a separate `tokio::sync::broadcast` channel (not the global evSQLite DB at `{workspace_dir}/notifications/notifications.db`, opened per-call via `with_connection` (idempotent schema migration on each open). Three tables:-- `integration_notifications` — one row per ingested notification (id, provider, account_id, title, body, raw_payload JSON, importance_score, triage_action, triage_reason, status, received_at, scored_at). Indexed on provider, status, and a dedup tuple (provider, account_id, title, body, received_at).-- `notification_settings` — per-provider routing prefs (enabled, importance_threshold, route_to_orchestrator), upserted on `provider` PK.-- `core_notifications` — persisted bridge events keyed by event id (#3805), indexed on read state and timestamp; served by `core_list` / `core_mark_read`.+- `integration_notifications`: one row per ingested notification (id, provider, account_id, title, body, raw_payload JSON, importance_score, triage_action, triage_reason, status, received_at, scored_at). Indexed on provider, status, and a dedup tuple (provider, account_id, title, body, received_at).+- `notification_settings`: per-provider routing prefs (enabled, importance_threshold, route_to_orchestrator), upserted on `provider` PK.+- `core_notifications`: persisted bridge events keyed by event id (#3805), indexed on read state and timestamp; served by `core_list` / `core_mark_read`.`insert_if_not_recent` runs a `BEGIN IMMEDIATE` transaction so concurrent duplicate ingests collapse to a single insert.## Dependencies- `crate::core::bus::BUS` and `crate::core::events::DomainEvent` (`BUS.subscribe` for the bridge, `BUS.publish` for triage results); the `EventHandler` trait comes from `tinybus`.-- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`) — controller registry contract.-- `crate::config` — `Config` (workspace dir for the DB path), `config::rpc::load_config_with_timeout` in handlers, `active_workspace_snapshot` / `workspace_handle` for the workspace gate.-- `crate::agent::triage` — `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`, `TriggerSource`, `TriageAction` for the background scoring/routing pipeline; `crate::agent::turn_origin::with_origin` scopes the routing turn.-- `crate::rpc::RpcOutcome` — RPC response shaping.+- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`), controller registry contract.+- `crate::config`: `Config` (workspace dir for the DB path), `config::rpc::load_config_with_timeout` in handlers, `active_workspace_snapshot` / `workspace_handle` for the workspace gate.+- `crate::agent::triage`: `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`, `TriggerSource`, `TriageAction` for the background scoring/routing pipeline; `crate::agent::turn_origin::with_origin` scopes the routing turn.+- `crate::rpc::RpcOutcome`: RPC response shaping.- External crates: `rusqlite` (store), `chrono`, `uuid`, `serde_json`, `tokio`, `once_cell`, `async_trait`.## Used by-- `crates/openhuman-core/src/core/all.rs` — registers the controllers/schemas into the RPC registry.-- `crates/openhuman-core/src/core/jsonrpc.rs` — calls `register_notification_bridge_subscriber(config)` at startup when the Desktop domain group is enabled.-- `crates/openhuman-core/src/core/socketio.rs` — calls `subscribe_core_notifications()` to forward events to web clients.-- `crates/openhuman-core/src/cron/scheduler/delivery.rs` — writes cron-triggered notifications through `notifications::store` directly; `cron/scheduler_tests*.rs` list them back with `store::list`.-- `crates/openhuman-core/src/flows/ops/execution.rs` and `crates/openhuman-core/src/security/approval/gate.rs` — call `publish_core_notification` directly to surface flow and approval events.+- `crates/openhuman-core/src/core/all.rs`: registers the controllers/schemas into the RPC registry.+- `crates/openhuman-core/src/core/jsonrpc.rs`: calls `register_notification_bridge_subscriber(config)` at startup when the Desktop domain group is enabled.+- `crates/openhuman-core/src/core/socketio.rs`: calls `subscribe_core_notifications()` to forward events to web clients.+- `crates/openhuman-core/src/cron/scheduler/delivery.rs`: writes cron-triggered notifications through `notifications::store` directly; `cron/scheduler_tests*.rs` list them back with `store::list`.+- `crates/openhuman-core/src/flows/ops/execution.rs` and `crates/openhuman-core/src/security/approval/gate.rs`: call `publish_core_notification` directly to surface flow and approval events.## Notes / gotchas- `CoreNotificationEvent` ids embed a publish timestamp, so each cron run / webhook failure / subagent event produces a distinct notification-center entry rather than coalescing.- `CoreNotificationCategory` must stay in sync with `NotificationCategory` in `app/src/store/notificationSlice.ts`.-- The ingest RPC returns immediately; triage runs in a spawned task and back-fills the score later — list/stats may show `importance_score: null` (unscored) until triage completes.+- The ingest RPC returns immediately; triage runs in a spawned task and back-fills the score later, list/stats may show `importance_score: null` (unscored) until triage completes.- Triage→score mapping is a fixed heuristic in `rpc::triage_action_to_score`: Drop 0.1, Acknowledge 0.35, React 0.65, Escalate 0.9.- Routing re-reads provider settings just before escalation so a mid-flight settings toggle takes effect; routing requires `score >= importance_threshold` AND `route_to_orchestrator`.- Dedup window is a hard-coded 60 seconds (`exists_recent` / `insert_if_not_recent`).diff --git a/crates/openhuman-core/src/desktop/overlay/README.md b/crates/openhuman-core/src/desktop/overlay/README.mdindex 3f993be94d..b23d8f1ff5 100644--- a/crates/openhuman-core/src/desktop/overlay/README.md+++ b/crates/openhuman-core/src/desktop/overlay/README.md@@ -1,13 +1,13 @@# overlay-Signals pushed from the core to the desktop **overlay surfaces** — separate WebViews (`app/src/overlay/OverlayApp.tsx` and the macOS notch pill `app/src/notch/NotchApp.tsx`, hosted by `crates/openhuman-app/src/notch_window.rs`) that render short, non-focus-stealing messages over the desktop. The standalone `overlay` window is currently disabled in `crates/openhuman-app/tauri.conf.json`; the notch is the live consumer. Because these surfaces run in their own JS runtime they cannot share Redux state with the main window; each subscribes to its own Socket.IO connection and reacts to events the core broadcasts. This module owns a single fire-and-forget broadcast bus for **attention** events; the Socket.IO transport bridge (`crates/openhuman-core/src/core/socketio.rs`) subscribes and forwards them. It is deliberately light: export-focused, one broadcast channel, no persistence and no RPC.+Signals pushed from the core to the desktop **overlay surfaces**, separate WebViews (`app/src/overlay/OverlayApp.tsx` and the macOS notch pill `app/src/notch/NotchApp.tsx`, hosted by `crates/openhuman-app/src/notch_window.rs`) that render short, non-focus-stealing messages over the desktop. The standalone `overlay` window is currently disabled in `crates/openhuman-app/tauri.conf.json`; the notch is the live consumer. Because these surfaces run in their own JS runtime they cannot share Redux state with the main window; each subscribes to its own Socket.IO connection and reacts to events the core broadcasts. This module owns a single fire-and-forget broadcast bus for **attention** events; the Socket.IO transport bridge (`crates/openhuman-core/src/core/socketio.rs`) subscribes and forwards them. It is deliberately light: export-focused, one broadcast channel, no persistence and no RPC.## Responsibilities- Define the `OverlayAttentionEvent` payload and its `OverlayAttentionTone` visual hint.- Provide a process-global broadcast channel so any core caller can surface a transient overlay message without threading a sender around.- Expose `publish_attention` (fire-and-forget producer) and `subscribe_attention_events` (consumed by the Socket.IO bridge).-- (STT/dictation overlay activation is driven separately by `voice::dictation_listener`'s `dictation:toggle` / `dictation:transcription` events — not by this module.)+- (STT/dictation overlay activation is driven separately by `voice::dictation_listener`'s `dictation:toggle` / `dictation:transcription` events, not by this module.)## Key files@@ -19,10 +19,10 @@ Signals pushed from the core to the desktop **overlay surfaces** — separate We## Public surface-- `OverlayAttentionEvent` — `{ id: Option<String>, message: String, tone: OverlayAttentionTone, ttl_ms: Option<u32>, source: Option<String> }`. Builders: `new(message)`, `with_source(..)`, `with_tone(..)`, `with_ttl_ms(..)`. Only `message` is required.-- `OverlayAttentionTone` — `Neutral` (default), `Accent`, `Success`; serialized lowercase. Frontend maps to bubble colours.-- `publish_attention(event) -> usize` — broadcasts; returns the number of active subscribers that received it (`0` if none, event then dropped). Logs under `[overlay]`.-- `subscribe_attention_events() -> broadcast::Receiver<OverlayAttentionEvent>` — receiver for the bus.+- `OverlayAttentionEvent`: `{ id: Option<String>, message: String, tone: OverlayAttentionTone, ttl_ms: Option<u32>, source: Option<String> }`. Builders: `new(message)`, `with_source(..)`, `with_tone(..)`, `with_ttl_ms(..)`. Only `message` is required.+- `OverlayAttentionTone`: `Neutral` (default), `Accent`, `Success`; serialized lowercase. Frontend maps to bubble colours.+- `publish_attention(event) -> usize`: broadcasts; returns the number of active subscribers that received it (`0` if none, event then dropped). Logs under `[overlay]`.+- `subscribe_attention_events() -> broadcast::Receiver<OverlayAttentionEvent>`: receiver for the bus.## Events@@ -38,13 +38,13 @@ None. State is purely an in-memory broadcast channel; events not consumed when p## Used by-- `crates/openhuman-core/src/core/socketio.rs` — subscribes to the bus and forwards events to the overlay WebView over Socket.IO.-- `crates/openhuman-core/src/voice/always_on/processor.rs` — `notch_status` publishes "Listening" / "Processing" status messages (`source: "voice"`, with a TTL) that the notch maps to icons. The only in-tree publisher today.-- `crates/openhuman-core/src/desktop/notifications/bus.rs` — references this module's bus only as a documented pattern to mirror (no code dependency).+- `crates/openhuman-core/src/core/socketio.rs`: subscribes to the bus and forwards events to the overlay WebView over Socket.IO.+- `crates/openhuman-core/src/voice/always_on/processor.rs`: `notch_status` publishes "Listening" / "Processing" status messages (`source: "voice"`, with a TTL) that the notch maps to icons. The only in-tree publisher today.+- `crates/openhuman-core/src/desktop/notifications/bus.rs`: references this module's bus only as a documented pattern to mirror (no code dependency).## Notes / gotchas- **Fire-and-forget:** if the Socket.IO bridge hasn't started or the overlay socket is disconnected, `publish_attention` drops the event and returns `0`. There is no buffering/replay for late subscribers.-- **Channel capacity is 64** — a slow/absent overlay consumer causes `Lagged` drops (logged as a warning by the bridge), not back-pressure.+- **Channel capacity is 64**, a slow/absent overlay consumer causes `Lagged` drops (logged as a warning by the bridge), not back-pressure.- Keep `message` short: the overlay types it out character-by-character and auto-dismisses after `ttl_ms` (frontend default when `None`). The notch treats the literal messages `Listening` and `Processing` as reserved status words.- The bridge emits two event names (`overlay:attention` and `overlay_attention`) for client compatibility.diff --git a/crates/openhuman-core/src/desktop/provider_surfaces/README.md b/crates/openhuman-core/src/desktop/provider_surfaces/README.mdindex e13bde2a41..a97aa2339d 100644--- a/crates/openhuman-core/src/desktop/provider_surfaces/README.md+++ b/crates/openhuman-core/src/desktop/provider_surfaces/README.md@@ -22,11 +22,11 @@ Local assistive surfaces for third-party provider apps. This domain owns a norma## Public surface-- `types::ProviderEvent` — inbound normalized provider event (`#[serde(deny_unknown_fields)]`).-- `types::RespondQueueItem` — queue entry (adds `id` and `status`, default `"pending"`).-- `types::RespondQueueListResponse` — `{ items, count }`.-- `ops::ingest_event(ProviderEvent)` / `ops::list_queue(EmptyRequest)` — async handlers returning `RpcOutcome<ApiEnvelope<T>>`.-- `store::{upsert_queue_item, list_queue_items}` — internal to `ops.rs`; no external caller reads the store directly today.+- `types::ProviderEvent`: inbound normalized provider event (`#[serde(deny_unknown_fields)]`).+- `types::RespondQueueItem`: queue entry (adds `id` and `status`, default `"pending"`).+- `types::RespondQueueListResponse`: `{ items, count }`.+- `ops::ingest_event(ProviderEvent)` / `ops::list_queue(EmptyRequest)`: async handlers returning `RpcOutcome<ApiEnvelope<T>>`.+- `store::{upsert_queue_item, list_queue_items}`: internal to `ops.rs`; no external caller reads the store directly today.- Re-exported from `mod.rs`: `all_provider_surfaces_controller_schemas`, `all_provider_surfaces_registered_controllers`.## RPC / controllers@@ -42,27 +42,27 @@ Namespace `provider_surfaces` (two controllers, registered via `crates/openhuman## Agent tools-None — no `tools.rs`; this domain owns no agent tools.+None, no `tools.rs`; this domain owns no agent tools.## Events-None — no `bus.rs`; no `DomainEvent`s published or subscribed.+None, no `bus.rs`; no `DomainEvent`s published or subscribed.## Persistence-In-memory only. State lives in a process-global `RESPOND_QUEUE` (`static OnceLock<Mutex<Vec<RespondQueueItem>>>`) in `store.rs`, prepend-ordered (newest-first), soft-capped at `MAX_QUEUE_ITEMS = 500` (oldest dropped from the tail). Upsert dedupes by composite id `provider:account_id:event_kind:entity_id`. Module docstrings flag SQLite-backed persistence for normalized events, queue state, and local drafts as follow-up work — not yet present.+In-memory only. State lives in a process-global `RESPOND_QUEUE` (`static OnceLock<Mutex<Vec<RespondQueueItem>>>`) in `store.rs`, prepend-ordered (newest-first), soft-capped at `MAX_QUEUE_ITEMS = 500` (oldest dropped from the tail). Upsert dedupes by composite id `provider:account_id:event_kind:entity_id`. Module docstrings flag SQLite-backed persistence for normalized events, queue state, and local drafts as follow-up work, not yet present.## Dependencies-- `crate::memory` — `ApiEnvelope`, `ApiMeta`, `EmptyRequest` (response envelope shape + empty-request type).-- `crate::rpc::RpcOutcome` — RPC return contract.-- `crate::core::all` — `RegisteredController`, `ControllerFuture` (controller registry wiring).-- `crate::core::{ControllerSchema, FieldSchema, TypeSchema}` — controller schema types.+- `crate::memory`: `ApiEnvelope`, `ApiMeta`, `EmptyRequest` (response envelope shape + empty-request type).+- `crate::rpc::RpcOutcome`: RPC return contract.+- `crate::core::all`: `RegisteredController`, `ControllerFuture` (controller registry wiring).+- `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller schema types.- External crates: `serde` / `serde_json`, `uuid` (request ids), `tracing` (debug logging with `[provider-surfaces]` prefix).## Used by-- `crates/openhuman-core/src/core/all.rs` — pushes `all_provider_surfaces_registered_controllers()` into the registry under `DomainGroup::Desktop` (schemas are read off each registered controller, so `all_provider_surfaces_controller_schemas` has no external caller) and carries a `"provider_surfaces"` arm in the namespace-description match. No other in-tree caller.+- `crates/openhuman-core/src/core/all.rs`: pushes `all_provider_surfaces_registered_controllers()` into the registry under `DomainGroup::Desktop` (schemas are read off each registered controller, so `all_provider_surfaces_controller_schemas` has no external caller) and carries a `"provider_surfaces"` arm in the namespace-description match. No other in-tree caller.## Notes / gotchasdiff --git a/crates/openhuman-core/src/flows/README.md b/crates/openhuman-core/src/flows/README.mdindex f834c7476c..2d774c4393 100644--- a/crates/openhuman-core/src/flows/README.md+++ b/crates/openhuman-core/src/flows/README.md@@ -1,6 +1,6 @@# Flows-Saved automation workflows — the graphs a user builds on the canvas or the+Saved automation workflows, the graphs a user builds on the canvas or thecopilot builds for them. Owns CRUD/enable/run/resume/cancel for saved flows,the trigger → run bridge, the authoring tools (propose/create/edit/validate/dry-run/save), and discovery/suggestion tools. Does NOT own the workflow engine itself: `tinyflows` (vendored) owns@@ -15,12 +15,12 @@ in-crate under `vendor/tinyflows/crates/tinyflows/src/graph/`), and[`tinyflows/README.md`](tinyflows/README.md) for the capability seam; thisfile is the directory map.-## Gate shape — leaf, not facade+## Gate shape, leaf, not facadeThe whole family (`flows` + `flows::tinyflows`) is gated at `pub mod flows;`in `crates/openhuman-core/src/lib.rs` behind `#[cfg(feature = "flows")]`, andevery submodule inherits that gate. There is deliberately **no `stub.rs`**:-every symbol reached from outside is a registration site —+every symbol reached from outside is a registration site,`core::all::all_flows_registered_controllers`, `core::jsonrpc`'s`FlowTriggerSubscriber`, `core::runtime::services`' boot reconcile(`sweep_orphaned_running_runs_on_boot`, `reconcile_schedule_triggers_on_boot`),@@ -34,36 +34,36 @@ from always-compiled code.## Public surface-- `pub mod ops` (split into submodules under `ops/`, e.g. `ops/execution.rs`, `ops/resume.rs`, `ops/builder.rs`, `ops/triggers.rs`, `ops/drafts.rs`, `ops/discovery.rs`, `ops/wiring_warnings.rs`, `ops/inference_readiness.rs`) — CRUD (`flows_create/get/list/update/delete/duplicate/import/validate`), revision history (`flows_get_history`, `flows_rollback`), run lifecycle (`flows_run`, `flows_run_detached`, `flows_resume`, `flows_cancel_run`, `flows_list_runs`, `flows_list_all_runs`, `flows_get_run`, `flows_prune_runs`), `flows_set_enabled` (only `schedule` triggers need an enable-time binding — `cron::add_flow_schedule_job` / `cron::remove_job`; `app_event` flows are matched at dispatch time against enabled flows, and `webhook` binding is logged as not implemented), builder (`flows_build`, `flows_build_cancel`, `flows_search_tool_catalog`, `flows_get_tool_contract`, `flows_list_connections`, `flows_required_connections`, `flows_approval_manifest`), discovery (`flows_discover`, `flows_list_suggestions`, `flows_dismiss_suggestion`, `flows_mark_suggestion_built`), drafts (`flows_draft_create/get/update/list/delete/promote`), and boot/periodic reconciliation (`sweep_orphaned_running_runs_on_boot`, `reconcile_schedule_triggers_on_boot`, `sweep_expired_parked_runs`).-- `pub mod bus` (split into `bus/trigger.rs`, `bus/run_digest.rs`, `bus/dedup_commit.rs`) — three subscribers, all constructed in `core/jsonrpc.rs`: `FlowTriggerSubscriber` (the trigger → run bridge: `DomainEvent::FlowScheduleTick` and `ComposioTriggerReceived` are matched against enabled flows' trigger nodes and spawn `ops::flows_run`; `WebhookIncomingRequest` is observed and logged only — webhook dispatch is not implemented), `FlowRunDigestSubscriber` (on a successful `FlowRunFinished`, writes a run digest into the flow's private memory namespace), and `DedupCommitSubscriber` (on `FlowRunFinished`, commits or rolls back every `dedup` node's tentative key set). `extract_trigger_kind` / `extract_trigger_config` are reused by `ops` to decide what `flows_set_enabled` and `flows_update` must bind or rebind.-- `pub mod catalogue` — lists saved flows as `Workflow` entries with `WorkflowScope::Flow` in the shared skill catalogue, so `skill_search` sees one list instead of skills and flows separately.-- `pub mod node_contracts` — host overlay on `tinyflows::catalog`'s node-kind contracts: attaches host-specific facts (which `tool_call` slugs resolve to Composio vs. native `oh:` tools, which trigger kinds actually dispatch here) without touching the portable contracts. Re-exports `all_node_kind_contracts`, `node_kind_contract`, `NODE_KINDS`, `ConfigField`, `PortSpec`, `NodeKindContract`.-- `mod store` / `mod draft_store` (private) — bind `tinyflows_sqlite::flows` / `tinyflows_sqlite::drafts` to `<workspace_dir>/flows`; `kv_get`, `kv_set`, and `upsert_flow_run_step` are re-exported from `store` for the `tinyflows::caps::FlowStateStore` seam and the run observer.-- `mod schemas` (private; `all_flows_controller_schemas` / `all_flows_registered_controllers` re-exported) — RPC/CLI controller surface under the `flows` namespace, 36 functions. The `ControllerSchema` lookups are split into `schemas/definition_schemas.rs` (`create`, `duplicate`, `validate`, `import`, `get`, `list`, `list_connections`, `update`, `delete`, `set_enabled`, `get_history`, `rollback`, `required_connections`, `approval_manifest`), `schemas/run_schemas.rs` (`run`, `run_detached`, `resume`, `cancel_run`, `list_runs`, `list_all_runs`, `get_run`, `prune_runs`), `schemas/builder_schemas.rs` (`build`, `build_cancel`, `search_tool_catalog`, `get_tool_contract`, `discover`, `list_suggestions`, `dismiss_suggestion`, `mark_suggestion_built`), and `schemas/draft_schemas.rs` (`draft_create/get/update/list/delete/promote`); all 36 `handle_*` thin handlers live in `schemas_handlers.rs`.-- `pub mod tools` — `ProposeWorkflowTool`, `RunFlowTool`. All 27 tool structs below are re-exported by glob from `crates/openhuman-core/src/tools/mod.rs` and pushed onto the agent tool list in `tools/ops.rs` under `#[cfg(feature = "flows")]`.-- `pub mod builder_tools` (split into submodules under `builder_tools/`: `draft_revise.rs`, `draft_edit.rs`, `draft_validate.rs`, `flow_reads.rs`, `run_control.rs`, `persistence.rs`, `connection_reads.rs`, `catalog_search.rs`, `tool_contract.rs`, `kind_reads.rs`, `dry_run.rs`, `dry_run_diagnostics.rs`) — the authoring toolset: `ReviseWorkflowTool`, `EditWorkflowTool`, `ValidateWorkflowTool`, `GetFlowHistoryTool`, `ListFlowRunsTool`, `ResumeFlowRunTool`, `CancelFlowRunTool`, `CreateWorkflowTool`, `DuplicateFlowTool`, `ListConnectableToolkitsTool`, `ListFlowsTool`, `GetFlowTool`, `GetFlowRunTool`, `ListFlowConnectionsTool`, `SearchToolCatalogTool`, `GetToolContractTool`, `GetToolOutputSampleTool`, `ListAgentDefinitionsTool`, `ListNodeKindsTool`, `GetNodeKindContractTool`, `DryRunWorkflowTool`, `SaveWorkflowTool`.-- `pub mod discovery_tools` — `SuggestWorkflowsTool`.-- `pub mod memory_tools` — `FlowMemoryRecallTool`, `FlowMemoryRememberTool`, plus `flow_namespace` / `FLOW_MEMORY_NAMESPACE_PREFIX` / `cross_flow_recall` (re-exported from `mod.rs` because the tinyflows `memory` node's `OpenHumanMemory` adapter needs byte-identical `scope: "flows"` results).-- `pub mod agents` — first-class built-in sub-agents: `workflow_builder` (authoring copilot) and `flow_discovery` (read-only suggestion scout); their `agent.toml` and `prompt::build` are referenced by path from the `BUILTINS` slice in `agent/registry/agents/loader.rs`.-- `pub mod skills` (needs both `flows` and `skills` features) — registers the portable `tinyflows-copilot` `flow-authoring` manual with OpenHuman's native skill runtime.-- `pub mod tinyflows` — the capability seam (`caps/`) implementing `tinyflows`'s traits over real OpenHuman services, plus `observability.rs` (`FlowRunObserver`), `memory_adapter.rs` (`OpenHumanMemory`), and `langfuse_export.rs`. Has its own [README](tinyflows/README.md).+- `pub mod ops` (split into submodules under `ops/`, e.g. `ops/execution.rs`, `ops/resume.rs`, `ops/builder.rs`, `ops/triggers.rs`, `ops/drafts.rs`, `ops/discovery.rs`, `ops/wiring_warnings.rs`, `ops/inference_readiness.rs`), CRUD (`flows_create/get/list/update/delete/duplicate/import/validate`), revision history (`flows_get_history`, `flows_rollback`), run lifecycle (`flows_run`, `flows_run_detached`, `flows_resume`, `flows_cancel_run`, `flows_list_runs`, `flows_list_all_runs`, `flows_get_run`, `flows_prune_runs`), `flows_set_enabled` (only `schedule` triggers need an enable-time binding, `cron::add_flow_schedule_job` / `cron::remove_job`; `app_event` flows are matched at dispatch time against enabled flows, and `webhook` binding is logged as not implemented), builder (`flows_build`, `flows_build_cancel`, `flows_search_tool_catalog`, `flows_get_tool_contract`, `flows_list_connections`, `flows_required_connections`, `flows_approval_manifest`), discovery (`flows_discover`, `flows_list_suggestions`, `flows_dismiss_suggestion`, `flows_mark_suggestion_built`), drafts (`flows_draft_create/get/update/list/delete/promote`), and boot/periodic reconciliation (`sweep_orphaned_running_runs_on_boot`, `reconcile_schedule_triggers_on_boot`, `sweep_expired_parked_runs`).+- `pub mod bus` (split into `bus/trigger.rs`, `bus/run_digest.rs`, `bus/dedup_commit.rs`), three subscribers, all constructed in `core/jsonrpc.rs`: `FlowTriggerSubscriber` (the trigger → run bridge: `DomainEvent::FlowScheduleTick` and `ComposioTriggerReceived` are matched against enabled flows' trigger nodes and spawn `ops::flows_run`; `WebhookIncomingRequest` is observed and logged only, webhook dispatch is not implemented), `FlowRunDigestSubscriber` (on a successful `FlowRunFinished`, writes a run digest into the flow's private memory namespace), and `DedupCommitSubscriber` (on `FlowRunFinished`, commits or rolls back every `dedup` node's tentative key set). `extract_trigger_kind` / `extract_trigger_config` are reused by `ops` to decide what `flows_set_enabled` and `flows_update` must bind or rebind.+- `pub mod catalogue`: lists saved flows as `Workflow` entries with `WorkflowScope::Flow` in the shared skill catalogue, so `skill_search` sees one list instead of skills and flows separately.+- `pub mod node_contracts`: host overlay on `tinyflows::catalog`'s node-kind contracts: attaches host-specific facts (which `tool_call` slugs resolve to Composio vs. native `oh:` tools, which trigger kinds actually dispatch here) without touching the portable contracts. Re-exports `all_node_kind_contracts`, `node_kind_contract`, `NODE_KINDS`, `ConfigField`, `PortSpec`, `NodeKindContract`.+- `mod store` / `mod draft_store` (private), bind `tinyflows_sqlite::flows` / `tinyflows_sqlite::drafts` to `<workspace_dir>/flows`; `kv_get`, `kv_set`, and `upsert_flow_run_step` are re-exported from `store` for the `tinyflows::caps::FlowStateStore` seam and the run observer.+- `mod schemas` (private; `all_flows_controller_schemas` / `all_flows_registered_controllers` re-exported), RPC/CLI controller surface under the `flows` namespace, 36 functions. The `ControllerSchema` lookups are split into `schemas/definition_schemas.rs` (`create`, `duplicate`, `validate`, `import`, `get`, `list`, `list_connections`, `update`, `delete`, `set_enabled`, `get_history`, `rollback`, `required_connections`, `approval_manifest`), `schemas/run_schemas.rs` (`run`, `run_detached`, `resume`, `cancel_run`, `list_runs`, `list_all_runs`, `get_run`, `prune_runs`), `schemas/builder_schemas.rs` (`build`, `build_cancel`, `search_tool_catalog`, `get_tool_contract`, `discover`, `list_suggestions`, `dismiss_suggestion`, `mark_suggestion_built`), and `schemas/draft_schemas.rs` (`draft_create/get/update/list/delete/promote`); all 36 `handle_*` thin handlers live in `schemas_handlers.rs`.+- `pub mod tools`: `ProposeWorkflowTool`, `RunFlowTool`. All 27 tool structs below are re-exported by glob from `crates/openhuman-core/src/tools/mod.rs` and pushed onto the agent tool list in `tools/ops.rs` under `#[cfg(feature = "flows")]`.+- `pub mod builder_tools` (split into submodules under `builder_tools/`: `draft_revise.rs`, `draft_edit.rs`, `draft_validate.rs`, `flow_reads.rs`, `run_control.rs`, `persistence.rs`, `connection_reads.rs`, `catalog_search.rs`, `tool_contract.rs`, `kind_reads.rs`, `dry_run.rs`, `dry_run_diagnostics.rs`), the authoring toolset: `ReviseWorkflowTool`, `EditWorkflowTool`, `ValidateWorkflowTool`, `GetFlowHistoryTool`, `ListFlowRunsTool`, `ResumeFlowRunTool`, `CancelFlowRunTool`, `CreateWorkflowTool`, `DuplicateFlowTool`, `ListConnectableToolkitsTool`, `ListFlowsTool`, `GetFlowTool`, `GetFlowRunTool`, `ListFlowConnectionsTool`, `SearchToolCatalogTool`, `GetToolContractTool`, `GetToolOutputSampleTool`, `ListAgentDefinitionsTool`, `ListNodeKindsTool`, `GetNodeKindContractTool`, `DryRunWorkflowTool`, `SaveWorkflowTool`.+- `pub mod discovery_tools`: `SuggestWorkflowsTool`.+- `pub mod memory_tools`: `FlowMemoryRecallTool`, `FlowMemoryRememberTool`, plus `flow_namespace` / `FLOW_MEMORY_NAMESPACE_PREFIX` / `cross_flow_recall` (re-exported from `mod.rs` because the tinyflows `memory` node's `OpenHumanMemory` adapter needs byte-identical `scope: "flows"` results).+- `pub mod agents`: first-class built-in sub-agents: `workflow_builder` (authoring copilot) and `flow_discovery` (read-only suggestion scout); their `agent.toml` and `prompt::build` are referenced by path from the `BUILTINS` slice in `agent/registry/agents/loader.rs`.+- `pub mod skills` (needs both `flows` and `skills` features), registers the portable `tinyflows-copilot` `flow-authoring` manual with OpenHuman's native skill runtime.+- `pub mod tinyflows`: the capability seam (`caps/`) implementing `tinyflows`'s traits over real OpenHuman services, plus `observability.rs` (`FlowRunObserver`), `memory_adapter.rs` (`OpenHumanMemory`), and `langfuse_export.rs`. Has its own [README](tinyflows/README.md).- Re-exported model types (from `tinyflows_catalog`, not owned here): `Flow`, `FlowConnection`, `FlowDraft`, `FlowImport`, `FlowRevision`, `FlowRun`, `FlowRunStep`, `FlowRunTrigger`, `FlowSuggestion`, `FlowValidation`, `FlowValidationError`, `SuggestionStatus`, `DraftOrigin`, plus `types`, `run_registry`, `build_registry`, and `n8n_import` (the format importer).## Calls into-- `vendor/tinyflows/` — the actual workflow model, validation, compilation, and run engine; this domain never re-implements it.-- `crates/openhuman-core/src/agent/tinyagents/` — message/tool-call/usage conversions used by the `llm` and `prompt` capabilities; `agent` nodes pass an explicit run context into nested harness turns through the `agent` capability (`tinyflows/caps/agent.rs`).-- `crates/openhuman-core/src/cron/` — `add_flow_schedule_job` arms a schedule-triggered flow as a `JobType::Flow` cron job; the scheduler fires it by publishing `DomainEvent::FlowScheduleTick`, which `bus::FlowTriggerSubscriber` picks up.-- `crates/openhuman-core/src/skills/` — the `Workflow` / `WorkflowScope` catalogue types used by `catalogue.rs`, and the native `BundledSkill` mechanism that exposes the portable `tinyflows-copilot` authoring manual.-- `crates/openhuman-core/src/memory/` — `memory_tools`/`tinyflows::memory_adapter` read/write agent memory under the `flows` scope.+- `vendor/tinyflows/`: the actual workflow model, validation, compilation, and run engine; this domain never re-implements it.+- `crates/openhuman-core/src/agent/tinyagents/`: message/tool-call/usage conversions used by the `llm` and `prompt` capabilities; `agent` nodes pass an explicit run context into nested harness turns through the `agent` capability (`tinyflows/caps/agent.rs`).+- `crates/openhuman-core/src/cron/`: `add_flow_schedule_job` arms a schedule-triggered flow as a `JobType::Flow` cron job; the scheduler fires it by publishing `DomainEvent::FlowScheduleTick`, which `bus::FlowTriggerSubscriber` picks up.+- `crates/openhuman-core/src/skills/`: the `Workflow` / `WorkflowScope` catalogue types used by `catalogue.rs`, and the native `BundledSkill` mechanism that exposes the portable `tinyflows-copilot` authoring manual.+- `crates/openhuman-core/src/memory/`: `memory_tools`/`tinyflows::memory_adapter` read/write agent memory under the `flows` scope.## Called by-- `crates/openhuman-core/src/core/all.rs` — registers `all_flows_registered_controllers()` under `#[cfg(feature = "flows")]`.-- `crates/openhuman-core/src/core/jsonrpc.rs` — constructs and subscribes `FlowTriggerSubscriber`, `FlowRunDigestSubscriber`, and `DedupCommitSubscriber` at startup.-- `crates/openhuman-core/src/tools/ops.rs` — pushes all 27 flows tools onto the agent tool list (`tools/mod.rs` re-exports the four tool modules).-- `crates/openhuman-core/src/agent/registry/agents/loader.rs` — registers `workflow_builder` and `flow_discovery` as built-in archetypes.-- `crates/openhuman-core/src/agent/session_host/` (`builder/factory.rs`, `turn/tools.rs`) — extends the skill catalogue with `catalogue::flow_entries`.+- `crates/openhuman-core/src/core/all.rs`: registers `all_flows_registered_controllers()` under `#[cfg(feature = "flows")]`.+- `crates/openhuman-core/src/core/jsonrpc.rs`: constructs and subscribes `FlowTriggerSubscriber`, `FlowRunDigestSubscriber`, and `DedupCommitSubscriber` at startup.+- `crates/openhuman-core/src/tools/ops.rs`: pushes all 27 flows tools onto the agent tool list (`tools/mod.rs` re-exports the four tool modules).+- `crates/openhuman-core/src/agent/registry/agents/loader.rs`: registers `workflow_builder` and `flow_discovery` as built-in archetypes.+- `crates/openhuman-core/src/agent/session_host/` (`builder/factory.rs`, `turn/tools.rs`), extends the skill catalogue with `catalogue::flow_entries`.## Tests@@ -72,5 +72,5 @@ from always-compiled code.## Related docs-- [gitbooks/developing/architecture/flows-on-tinyagents.md](../../../../gitbooks/developing/architecture/flows-on-tinyagents.md) — the run pipeline, capability seam, and two-layer security model.-- [`../cron/README.md`](../cron/README.md) — `JobType::Flow` and the schedule-trigger binding.+- [gitbooks/developing/architecture/flows-on-tinyagents.md](../../../../gitbooks/developing/architecture/flows-on-tinyagents.md), the run pipeline, capability seam, and two-layer security model.+- [`../cron/README.md`](../cron/README.md), `JobType::Flow` and the schedule-trigger binding.diff --git a/crates/openhuman-core/src/hooks/README.md b/crates/openhuman-core/src/hooks/README.mdindex 38ef23d2a2..e31ce173a1 100644--- a/crates/openhuman-core/src/hooks/README.md+++ b/crates/openhuman-core/src/hooks/README.md@@ -3,8 +3,8 @@Configurable, file-based hooks: user-authored scripts (or model-evaluatedprompts) that observe or gate the agent at specific moments, discovered from`hooks.json` files rather than compiled against the core. The contract is-Cursor's `hooks.json` (<https://cursor.com/docs/hooks>) — same event names,-stdin envelope, stdout decision object, and exit-code semantics — so a script+Cursor's `hooks.json` (<https://cursor.com/docs/hooks>), same event names,+stdin envelope, stdout decision object, and exit-code semantics, so a scriptwritten for either host runs on the other unchanged.This is a different "hook" from two other things in the codebase: the@@ -34,7 +34,7 @@ second.**The strictest verdict wins.** Layers concatenate rather than override, and`types::HookOutput::merge` folds denial over ask over allow. Adding a hook can-therefore never loosen a policy another one set — an operator-managed+therefore never loosen a policy another one set, an operator-managedsystem-wide deny hook cannot be overridden by a repository shipping its own`hooks.json`.@@ -47,7 +47,7 @@ the agent, and a gating hook must not be demoted to fire-and-forget.`exec.rs` reads a command hook's exit code: `0` parses stdout as a`HookOutput` (the last complete JSON object on stdout, so progress lines arefine), `2` denies regardless of stdout with stderr as the reason, and anything-else — including a timeout, a missing interpreter, or unparseable stdout — is a+else, including a timeout, a missing interpreter, or unparseable stdout, is afailure that fails open unless the definition sets `fail_closed`, in which caseit denies. Do not change this default without reading the configuration andsecurity section of `AGENTS.md`. A hook that answers `allow` only lets the call@@ -75,7 +75,7 @@ trust last:| `Project` | `<action_dir>/.openhuman/hooks.json` |This is the opposite of how `config.toml` merges (override, not concatenate)-— deliberately, since concatenation combined with `HookOutput::merge`'s+, deliberately, since concatenation combined with `HookOutput::merge`'sstrictest-wins rule is the only composition that can't be used to loosenpolicy. `HookDefinition::layer` and `source_dir` are `skip_deserializing` andstamped from the file's own location, so a `hooks.json` cannot claim a more@@ -87,12 +87,12 @@ unreadable or malformed one becomes a `HookConfig::warnings` entry surfaced byMost hooks are `command`: spawn a program, hand it the event JSON on stdin,read a decision from stdout. A `prompt` hook is a policy written in English-instead — `prompt_eval.rs` asks the configured model to judge a condition,+instead, `prompt_eval.rs` asks the configured model to judge a condition,via a one-shot `inference::ops::inference_prompt` call capped at 200 outputtokens. A hook definition may override the model; the override is applied tothe `Config` copy returned by `load_config_with_timeout` for that one call(`default_model`), so nothing persists and a concurrent turn on the real-config is unaffected. Reserve `prompt` hooks for rare, high-stakes moments —+config is unaffected. Reserve `prompt` hooks for rare, high-stakes moments,they cost a model call per event.## Bridge (`bridge.rs`)@@ -103,14 +103,14 @@ engine registers itself through those seams once at bootstrap(`ConfiguredHookBridge::install`/`uninstall`, registered under`BRIDGE_HOOK_NAME` so a rebuilt core replaces rather than duplicates it).Cursor's `beforeShellExecution`, `beforeReadFile`, and `afterFileEdit` are not-separate call sites here — `derived_event` maps tool names onto them+separate call sites here, `derived_event` maps tool names onto them(`SHELL_TOOLS`: `shell`/`run_command`/`bash`/...; `READ_TOOLS`:`file_read`/`read_diff`; `WRITE_TOOLS`: `file_write`/`edit`/...; MCP toolsget `beforeMCPExecution`/`afterMCPExecution`). On the pre side the bridge fires`preToolUse` and then the derived `before*` event with a Cursor-shapedpayload, merging both verdicts; on the post side it fires `postToolUse` (or`postToolUseFailure`) and then `afterShellExecution`/`afterFileEdit`. A write-therefore has no derived pre-event — denying it belongs to `preToolUse`. The+therefore has no derived pre-event, denying it belongs to `preToolUse`. The`PostTurnHook` impl fires `afterAgentResponse` and `stop`.## Wiring@@ -121,7 +121,7 @@ therefore has no derived pre-event — denying it belongs to `preToolUse`. Theor empty config uninstalls the bridge entirely so an unconfigured host paysno per-tool-call cost.- `[hooks]` in `config/schema/hooks.rs` carries only host-level switches- (`enabled`, `default_timeout_secs`) — the hooks themselves live in+ (`enabled`, `default_timeout_secs`), the hooks themselves live in`hooks.json`, not in `config.toml`.- RPC namespace `hooks` (`schemas.rs`) is registered via`all_hooks_registered_controllers` in `core/all.rs`.@@ -139,5 +139,5 @@ therefore has no derived pre-event — denying it belongs to `preToolUse`. The## Related docs-- [gitbooks/developing/hooks.md](../../../../gitbooks/developing/hooks.md) — user-facing `hooks.json` guide-- [gitbooks/developing/architecture/security.md](../../../../gitbooks/developing/architecture/security.md) — approval gate and autonomy policy that still applies after a hook allows+- [gitbooks/developing/hooks.md](../../../../gitbooks/developing/hooks.md), user-facing `hooks.json` guide+- [gitbooks/developing/architecture/security.md](../../../../gitbooks/developing/architecture/security.md), approval gate and autonomy policy that still applies after a hook allowsdiff --git a/crates/openhuman-core/src/hosting/README.md b/crates/openhuman-core/src/hosting/README.mdindex 30dd6a0b7d..a956442af4 100644--- a/crates/openhuman-core/src/hosting/README.md+++ b/crates/openhuman-core/src/hosting/README.md@@ -11,9 +11,9 @@ everything about a provider, and this module owns everything about OpenHuman.- Decide which directory an agent may deploy (`resolve_in_workspace`).- Expose the ten `hosting_*` agent tools and describe their results to a model.-Everything else — Vercel's endpoints, the upload-then-build deployment protocol,+Everything else, Vercel's endpoints, the upload-then-build deployment protocol,how a marketplace database is provisioned and connected, the order a launch runs-in — belongs to the crate, where it is provider-independent and tested against a+in, belongs to the crate, where it is provider-independent and tested against amock of the provider's REST API. Outside the mock responses in`hosting_tests.rs`, nothing here knows the word `readyState`.@@ -53,7 +53,7 @@ agent reaches for it.`hosting_rollback` reads the deployment before promoting it and refuses one thatdid not finish building. `hosting_list_deployments` returns failed and-still-building deployments too — they are the history an agent is reading — so+still-building deployments too, they are the history an agent is reading, sothe id it picks is not necessarily one that can serve traffic, and promoting afailed build would take the site down during an attempt to bring it back up. Itdoes **not** check that the deployment belongs to the named site: a deployment is@@ -71,7 +71,7 @@ Two gates, and both matter:`tools::ops` then registers nothing. A tool that is present and cannot work isworse than one that is absent, because a model retries it.-A *misconfigured* section — an unknown provider slug, a blank configured key — is+A *misconfigured* section, an unknown provider slug, a blank configured key, isan error rather than a silent skip, logged at `warn` by the registry.## Two things this domain will not dodiff --git a/crates/openhuman-core/src/http_host/README.md b/crates/openhuman-core/src/http_host/README.mdindex fe631b4c46..63a3d82acb 100644--- a/crates/openhuman-core/src/http_host/README.md+++ b/crates/openhuman-core/src/http_host/README.md@@ -1,6 +1,6 @@# http_host-Static directory hosting over ad-hoc, in-process HTTP listeners owned by the core. Lets trusted callers (RPC/CLI) start, inspect, list, and stop lightweight file servers that expose a chosen directory on a chosen TCP port. Each server runs as an in-process `axum` task sharing the core's lifetime, and defaults to HTTP Basic authentication using the active user's identity plus a randomly generated password. There is no on-disk persistence — the registry of running servers lives in process memory and is torn down on shutdown.+Static directory hosting over ad-hoc, in-process HTTP listeners owned by the core. Lets trusted callers (RPC/CLI) start, inspect, list, and stop lightweight file servers that expose a chosen directory on a chosen TCP port. Each server runs as an in-process `axum` task sharing the core's lifetime, and defaults to HTTP Basic authentication using the active user's identity plus a randomly generated password. There is no on-disk persistence, the registry of running servers lives in process memory and is torn down on shutdown.## Responsibilities@@ -29,9 +29,9 @@ Static directory hosting over ad-hoc, in-process HTTP listeners owned by the cor## Public surface-- `all_http_host_controller_schemas()` / `all_http_host_registered_controllers()` — re-exported from `schemas`; wired into the core controller registry.-- `pub mod ops` — `start_hosted_dir_server`, `list_hosted_dir_servers`, `get_hosted_dir_server`, `stop_hosted_dir_server`, `stop_all_hosted_dir_servers`.-- `pub mod rpc` — async `start`/`stop`/`get`/`list` returning `RpcOutcome<...>`.+- `all_http_host_controller_schemas()` / `all_http_host_registered_controllers()`: re-exported from `schemas`; wired into the core controller registry.+- `pub mod ops`: `start_hosted_dir_server`, `list_hosted_dir_servers`, `get_hosted_dir_server`, `stop_hosted_dir_server`, `stop_all_hosted_dir_servers`.+- `pub mod rpc`: async `start`/`stop`/`get`/`list` returning `RpcOutcome<...>`.(`auth`, `handlers`, `path_utils`, `types` are private to the module.)@@ -52,18 +52,18 @@ None on disk. Running servers are held in a process-global `HostedDirRegistry` (## Dependencies-- `crate::config` — `load_config_with_timeout` to resolve the active config when deriving the default Basic-auth username (`auth.rs`).-- `crate::security::credentials::session_support` — `build_session_state` to read the active user identity for the default auth username (`auth.rs`).-- `crate::core::shutdown` — `register` a one-time hook so all hosted servers stop when the core shuts down (`ops.rs`).-- `crate::core::all` — `ControllerFuture`, `RegisteredController` for controller registration (`schemas.rs`).-- `crate::core::{ControllerSchema, FieldSchema, TypeSchema}` — controller schema types (`schemas.rs`).-- `crate::rpc::RpcOutcome` — RPC response envelope (`rpc.rs`); `crate::rpc` is the `openhuman-rpc` crate re-exported from `crates/openhuman-core/src/lib.rs`.+- `crate::config`: `load_config_with_timeout` to resolve the active config when deriving the default Basic-auth username (`auth.rs`).+- `crate::security::credentials::session_support`: `build_session_state` to read the active user identity for the default auth username (`auth.rs`).+- `crate::core::shutdown`: `register` a one-time hook so all hosted servers stop when the core shuts down (`ops.rs`).+- `crate::core::all`: `ControllerFuture`, `RegisteredController` for controller registration (`schemas.rs`).+- `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller schema types (`schemas.rs`).+- `crate::rpc::RpcOutcome`: RPC response envelope (`rpc.rs`); `crate::rpc` is the `openhuman-rpc` crate re-exported from `crates/openhuman-core/src/lib.rs`.- External crates: `axum` (HTTP server/router), `tokio` (`TcpListener`, tasks), `tokio_util` (`CancellationToken`, `ReaderStream`), `uuid`, `base64`, `rand`, `urlencoding`, `serde`/`serde_json`.## Used by-- `crates/openhuman-core/src/core/all.rs` — registers `all_http_host_registered_controllers()` into the core controller registry, exposing the RPC/CLI surface.-- `crates/openhuman-core/src/lib.rs` — declares `pub mod http_host;`, gated by `#[cfg(feature = "http-server")]`; a slim build without that feature has no `http_host.*` controllers (see the `default` feature list and `http-server` feature notes in `crates/openhuman-core/Cargo.toml`).+- `crates/openhuman-core/src/core/all.rs`: registers `all_http_host_registered_controllers()` into the core controller registry, exposing the RPC/CLI surface.+- `crates/openhuman-core/src/lib.rs`: declares `pub mod http_host;`, gated by `#[cfg(feature = "http-server")]`; a slim build without that feature has no `http_host.*` controllers (see the `default` feature list and `http-server` feature notes in `crates/openhuman-core/Cargo.toml`).- `crates/openhuman-core/src/core/observability.rs` references `http_host::path_utils` paths in error-classification docs/tests (`http_host` directory-not-found maps to a filesystem user-path-invalid class).## Notes / gotchas@@ -73,6 +73,6 @@ None on disk. Running servers are held in a process-global `HostedDirRegistry` (- **Path safety**: `resolve_request_path` rejects URL-encoded traversal and verifies the canonicalized target stays under the hosted root; `canonicalize_hosted_directory` resolves and verifies the root is a real directory before binding.- **Port `0`**: binding with port `0` lets the OS pick a free port; the actual assigned port (from `local_addr`) is what gets stored and reported.- **No duplicate binds**: `start` rejects another server already registered on the same `bind_host:port`.-- **Logging redaction**: directory paths are logged via `redact_path_for_log` (only the leaf name, prefixed `<redacted>/`) — full host paths are not emitted.+- **Logging redaction**: directory paths are logged via `redact_path_for_log` (only the leaf name, prefixed `<redacted>/`), full host paths are not emitted.- **Lifetime**: servers do not persist across core restarts; the shutdown hook (`register_shutdown_hook_once`) is installed lazily on the first `start`.- **IPv6**: `bind_host` containing `:` (and not already bracketed) is wrapped in `[...]` for both the bind target and the URL rendering.diff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.mdindex b4c783d22c..1586485348 100644--- a/crates/openhuman-core/src/inference/README.md+++ b/crates/openhuman-core/src/inference/README.md@@ -27,7 +27,7 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.| File / dir | Role || --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `mod.rs` | Domain root; module decls + re-exports; wires `inference.*` controller schemas/controllers. |-| `ops.rs` | Canonical handler file — `inference_*` business logic returning `RpcOutcome<T>`; delegates to `local`, `provider`, `sentiment`, `device`, `presets`, `openai_oauth`. Includes Sentry-noise suppression for expected provider/user-config failures. |+| `ops.rs` | Canonical handler file, `inference_*` business logic returning `RpcOutcome<T>`; delegates to `local`, `provider`, `sentiment`, `device`, `presets`, `openai_oauth`. Includes Sentry-noise suppression for expected provider/user-config failures. || `schemas.rs` + `schemas/` (`catalog.rs`, `prompt_handlers.rs`, `oauth_handlers.rs`, `claude_code_handlers.rs`, `settings_handlers.rs`) | `inference.*` controller schemas + `handle_*` fns + param DTOs. || `tinyinference_llm::{classification,completion,sentiment}` | Reusable language-model parsing and classification called directly by the host. || `tinyinference_local::device`; `tinyinference_core::sanitize` | Shared hardware detection and credential-safe diagnostic formatting. |@@ -94,26 +94,26 @@ Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates## Persistence- `openai_oauth/store.rs` persists OAuth tokens via the credentials auth-profile store (`AuthProfilesStore`, `auth-profiles.json`, encrypted at rest) under profile key `provider:openai` / profile `oauth`.-- `LocalAiService` holds in-process runtime state (status, owned `ollama serve` child) via the `local::global` `OnceCell` singleton — process-lifetime, not durably persisted.+- `LocalAiService` holds in-process runtime state (status, owned `ollama serve` child) via the `local::global` `OnceCell` singleton, process-lifetime, not durably persisted.- Model artifacts live under `<root>/models/local-ai/` (`local/core.rs::model_artifact_path`); OpenHuman selects the Piper root and passes it to `tinyinference_local::piper::PiperInstall`.- Routing/provider/local settings persisted through `config` (no dedicated `store.rs`).## Dependencies-- `crate::config` — `Config`, `config::rpc` (load/save, `ModelSettingsPatch`, `LocalAiSettingsPatch`), cloud-provider schema (`AuthStyle`, slug reservation, id generation), abstract tier model constants. Heaviest dependency.-- `crate::security::credentials` — `AuthService`, `AuthProfilesStore`/`AuthProfile`/`TokenSet`, state dir — for OAuth token storage and provider auth resolution.-- `crate::tools` — tool schemas and product tool metadata projected into TinyAgents requests.-- `crate::agent::tinyagents` — native model, route, message, usage, and thread-context seams used by the agent harness.-- `crate::voice` — voice RPC/audio layer that imports these inference STT/TTS implementations (also a consumer).-- `crate::security::prompt_injection` — prompt-injection handling on the inference path.-- `crate::util` — small shared helpers.-- `crate::core::all` — `ControllerFuture`, `RegisteredController` (controller registry).-- `crate::core::types` — `ControllerSchema`, `FieldSchema`, `TypeSchema`.-- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent` — `SessionExpired` / `ProviderApiKeyRejected` publishing on auth failure.-- `crate::security::live_policy` + `crate::security::egress` — Privacy-Mode `LocalOnly` enforcement and egress descriptors at the chat-factory chokepoint (`enforce_local_only_inference`, `emit_inference_egress` in `provider/factory/access_gates.rs`).-- `crate::core::observability` — `expected_error_kind` for Sentry-noise classification.-- `crate::core::jsonrpc` — endpoint mounting reference for `/v1`.-- `crate::core::auth` — bearer auth for the OpenAI-compatible endpoint.+- `crate::config`: `Config`, `config::rpc` (load/save, `ModelSettingsPatch`, `LocalAiSettingsPatch`), cloud-provider schema (`AuthStyle`, slug reservation, id generation), abstract tier model constants. Heaviest dependency.+- `crate::security::credentials`: `AuthService`, `AuthProfilesStore`/`AuthProfile`/`TokenSet`, state dir, for OAuth token storage and provider auth resolution.+- `crate::tools`: tool schemas and product tool metadata projected into TinyAgents requests.+- `crate::agent::tinyagents`: native model, route, message, usage, and thread-context seams used by the agent harness.+- `crate::voice`: voice RPC/audio layer that imports these inference STT/TTS implementations (also a consumer).+- `crate::security::prompt_injection`: prompt-injection handling on the inference path.+- `crate::util`: small shared helpers.+- `crate::core::all`: `ControllerFuture`, `RegisteredController` (controller registry).+- `crate::core::types`: `ControllerSchema`, `FieldSchema`, `TypeSchema`.+- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent`: `SessionExpired` / `ProviderApiKeyRejected` publishing on auth failure.+- `crate::security::live_policy` + `crate::security::egress`: Privacy-Mode `LocalOnly` enforcement and egress descriptors at the chat-factory chokepoint (`enforce_local_only_inference`, `emit_inference_egress` in `provider/factory/access_gates.rs`).+- `crate::core::observability`: `expected_error_kind` for Sentry-noise classification.+- `crate::core::jsonrpc`: endpoint mounting reference for `/v1`.+- `crate::core::auth`: bearer auth for the OpenAI-compatible endpoint.- External: `sysinfo` (device profile), `reqwest`.## Used bydiff --git a/crates/openhuman-core/src/inference/host_runtime/README.md b/crates/openhuman-core/src/inference/host_runtime/README.mdindex ad02794848..a72351f747 100644--- a/crates/openhuman-core/src/inference/host_runtime/README.md+++ b/crates/openhuman-core/src/inference/host_runtime/README.md@@ -2,8 +2,8 @@OpenHuman-owned bindings around `tinyinference-local`.-The reusable runtime implementation—Ollama and LM Studio discovery, process-lifecycle, model downloads, status, prompts, vision, and embeddings—lives in+The reusable runtime implementation, Ollama and LM Studio discovery, process+lifecycle, model downloads, status, prompts, vision, and embeddings, lives inthe `tinyinference-local` crate. This directory contains only OpenHuman policyand integration seams:diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.mdindex 63bd539368..df29c02f8f 100644--- a/crates/openhuman-core/src/inference/provider/README.md+++ b/crates/openhuman-core/src/inference/provider/README.md@@ -8,7 +8,7 @@ domain.## Public surface-- **Factory** (`factory.rs` + `factory/` — `routing.rs`, `tiers.rs`, `turn_model.rs`, `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`, `primary_cloud.rs`) — `create_chat_model`,+- **Factory** (`factory.rs` + `factory/`: `routing.rs`, `tiers.rs`, `turn_model.rs`, `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`, `primary_cloud.rs`), `create_chat_model`,`create_chat_model_from_string[_with_model_id]`,`create_chat_model_with_model_id`, `provider_for_role`, `role_for_model_tier`,`probe_inference_readiness`, `BYOK_INCOMPLETE_SENTINEL`. Parses the@@ -18,12 +18,12 @@ domain.and applies the BYOK sentinel, Privacy-Mode `LocalOnly`(`enforce_local_only_inference`), and managed-session (`verify_session_active`)gates before building a model.-- **Models** — `OpenHumanBackendModel` + `PROVIDER_LABEL`+- **Models**, `OpenHumanBackendModel` + `PROVIDER_LABEL`(`openhuman_backend_model.rs`); OpenAI-compatible and Anthropic builders livein `tinyinference_llm::providers` and are called directly.-- **DTOs** (`types.rs`) — `ChatRequest`, `ChatResponse`, `ProviderDelta`,+- **DTOs** (`types.rs`), `ChatRequest`, `ChatResponse`, `ProviderDelta`,`ToolCall`, `UsageInfo`, `AGENT_TURN_MAX_OUTPUT_TOKENS`.-- **Error classifiers** — reusable classifiers live in+- **Error classifiers**, reusable classifiers live in`tinyinference_llm::classification`; this directory retains OpenHuman managed-backend and telemetry policy.## Transports@@ -35,32 +35,32 @@ domain.| Anthropic Messages API (prompt caching) | `tinyinference_llm::providers::anthropic` | `<slug>:<model>` whose endpoint is the first-party Messages API and native tool calling is on || Codex OAuth / Responses API | `openai_codex.rs` host OAuth selection plus `tinyinference_llm::providers::openai::codex` metadata | the `openai` cloud slug once Codex OAuth tokens exist || Claude Agent SDK subprocess | `tinyagents_harness::providers::claude_agent_sdk` | `claude_agent_sdk` / `claude_agent_sdk:<model>` |-| Claude Code CLI subprocess | `claude_code/` — see its own [README](claude_code/README.md) | `claude-code:<model>` |+| Claude Code CLI subprocess | `claude_code/`: see its own [README](claude_code/README.md) | `claude-code:<model>` |## Calls into- `tinyinference_llm::model::ChatModel` (`vendor/tinyagents/vendor/tinyinference`)- — the trait every transport implements.-- `crate::config` — cloud-provider schema (`AuthStyle`, slug reservation),+, the trait every transport implements.+- `crate::config`: cloud-provider schema (`AuthStyle`, slug reservation),`Config::claude_agent_sdk`, abstract tier model constants.-- `crate::security::credentials` — auth-profile store for BYOK keys and OAuth+- `crate::security::credentials`: auth-profile store for BYOK keys and OAuthtokens.-- `crate::agent::tinyagents::{routes, host}` — workload routing and explicit run+- `crate::agent::tinyagents::{routes, host}`: workload routing and explicit runexplicit run-thread plumbing consumed while building a managed model.-- `crate::security::live_policy` + `crate::security::egress` — Privacy-Mode+- `crate::security::live_policy` + `crate::security::egress`: Privacy-Mode`LocalOnly` refusal and `EgressDescriptor` emission at the factory chokepoint(`factory/access_gates.rs`).-- `crate::inference::host_runtime` — `profile::is_local_provider_string`, Ollama /+- `crate::inference::host_runtime`: `profile::is_local_provider_string`, Ollama /LM Studio base-url resolution for local provider strings.-- `crate::inference::auth_error_registry` — surfaces OpenHuman per-provider auth errors+- `crate::inference::auth_error_registry`: surfaces OpenHuman per-provider auth errorsback to the UI.-- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent` —+- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent`:`ops/http_error/auth_failure.rs::publish_backend_session_expired` and`openhuman_backend_model.rs` publish `DomainEvent::SessionExpired` when themanaged backend reports an auth failure, so the credentials layer canclear/refresh the session; `ops/http_error/auth_failure.rs` also publishes`DomainEvent::ProviderApiKeyRejected` the first time a BYO key is rejected.-- `crate::mcp::server::local` (via `claude_code/driver.rs`) — the Claude Code+- `crate::mcp::server::local` (via `claude_code/driver.rs`), the Claude Codeprovider points the sandboxed `claude` subprocess at the in-process MCPserver so it can reach OpenHuman's memory/tools over loopback without theMCP server inheriting CC's OS jail.@@ -80,13 +80,13 @@ consumers: the agent harness (`agent/session_host/builder/factory.rs`,## Sub-modules-- `ops/` — `http_error` (HTTP error+- `ops/`: `http_error` (HTTP errorclassification, Sentry routing, `api_error`), `models`(`list_configured_models`), `provider_factory` (`ProviderRuntimeOptions`,`list_providers`, `is_qwen_alias`-style China-provider alias helpers).Preserves the original `pub use ops::*` contract split out of a single `ops.rs`.-- [`claude_code/`](claude_code/README.md) — Claude Code CLI provider.-- `schemas.rs` — a `providers.list_models` controller that is **not**+- [`claude_code/`](claude_code/README.md), Claude Code CLI provider.+- `schemas.rs`: a `providers.list_models` controller that is **not**registered in `core/all.rs`; the live method is `inference.list_models`(`openhuman.providers_list_models` survives only as a legacy alias in`core/legacy_aliases.rs`).@@ -95,17 +95,17 @@ consumers: the agent harness (`agent/session_host/builder/factory.rs`,- `factory_tests.rs`, `factory_crate_native_tests.rs`,`factory_egress_fallback_tests.rs`, `factory_route_resolution_tests.rs`,- `factory_test_provider_override_tests.rs` — provider-string parsing, access+ `factory_test_provider_override_tests.rs`: provider-string parsing, accessgates, and model construction.- `ops_tests.rs`, `ops_tests_error_suppression_tests.rs`,- `ops_tests_models_parsing_tests.rs`, `ops/http_error_tests.rs`, `ops/models_tests.rs` — error+ `ops_tests_models_parsing_tests.rs`, `ops/http_error_tests.rs`, `ops/models_tests.rs`: errorclassification and model listing.-- `error_classify_tests.rs` — OpenHuman-specific classifier policy; reusable+- `error_classify_tests.rs`: OpenHuman-specific classifier policy; reusableclassifier tests live in TinyInference.-- `claude_code/*_tests.rs` — per-file coverage of the CC provider (auth,+- `claude_code/*_tests.rs`: per-file coverage of the CC provider (auth,auth status, driver, event mapper, input builder, stream parser, sessionstore, settings, version check) plus `mod_tests.rs`.-- `openhuman_backend_model_tests.rs` — managed host transport; reusable provider+- `openhuman_backend_model_tests.rs`: managed host transport; reusable providerbuilder and Codex tests live in TinyInference and TinyAgents.Local runtime chat providers (Ollama, LM Studio, MLX, oMLX, local-openai)diff --git a/crates/openhuman-core/src/inference/tokenjuice/README.md b/crates/openhuman-core/src/inference/tokenjuice/README.mdindex 543f6cf8c9..6b1cd95f11 100644--- a/crates/openhuman-core/src/inference/tokenjuice/README.md+++ b/crates/openhuman-core/src/inference/tokenjuice/README.md@@ -1,8 +1,8 @@# OpenHuman TokenJuice AdapterThe reusable compression engine ships as the separately released `tinyjuice`-TinyBus module. Its stateful half — the router, the CCR cache, the rule engine,-ranged retrieval — runs there and is reached only over the bus; its stateless+TinyBus module. Its stateful half, the router, the CCR cache, the rule engine,+ranged retrieval, runs there and is reached only over the bus; its statelesscontent transforms are linked directly (see "What is linked" below). Thisdirectory is the host adapter and shared wire-contract layer.@@ -14,7 +14,7 @@ OpenHuman-owned files:| `types.rs` | Re-export of the `tinyjuice-bus` contract (`tinyjuice_bus::types::{AgentTokenjuiceCompression, CompressOptions, CompressedOutput, CompressorKind, ContentHint, ContentKind}` and `tinyjuice_bus::wire::{CacheStats, CompactResponse, InstallRequest, RangeUnit, RetrieveRange}`) under the paths ~40 call sites in this crate already use. || `schemas.rs` | JSON-RPC controller schemas and handlers. || `config_patch.rs` | Partial update shape for the `[tokenjuice]` config block. |-| `tools.rs` | OpenHuman agent tool implementation for the retrieve tool (`RETRIEVE_TOOL_NAME = "tinyjuice_retrieve"`; `"tokenjuice_retrieve"` is a recognized recovery-tool alias, not the tool's registered name — see `RECOVERY_TOOL_NAMES`). |+| `tools.rs` | OpenHuman agent tool implementation for the retrieve tool (`RETRIEVE_TOOL_NAME = "tinyjuice_retrieve"`; `"tokenjuice_retrieve"` is a recognized recovery-tool alias, not the tool's registered name, see `RECOVERY_TOOL_NAMES`). || `ml/` | Bridge from TinyJuice's optional ML callback into the shared `runtime::python_server` Kompress backend (ModernBERT token/sentence salience); opt-in via `config.tokenjuice.ml_compression_enabled` (default off), degrades gracefully when the flag is off or the runtime server is unavailable. || `savings.rs` | OpenHuman model-pricing attribution and persisted dashboard stats. |@@ -31,7 +31,7 @@ TinyJuice-owned engine pieces:## What is linked, and what stays behind the module boundary-The rule is no longer "the crate is never linked" — it is **stateful engine+The rule is no longer "the crate is never linked", it is **stateful enginebehavior stays behind the module boundary; stateless content transforms donot.**@@ -49,12 +49,12 @@ Everything with state stays where it was, reached only through TinyBus:| Behind the module boundary | Why it stays || --- | --- || `compress::route` / `compress_content` | Picks a compressor from the rule engine and records savings. |-| `cache/` — the CCR store, retrieval markers, disk tier, ranged retrieval | Owns a disk tier and a marker vocabulary (`⟦tj:<hash>⟧`) the module must resolve. `tinyjuice_retrieve` is the model-facing half and is unchanged. |+| `cache/`: the CCR store, retrieval markers, disk tier, ranged retrieval | Owns a disk tier and a marker vocabulary (`⟦tj:<hash>⟧`) the module must resolve. `tinyjuice_retrieve` is the model-facing half and is unchanged. || `rules/`, `reduce/`, `ml/` | Rule tables, execution reduction, the ModernBERT callback. |Why a content transform is not allowed to go through the bus: reaching it thereneeds the `modules` feature, a loaded cdylib, and `config.tokenjuice` /-`context.compaction_enabled` — which defaults to `false`. A core tool's default+`context.compaction_enabled`: which defaults to `false`. A core tool's defaultoutput would then depend on whether an optional module happened to load, so thesame URL would come back as Markdown on one install and as raw markup onanother. That is not a defensible way to decide what a fetched page looks like.diff --git a/crates/openhuman-core/src/integrations/composio/README.md b/crates/openhuman-core/src/integrations/composio/README.mdindex 8e458c8fe4..0b5ccb7622 100644--- a/crates/openhuman-core/src/integrations/composio/README.md+++ b/crates/openhuman-core/src/integrations/composio/README.md@@ -1,10 +1,10 @@# composio-Backend-proxied (and optionally direct/BYO-key) access to Composio's 1000+ OAuth integrations (Gmail, Notion, GitHub, Slack, Google Calendar, …). The Rust counterpart to the backend routes under `src/routes/agentIntegrations/composio.ts`. In **backend mode** the openhuman backend owns the Composio API key, billing/margin, the toolkit allowlist, HMAC webhook verification, and Socket.IO trigger fan-out — the core never hits the Composio API directly. In **direct mode** (`composio.mode = "direct"`, gated by a user-supplied API key in the encrypted keychain) the core talks to Composio's v3 API with the user's own key against their personal tenant. This domain exposes toolkit/connection/tool/trigger management over JSON-RPC, model-facing agent tools for discovery + execution, an OAuth handoff flow, a persistent trigger-event archive, and a per-action execute pipeline (prepare → retry → error classification).+Backend-proxied (and optionally direct/BYO-key) access to Composio's 1000+ OAuth integrations (Gmail, Notion, GitHub, Slack, Google Calendar, …). The Rust counterpart to the backend routes under `src/routes/agentIntegrations/composio.ts`. In **backend mode** the openhuman backend owns the Composio API key, billing/margin, the toolkit allowlist, HMAC webhook verification, and Socket.IO trigger fan-out, the core never hits the Composio API directly. In **direct mode** (`composio.mode = "direct"`, gated by a user-supplied API key in the encrypted keychain) the core talks to Composio's v3 API with the user's own key against their personal tenant. This domain exposes toolkit/connection/tool/trigger management over JSON-RPC, model-facing agent tools for discovery + execution, an OAuth handoff flow, a persistent trigger-event archive, and a per-action execute pipeline (prepare → retry → error classification).A third path underlies most of the above: profile fetch, action execution,and sync now go through the loaded `tinyconnectors` module (via-`module_client.rs`) rather than an in-process engine — `tinymemory` v1.13.4+`module_client.rs`) rather than an in-process engine, `tinymemory` v1.13.4deleted the old in-process Composio pipeline outright (72 files, ~18.3klines) because reaching a connected account needs a credential this cratemust not hold. `tinyconnectors-bus` is the wire contract for that module@@ -28,12 +28,12 @@ Every Composio operation (profile fetch, action execution, connection sync)now lives in the `tinyconnectors` module, loaded through `crate::modules`behind the `modules` feature. `module_client.rs` is the single `#[cfg]`switch for this: rather than feature-gating each of a dozen handlers-individually — twelve chances to gate one differently, with a gates-off-build failing wherever the compiler happens to hit first — the gate lives+individually, twelve chances to gate one differently, with a gates-off+build failing wherever the compiler happens to hit first, the gate livesonce, here, and every handler reads the same either way.`tinyconnectors-bus` (`vendor/tinyconnectors/crates/tinyconnectors-bus`,-declared in `crates/openhuman-core/Cargo.toml` ~486–496) supplies the member names+declared in `crates/openhuman-core/Cargo.toml` ~486, 496) supplies the member names(`module_client::methods`) and payload types with no transport and nobehaviour; it compiles none of the connector itself. A gates-off build canstill name a member and match on the contract, it just cannot call one.@@ -53,7 +53,7 @@ triggers) from a real transport failure.| `crates/openhuman-core/src/integrations/composio/module_client.rs` | The `tinyconnectors` module bridge: the one `modules`-feature `#[cfg]` switch, `methods` re-exported from `tinyconnectors_bus`, and member-failure classification (`is_unsupported_by_route`, error-prefix peeling). || `crates/openhuman-core/src/integrations/composio/tools.rs` + `tools/` (`authorize.rs`, `connect.rs`, `list_connections.rs`, `list_toolkits.rs`, `list_tools.rs`, `execute.rs`, `registry.rs`, `visibility.rs`) | Agent tools (`ComposioListToolkitsTool`, `ComposioListConnectionsTool`, `ComposioAuthorizeTool`, `ComposioConnectTool`, `ComposioListToolsTool`, `ComposioExecuteTool`) + `all_composio_agent_tools`; scope/visibility gating (`resolve_action_scope`, `evaluate_tool_visibility`). || `crates/openhuman-core/src/integrations/composio/tools/direct.rs` + `tools/direct/` (`types.rs`, `connections.rs`, `discovery.rs`, `construction.rs`, `execution.rs`, `http_errors.rs`, `tool_impl.rs`) | Direct-mode Composio tool provider hitting Composio v2/v3 APIs with the user's key (`ComposioTool`, `ComposioAction`, `ComposioConnectedAccount`). |-| `crates/openhuman-core/src/integrations/composio/action_tool.rs` | `ComposioActionTool` — a `Tool` wrapping exactly one Composio action, constructed dynamically when `integrations_agent` is spawned with a toolkit. |+| `crates/openhuman-core/src/integrations/composio/action_tool.rs` | `ComposioActionTool`: a `Tool` wrapping exactly one Composio action, constructed dynamically when `integrations_agent` is spawned with a toolkit. || `crates/openhuman-core/src/integrations/composio/contract_gate.rs` | Late-bound action contract gate (#4853): on an action's first call this turn, surfaces the full live contract (via `catalog::fetch_live_toolkit_catalog`) as a recoverable tool error before executing, so the retry has the real schema in context. || `crates/openhuman-core/src/integrations/composio/catalog.rs` + `catalog/` (`contract.rs`, `lookups.rs`, `probe.rs`) | Live Composio tool contracts (`fetch_live_toolkit_catalog`, `ToolContract`, in `catalog/contract.rs`): the unfiltered mode-aware `list_tools` schema (backend `ComposioClient::list_tools` or direct v3 `direct_list_tools`) plus a bounded read-only response probe (`probe_tool_output_sample`, `catalog/probe.rs`) when a schema publishes no `output_parameters`. || `crates/openhuman-core/src/integrations/composio/connected_integrations.rs` + `connected_integrations/` (`cache.rs`, `fetch.rs`, `fetch_uncached.rs`) | Cached active-connections lookups (`cached_active_integrations`, `fetch_connected_integrations*`, `fetch_toolkit_actions`) reconciled against `list_connections`. |@@ -81,7 +81,7 @@ triggers) from a real transport failure.| Sub-module | Contents || --- | --- || `error_utils` | `OpResult`, `resolve_client`, `report_composio_op_error`, helpers |-| `toolkits` | `composio_list_toolkits`, `composio_list_capabilities`, ... |+| `toolkits` | `composio_list_toolkits`, `composio_list_capabilities`... || `connections` | `composio_list_connections`, `composio_authorize`, `_delete_...` || `memory_cleanup` | Memory-cleanup helpers for connection deletion || `tools_ops` | `composio_list_tools` |@@ -108,7 +108,7 @@ From `mod.rs` re-exports:- **Identity**: `connection_identity`.- **Trigger history**: `init_composio_trigger_history`, `global_composio_trigger_history`.- **Types**: `ComposioConnection`, `ComposioConnectionsResponse`, `ComposioToolkitsResponse`, `ComposioToolSchema`/`ComposioToolFunction`, `ComposioToolsResponse`, `ComposioAuthorizeResponse`, `ComposioExecuteResponse`, `ComposioDeleteResponse`, `ComposioCapability`/`ComposioCapabilitiesResponse`, `ComposioAgentReadyToolkitsResponse`, `ComposioTriggerEvent`/`ComposioTriggerMetadata`, `ComposioTriggerHistoryEntry`/`ComposioTriggerHistoryResult`.-- **Periodic sync**: `record_sync_success`, `start_periodic_sync` (from `periodic.rs`, host code — see above).+- **Periodic sync**: `record_sync_success`, `start_periodic_sync` (from `periodic.rs`, host code, see above).- **Re-exported from `providers::{ProviderUserProfile, SyncOutcome, SyncReason}`** (contract types, `tinymemory_api::composio`), plus `crate::memory::sync::composio::bus::{register_composio_trigger_subscriber, ComposioConfigChangedSubscriber, ComposioTriggerSubscriber}`.## RPC / controllers@@ -142,15 +142,15 @@ Handlers delegate to `ops/`; scope handlers delegate to `ops::user_scopes`. Expo## Agent tools-From `tools.rs` (`all_composio_agent_tools`, registered only when `agent::subagent_host::user_is_signed_in_to_composio` is true): `composio_list_toolkits`, `composio_list_connections`, `composio_authorize`, `composio_connect` (inline OAuth approval card, #3993), `composio_list_tools`, `composio_execute`. Plus `ComposioActionTool` (one tool per action, spawned for `integrations_agent`, gated by `contract_gate.rs` on first call) and the direct-mode `ComposioTool` provider (`tools/direct.rs`). Scope elevation is deliberately NOT an agent tool — the user toggles it in the UI. Visibility/execution is gated by curated catalogs (`providers::` contract re-exports) + per-toolkit user-scope prefs and sandbox mode; unparseable slugs default to `Write` (fail-closed).+From `tools.rs` (`all_composio_agent_tools`, registered only when `agent::subagent_host::user_is_signed_in_to_composio` is true): `composio_list_toolkits`, `composio_list_connections`, `composio_authorize`, `composio_connect` (inline OAuth approval card, #3993), `composio_list_tools`, `composio_execute`. Plus `ComposioActionTool` (one tool per action, spawned for `integrations_agent`, gated by `contract_gate.rs` on first call) and the direct-mode `ComposioTool` provider (`tools/direct.rs`). Scope elevation is deliberately NOT an agent tool, the user toggles it in the UI. Visibility/execution is gated by curated catalogs (`providers::` contract re-exports) + per-toolkit user-scope prefs and sandbox mode; unparseable slugs default to `Write` (fail-closed).## EventsSubscribers/handlers for trigger and config-change events still live in `crate::memory::sync::composio::bus` (re-exported here via `bus.rs`). All three are registered by one call, `register_composio_trigger_subscriber()`, from `crates/openhuman-core/src/core/jsonrpc.rs` (~2158, right after `init_composio_trigger_history`):-- **`ComposioTriggerSubscriber`** — reacts to `DomainEvent::ComposioTriggerReceived` (published by `platform::socket::event_handlers` when the backend emits `composio:trigger`); archives the event to `trigger_history` and routes it through `agent::triage::run_triage` unless `OPENHUMAN_TRIGGER_TRIAGE_DISABLED`, `composio.triage_disabled`, or `composio.triage_disabled_toolkits` opts out.-- **`ComposioConnectionCreatedSubscriber`** — reacts to `DomainEvent::ComposioConnectionCreated` (published by `composio_authorize`); waits for the connection to go active, invalidates and eagerly warms the integrations cache, then runs the initial profile fetch + sync.-- **`ComposioConfigChangedSubscriber`** — reacts to `DomainEvent::ComposioConfigChanged` (mode/api-key changes).+- **`ComposioTriggerSubscriber`**, reacts to `DomainEvent::ComposioTriggerReceived` (published by `platform::socket::event_handlers` when the backend emits `composio:trigger`); archives the event to `trigger_history` and routes it through `agent::triage::run_triage` unless `OPENHUMAN_TRIGGER_TRIAGE_DISABLED`, `composio.triage_disabled`, or `composio.triage_disabled_toolkits` opts out.+- **`ComposioConnectionCreatedSubscriber`**, reacts to `DomainEvent::ComposioConnectionCreated` (published by `composio_authorize`); waits for the connection to go active, invalidates and eagerly warms the integrations cache, then runs the initial profile fetch + sync.+- **`ComposioConfigChangedSubscriber`**, reacts to `DomainEvent::ComposioConfigChanged` (mode/api-key changes).Published from `ops/` via `crate::core::bus::BUS.publish` (`crate::core::events::DomainEvent`): `DomainEvent::ComposioConnectionCreated` (authorize), `DomainEvent::ComposioConnectionDeleted` (delete), `DomainEvent::ComposioActionExecuted` (execute success/failure, with cost + elapsed).@@ -164,50 +164,50 @@ Published from `ops/` via `crate::core::bus::BUS.publish` (`crate::core::events:## Dependencies-- `crate::integrations` — shared `IntegrationClient` (Bearer JWT, timeouts, envelope parsing, proxy) backing backend-mode calls.-- `crate::config` — `Config` / `ComposioConfig` (`mode`, `entity_id`), `config::rpc` config loading.-- `crate::modules` — loads the `tinyconnectors` native module that `module_client.rs` calls into (behind the `modules` feature).-- `tinyconnectors_bus` — the wire contract (member names, payload types) for the `tinyconnectors` module call surface; a plain dependency, not feature-gated.-- `tinymemory_api::composio` — curated catalogs, scope verdicts, identity vocabulary, and task-fetch types (`providers/mod.rs`, `identity_store.rs`, `profile_md.rs`).-- `crate::memory::binding` — the workspace's bound memory driver. Connection-scoped cleanup deletes through `MemorySourceSink::forget_matching`; identity facets and user-scope prefs are also read/written through this binding.-- `crate::memory::sync::composio` — still owns the trigger/config-change bus subscribers (this module re-exports them via `bus.rs`) and the `slack` RPC layer re-exported from `providers/mod.rs`.-- `crate::agent::harness` — sandbox mode (`current_sandbox_mode` / `SandboxMode`) for tool gating; `current_task_recency_window` consumed by `task_window.rs`.-- `tinytools` — `Tool`, `ToolResult`, `ToolCategory`, `PermissionLevel`, `ToolCallOptions`.-- `crate::security` — `SecurityPolicy` / `ToolOperation` for direct-tool gating.-- `crate::security::credentials` — encrypted store for the direct-mode API key.-- `crate::agent::prompts`, `agent::prompts` — prompt/profile injection of connected identities.-- `crate::core::all` — `ControllerFuture` / `RegisteredController` registry types.-- `crate::core::bus` (`BUS`) / `crate::core::events::DomainEvent` — event publish/subscribe.-- `crate::core::observability` — Sentry error classification/reporting.-- `crate::rpc` — `RpcOutcome<T>`.+- `crate::integrations`: shared `IntegrationClient` (Bearer JWT, timeouts, envelope parsing, proxy) backing backend-mode calls.+- `crate::config`: `Config` / `ComposioConfig` (`mode`, `entity_id`), `config::rpc` config loading.+- `crate::modules`: loads the `tinyconnectors` native module that `module_client.rs` calls into (behind the `modules` feature).+- `tinyconnectors_bus`: the wire contract (member names, payload types) for the `tinyconnectors` module call surface; a plain dependency, not feature-gated.+- `tinymemory_api::composio`: curated catalogs, scope verdicts, identity vocabulary, and task-fetch types (`providers/mod.rs`, `identity_store.rs`, `profile_md.rs`).+- `crate::memory::binding`: the workspace's bound memory driver. Connection-scoped cleanup deletes through `MemorySourceSink::forget_matching`; identity facets and user-scope prefs are also read/written through this binding.+- `crate::memory::sync::composio`: still owns the trigger/config-change bus subscribers (this module re-exports them via `bus.rs`) and the `slack` RPC layer re-exported from `providers/mod.rs`.+- `crate::agent::harness`: sandbox mode (`current_sandbox_mode` / `SandboxMode`) for tool gating; `current_task_recency_window` consumed by `task_window.rs`.+- `tinytools`: `Tool`, `ToolResult`, `ToolCategory`, `PermissionLevel`, `ToolCallOptions`.+- `crate::security`: `SecurityPolicy` / `ToolOperation` for direct-tool gating.+- `crate::security::credentials`: encrypted store for the direct-mode API key.+- `crate::agent::prompts`, `agent::prompts`: prompt/profile injection of connected identities.+- `crate::core::all`: `ControllerFuture` / `RegisteredController` registry types.+- `crate::core::bus` (`BUS`) / `crate::core::events::DomainEvent`: event publish/subscribe.+- `crate::core::observability`: Sentry error classification/reporting.+- `crate::rpc`: `RpcOutcome<T>`.## Used by-- `crates/openhuman-core/src/core/all.rs` — registers the controllers.-- `crates/openhuman-core/src/tools/{mod,ops}.rs`, `tools/schemas/composio.rs` — wires agent tools into the tool registry.-- `crates/openhuman-core/src/core/jsonrpc.rs` — at startup initializes trigger history and registers the three bus subscribers.-- `crates/openhuman-core/src/channels/runtime/startup/start_channels.rs` (`start_channels`) — the one caller of `start_periodic_sync()`. `core/runtime/services.rs`'s `composio_integration_sync` job only runs `memory::sources::reconcile::ensure_composio_sources`; its comment explains why the periodic loop is not started there.-- `crates/openhuman-core/src/agent/**` — session-host/subagent spawning (`integrations_agent`), triage escalation and debug (e.g. `agent/subagent_host/`, `agent/orchestration/tools/`, `agent/debug/mod.rs`).-- `crates/openhuman-core/src/platform/socket/event_handlers.rs` — parses `composio:trigger` and publishes `ComposioTriggerReceived`.-- `crates/openhuman-core/src/agent/learning/linkedin_enrichment*.rs`, `agent/learning/profile_md_renderer.rs` — connected-identity enrichment consumers.-- `crates/openhuman-core/src/agent/prompts/connected_identities.rs` — renders connected identities into the agent prompt.-- `crates/openhuman-core/src/skills/preflight.rs` — identity gate via `connection_identity`.-- `crates/openhuman-core/src/security/credentials/ops/composio.rs` — direct-mode API key storage.-- `crates/openhuman-core/src/channels/runtime/dispatch/routing.rs` — channel routing over connected integrations.-- `crates/openhuman-core/src/flows/**` (`ops/catalog.rs`, `ops/connection_ref_gate.rs`, `ops/tool_contract_gate.rs`, `ops/connections.rs`, `ops/wiring_warnings.rs`, `ops/approval_manifest.rs`, `ops/builder.rs`, `tinyflows/caps/tools/composio.rs`) — workflow builder capability adapters over the catalog.-- `crates/openhuman-core/src/integrations/task_sources/**` — re-exports `NormalizedTask`/`TaskContainer`/`TaskFetchFilter`/`TaskKind` from `providers/mod.rs` (its fetch stage is stubbed since `ComposioProvider::fetch_tasks` went away).-- `crates/openhuman-core/src/memory/**` (`ops/sync.rs`, `sources/rpc/registry_crud.rs`/`source_sync.rs`/`status_toolkits.rs`/`apply_all.rs`, `tree/tree/mod.rs`) — memory sync and read paths over Composio-sourced data.-- `crates/openhuman-core/src/modules/{connectors_tests,memory_host}.rs` — module loader tests/wiring for the connector bridge.-- `crates/openhuman-core/src/core/observability.rs` — matches `direct_auth::COMPOSIO_INVALID_API_KEY_ANCHOR` / `_USER_MESSAGE` when classifying errors.+- `crates/openhuman-core/src/core/all.rs`: registers the controllers.+- `crates/openhuman-core/src/tools/{mod,ops}.rs`, `tools/schemas/composio.rs`: wires agent tools into the tool registry.+- `crates/openhuman-core/src/core/jsonrpc.rs`: at startup initializes trigger history and registers the three bus subscribers.+- `crates/openhuman-core/src/channels/runtime/startup/start_channels.rs` (`start_channels`), the one caller of `start_periodic_sync()`. `core/runtime/services.rs`'s `composio_integration_sync` job only runs `memory::sources::reconcile::ensure_composio_sources`; its comment explains why the periodic loop is not started there.+- `crates/openhuman-core/src/agent/**`: session-host/subagent spawning (`integrations_agent`), triage escalation and debug (e.g. `agent/subagent_host/`, `agent/orchestration/tools/`, `agent/debug/mod.rs`).+- `crates/openhuman-core/src/platform/socket/event_handlers.rs`: parses `composio:trigger` and publishes `ComposioTriggerReceived`.+- `crates/openhuman-core/src/agent/learning/linkedin_enrichment*.rs`, `agent/learning/profile_md_renderer.rs`: connected-identity enrichment consumers.+- `crates/openhuman-core/src/agent/prompts/connected_identities.rs`: renders connected identities into the agent prompt.+- `crates/openhuman-core/src/skills/preflight.rs`: identity gate via `connection_identity`.+- `crates/openhuman-core/src/security/credentials/ops/composio.rs`: direct-mode API key storage.+- `crates/openhuman-core/src/channels/runtime/dispatch/routing.rs`: channel routing over connected integrations.+- `crates/openhuman-core/src/flows/**` (`ops/catalog.rs`, `ops/connection_ref_gate.rs`, `ops/tool_contract_gate.rs`, `ops/connections.rs`, `ops/wiring_warnings.rs`, `ops/approval_manifest.rs`, `ops/builder.rs`, `tinyflows/caps/tools/composio.rs`), workflow builder capability adapters over the catalog.+- `crates/openhuman-core/src/integrations/task_sources/**`: re-exports `NormalizedTask`/`TaskContainer`/`TaskFetchFilter`/`TaskKind` from `providers/mod.rs` (its fetch stage is stubbed since `ComposioProvider::fetch_tasks` went away).+- `crates/openhuman-core/src/memory/**` (`ops/sync.rs`, `sources/rpc/registry_crud.rs`/`source_sync.rs`/`status_toolkits.rs`/`apply_all.rs`, `tree/tree/mod.rs`), memory sync and read paths over Composio-sourced data.+- `crates/openhuman-core/src/modules/{connectors_tests,memory_host}.rs`: module loader tests/wiring for the connector bridge.+- `crates/openhuman-core/src/core/observability.rs`: matches `direct_auth::COMPOSIO_INVALID_API_KEY_ANCHOR` / `_USER_MESSAGE` when classifying errors.## Notes / gotchas-- **`bus.rs` is a compatibility shim** — trigger/config-change subscribers still live under `crates/openhuman-core/src/memory/sync/composio/`. **`periodic.rs` and `providers/mod.rs` are not shims anymore** — read their own module docs; both were rewritten host-side or reunified from a contract crate after tinymemory v1.13.4 deleted the in-process Composio pipeline they used to glob-import.+- **`bus.rs` is a compatibility shim**, trigger/config-change subscribers still live under `crates/openhuman-core/src/memory/sync/composio/`. **`periodic.rs` and `providers/mod.rs` are not shims anymore**, read their own module docs; both were rewritten host-side or reunified from a contract crate after tinymemory v1.13.4 deleted the in-process Composio pipeline they used to glob-import.- **Mode-aware routing (#1710)**: the `ops/` layer calls the connector module (`module_client::call*`) for every member, and the module reconciles the backend/direct route from live config on each call, so a `composio.mode` toggle is honoured per call. Two host-side exceptions: `list_connections` in direct mode uses `create_composio_client` + `direct_list_connections` (the v3 response mapper and loopback overrides live here), and the `composio_execute` agent tool still dispatches through `execute_dispatch.rs`. Operations a route does not offer (e.g. the toolkit allowlist or triggers in direct mode) come back as a named refusal, recognised by `module_client::is_unsupported_by_route`, and are rendered as empty rather than as an outage. `ops::error_utils::resolve_client` survives only for tests.- **`ops/` is split by concern** (see [Ops layout](#ops-layout)) rather than one large file; `pass_budget.rs` is the one piece of shared sync-pass plumbing every sync entry point calls through.- **Error classification matters for the UI**: `execute` may return pre-classified `[composio:error:<class>] …` strings (parsed by `app/src/lib/composio/formatters.ts`); `ops/execute.rs` preserves them rather than re-wrapping.- **Sentry funnel**: `report_composio_op_error` re-tags op-layer failures under `domain="composio"` with `failure="non_2xx"|"transport"` (+ extracted backend status) so transient 5xx leaks are dropped by `before_send` while genuine bugs surface.- **Type drift tolerance**: trigger types use `de_string_or_object` / `de_opt_string_or_object` to accept upstream fields that flip between string and object shapes.- **Direct-mode 401 short-circuit** (`direct_auth/mod.rs`): after `DIRECT_INVALID_API_KEY_THRESHOLD` (3) consecutive `401 Invalid API key` responses for the same fingerprinted key, further polls short-circuit with a stable user-facing message instead of re-hitting Composio.-- **Contract gate is per-action, per-turn** (`contract_gate.rs`, #4853): only gates `ComposioActionTool` (the per-action surface used by `integrations_agent`), not the generic `composio_execute` dispatcher, MCP bridges, or Workflow dispatchers — those are tracked as follow-up.+- **Contract gate is per-action, per-turn** (`contract_gate.rs`, #4853): only gates `ComposioActionTool` (the per-action surface used by `integrations_agent`), not the generic `composio_execute` dispatcher, MCP bridges, or Workflow dispatchers, those are tracked as follow-up.</content>diff --git a/crates/openhuman-core/src/integrations/file_storage/README.md b/crates/openhuman-core/src/integrations/file_storage/README.mdindex b895c2cba9..7c62cd1c76 100644--- a/crates/openhuman-core/src/integrations/file_storage/README.md+++ b/crates/openhuman-core/src/integrations/file_storage/README.md@@ -8,7 +8,7 @@ and TTL enforcement.## Responsibilities- Upload a file from the workspace, list stored files, generate presigned- download links, change visibility, and delete files — all proxied through+ download links, change visibility, and delete files, all proxied through`/agent-integrations/file-storage/*`.- Enforce that uploads read from, and downloads write into, the agent's`action_dir` (the agent's canonical read/write root); reject paths that@@ -53,7 +53,7 @@ alphanumeric/`-`/`_` charset before it is interpolated into the URL path- `resolve_upload_path` (`tools/helpers.rs`) resolves the `path` argumentrelative to `action_dir` if not absolute, canonicalizes both the workspaceroot and the candidate, and rejects the upload unless the canonicalized- path starts with the canonicalized `action_dir` — this also rejects a+ path starts with the canonicalized `action_dir`: this also rejects asymlink that resolves outside the workspace, and rejects non-regular files.- Downloads always land under `<action_dir>/storage-downloads/`; the targetfilename is sanitized (`sanitize_filename`) to strip path separators and@@ -91,13 +91,13 @@ outside `build_file_storage_tools`.## Dependencies-- `crate::integrations::IntegrationClient` (and `build_client`) — the shared+- `crate::integrations::IntegrationClient` (and `build_client`), the sharedbackend-proxied HTTP client; see the [parent README](../README.md).-- `crate::security::SecurityPolicy` — gates the mutating tools under+- `crate::security::SecurityPolicy`: gates the mutating tools underread-only autonomy.-- `tinytools` — `Tool`, `ToolResult`, `PermissionLevel`,+- `tinytools`: `Tool`, `ToolResult`, `PermissionLevel`,`ToolCategory`.-- `tinytools::ToolRunContext` — supplies the TinyAgents workspace root when+- `tinytools::ToolRunContext`: supplies the TinyAgents workspace root whenrunning inside an agent turn.## Testsdiff --git a/crates/openhuman-core/src/integrations/task_sources/README.md b/crates/openhuman-core/src/integrations/task_sources/README.mdindex 8edcd0528e..62571b807e 100644--- a/crates/openhuman-core/src/integrations/task_sources/README.md+++ b/crates/openhuman-core/src/integrations/task_sources/README.md@@ -1,6 +1,6 @@# task_sources-Proactive ingestion of work items from external tools. A **task source** is a user-configured pull from a Composio-backed provider (GitHub, Notion, Linear, ClickUp) with a per-provider filter. A periodic poll runs a fetch → dedup → enrich → route pipeline that records each item in the ingestion ledger and, for proactive sources, dispatches a triage turn so an agent can start working immediately. **The fetch stage is currently a stub**: `ComposioProvider::fetch_tasks` was deleted upstream (tinymemory v1.13.4) with no replacement, so `pipeline::fetch_tasks_unavailable` refuses every toolkit and only the surrounding stages (dedup, enrichment, routing, storage, reconciliation) are live — see [Notes](#notes--gotchas). The domain mirrors the `cron` layering: `mod.rs` is export-only, business logic lives in sibling modules, persistence is SQLite, and the RPC surface is wired through `schemas.rs`.+Proactive ingestion of work items from external tools. A **task source** is a user-configured pull from a Composio-backed provider (GitHub, Notion, Linear, ClickUp) with a per-provider filter. A periodic poll runs a fetch → dedup → enrich → route pipeline that records each item in the ingestion ledger and, for proactive sources, dispatches a triage turn so an agent can start working immediately. **The fetch stage is currently a stub**: `ComposioProvider::fetch_tasks` was deleted upstream (tinymemory v1.13.4) with no replacement, so `pipeline::fetch_tasks_unavailable` refuses every toolkit and only the surrounding stages (dedup, enrichment, routing, storage, reconciliation) are live, see [Notes](#notes--gotchas). The domain mirrors the `cron` layering: `mod.rs` is export-only, business logic lives in sibling modules, persistence is SQLite, and the RPC surface is wired through `schemas.rs`.## Responsibilities@@ -8,7 +8,7 @@ Proactive ingestion of work items from external tools. A **task source** is a us- Periodically poll enabled sources (`periodic.rs`) on a global 10-minute tick honoring per-source `interval_secs` (floored to 60s).- Translate a typed `FilterSpec` into the provider-agnostic `TaskFetchFilter` (`filter.rs`); the fetch itself is stubbed (`pipeline::fetch_tasks_unavailable`) until a task-fetch surface exists again.- Dedup ingested items with an edit-aware SHA-256 content hash; re-ingest only when the upstream task changed (`store.rs` + `pipeline.rs`).-- Deterministically enrich raw tasks into agent-ready ones — urgency heuristic, summary, linked assignee, templated agent prompt (`enrich.rs`).+- Deterministically enrich raw tasks into agent-ready ones, urgency heuristic, summary, linked assignee, templated agent prompt (`enrich.rs`).- Route enriched tasks: for proactive sources, dispatch a triage turn through the same path Composio webhooks use; collect-only sources stop at the ledger (`route.rs`).- Fire a one-shot fetch when a matching Composio connection is created (`bus.rs`).- Expose an `openhuman.task_sources_*` RPC surface for CRUD, manual fetch/sync, filter preview, container listing, ingested-task listing, and status (`schemas.rs` + `ops.rs`).@@ -22,13 +22,13 @@ Proactive ingestion of work items from external tools. A **task source** is a us| `crates/openhuman-core/src/integrations/task_sources/store.rs` | SQLite persistence (`<workspace>/task_sources/sources.db`): `task_sources` + `ingested_tasks` tables, dedup `content_hash`, migrate-on-open. || `crates/openhuman-core/src/integrations/task_sources/ops.rs` | RPC-facing business logic returning `RpcOutcome<T>`: `list`/`get`/`add`/`update`/`remove`/`fetch`/`sync`/`list_tasks`/`preview_filter`/`list_databases`/`status`. || `crates/openhuman-core/src/integrations/task_sources/schemas.rs` | `task_sources` controller schemas + `all_controller_schemas` / `all_registered_controllers` + thin `handle_*` param parsers delegating to `ops.rs`. |-| `crates/openhuman-core/src/integrations/task_sources/pipeline.rs` | `run_source_once` — the infallible fetch → dedup → enrich → route pass shared by poll, manual RPC, and connection hook; publishes domain events. Holds the `fetch_tasks_unavailable` stub and its rationale doc comment. |-| `crates/openhuman-core/src/integrations/task_sources/filter.rs` | `to_fetch_filter` — flattens a `FilterSpec` variant into the shared `TaskFetchFilter`. |+| `crates/openhuman-core/src/integrations/task_sources/pipeline.rs` | `run_source_once`: the infallible fetch → dedup → enrich → route pass shared by poll, manual RPC, and connection hook; publishes domain events. Holds the `fetch_tasks_unavailable` stub and its rationale doc comment. |+| `crates/openhuman-core/src/integrations/task_sources/filter.rs` | `to_fetch_filter`: flattens a `FilterSpec` variant into the shared `TaskFetchFilter`. || `crates/openhuman-core/src/integrations/task_sources/enrich.rs` | Deterministic, dependency-free `enrich_task`: urgency heuristic, summary, linked assignee, agent prompt. No LLM call. |-| `crates/openhuman-core/src/integrations/task_sources/route.rs` | `route_enriched` — dispatches a scheduler-gated triage turn for proactive sources; collect-only sources are a no-op past the ledger. |-| `crates/openhuman-core/src/integrations/task_sources/periodic.rs` | `start_periodic_poll` — global tick scheduler; per-source due-timing in a process-global map; `run_one_tick` is `pub(crate)` for tests. |-| `crates/openhuman-core/src/integrations/task_sources/bus.rs` | `TaskSourcesConnectionSubscriber` + `register_task_sources_subscriber` — one-shot fetch on `ComposioConnectionCreated`. |-| `crates/openhuman-core/src/integrations/task_sources/tools.rs` | LLM-callable wrappers over `ops.rs` — see [Agent tools](#agent-tools) below. |+| `crates/openhuman-core/src/integrations/task_sources/route.rs` | `route_enriched`: dispatches a scheduler-gated triage turn for proactive sources; collect-only sources are a no-op past the ledger. |+| `crates/openhuman-core/src/integrations/task_sources/periodic.rs` | `start_periodic_poll`: global tick scheduler; per-source due-timing in a process-global map; `run_one_tick` is `pub(crate)` for tests. |+| `crates/openhuman-core/src/integrations/task_sources/bus.rs` | `TaskSourcesConnectionSubscriber` + `register_task_sources_subscriber`: one-shot fetch on `ComposioConnectionCreated`. |+| `crates/openhuman-core/src/integrations/task_sources/tools.rs` | LLM-callable wrappers over `ops.rs`: see [Agent tools](#agent-tools) below. || `crates/openhuman-core/src/integrations/task_sources/store_tests.rs` | Sibling test suite for `store.rs`. || `crates/openhuman-core/src/integrations/task_sources/pipeline_tests.rs` | Sibling test suite for `pipeline.rs`. || `crates/openhuman-core/src/integrations/task_sources/tools_tests.rs` | Sibling test suite for `tools.rs`. |@@ -56,7 +56,7 @@ Namespace `task_sources` (methods `openhuman.task_sources_<function>`):| `fetch` | Fetch one source now (`FetchReason::Manual`) and route new tasks. || `sync` | Run `fetch` for every enabled source; returns one `FetchOutcome` per source. || `list_tasks` | List recently ingested tasks for a source (newest first, default limit 50). |-| `preview_filter` | Dry-run a filter — fetch matching tasks WITHOUT routing/recording. Currently always errors (fetch stub). |+| `preview_filter` | Dry-run a filter, fetch matching tasks WITHOUT routing/recording. Currently always errors (fetch stub). || `list_databases` | List selectable containers (Notion databases) for a provider. Currently always errors (fetch stub). || `status` | Domain master switch + default interval + source counts. |@@ -64,7 +64,7 @@ Handlers parse params and delegate to `ops.rs`; schemas reference `FilterSpec`,## Agent tools-`tools.rs` wraps `ops.rs` as thin LLM-callable shims — each parses args,+`tools.rs` wraps `ops.rs` as thin LLM-callable shims, each parses args,calls the matching `ops` function, and emits its `RpcOutcome::value` as JSON.Read/observe tools are default-enabled; the persistent-config mutators aredefault-OFF and must be explicitly allowlisted via `tools/user_filter.rs`@@ -95,13 +95,13 @@ restored.Publishes (via `BUS.publish`, domain `"task_sources"` in `core/events.rs`):-- `DomainEvent::TaskSourceFetched` — after a successful fetch pass (counts: fetched/routed/skipped).-- `DomainEvent::TaskSourceTaskIngested` — per newly routed task (provider, external_id, title, urgency).-- `DomainEvent::TaskSourceFetchFailed` — on a failed pass (error string).+- `DomainEvent::TaskSourceFetched`: after a successful fetch pass (counts: fetched/routed/skipped).+- `DomainEvent::TaskSourceTaskIngested`: per newly routed task (provider, external_id, title, urgency).+- `DomainEvent::TaskSourceFetchFailed`: on a failed pass (error string).Subscribes:-- `DomainEvent::ComposioConnectionCreated` (domain filter `["composio"]`) via `TaskSourcesConnectionSubscriber` — fires a one-shot `ConnectionCreated` fetch for matching enabled sources. Registered once at startup (`register_task_sources_subscriber`, idempotent `OnceLock` handle).+- `DomainEvent::ComposioConnectionCreated` (domain filter `["composio"]`) via `TaskSourcesConnectionSubscriber`: fires a one-shot `ConnectionCreated` fetch for matching enabled sources. Registered once at startup (`register_task_sources_subscriber`, idempotent `OnceLock` handle).Startup wiring is split across three sites; both entry points are idempotent(`OnceLock`), so the overlap is harmless:@@ -120,29 +120,29 @@ Startup wiring is split across three sites; both entry points are idempotentSQLite at `<workspace_dir>/task_sources/sources.db` (WAL, 5s busy timeout, migrate-on-open):-- **`task_sources`** — configured sources: provider, optional connection_id/name, enabled, filter JSON, interval_secs, target, max_tasks_per_fetch, created_at, and last_fetch_at/last_status.-- **`ingested_tasks`** — per-(source, external_id) dedup ledger: edit-aware `content_hash` (SHA-256 over title/body/status/updated_at/url), normalized task `payload`, `ingested_at`. The `card_id` column is a leftover from when tasks were mirrored onto a todo board; it is written as `NULL` and kept only so older databases open unchanged. FK to `task_sources` with `ON DELETE CASCADE`.+- **`task_sources`**, configured sources: provider, optional connection_id/name, enabled, filter JSON, interval_secs, target, max_tasks_per_fetch, created_at, and last_fetch_at/last_status.+- **`ingested_tasks`**, per-(source, external_id) dedup ledger: edit-aware `content_hash` (SHA-256 over title/body/status/updated_at/url), normalized task `payload`, `ingested_at`. The `card_id` column is a leftover from when tasks were mirrored onto a todo board; it is written as `NULL` and kept only so older databases open unchanged. FK to `task_sources` with `ON DELETE CASCADE`.The additive idempotent `ingested_tasks.card_id` migration preserves older databases. App-level defaults (enabled flag, default interval, per-fetch cap, auto_proactive) live in config (`TaskSourcesConfig`), not the store.## Dependencies-- `crate::core::all` — `ControllerFuture`, `RegisteredController` for the RPC registry.-- `crate::core::bus` (`BUS`) + `crate::core::events::DomainEvent` — `BUS.publish`/`BUS.subscribe` for event publish/subscribe.-- `crate::config` (+ `config::rpc`) — `Config`, `load_config_with_timeout`; reads the `[task_sources]` block for defaults and the master switch.-- `crate::integrations::composio::providers` — `NormalizedTask`, `TaskContainer`, `TaskFetchFilter`, `TaskKind` (contract types re-exported from `tinymemory_api::composio::tasks`). The old `get_provider` / `ProviderContext` / `ComposioProvider::fetch_tasks` registry no longer exists; `mod.rs`'s intra-doc link to `fetch_tasks` is stale.-- `crate::agent::triage` — `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`; dispatches the proactive agent turn for `AgentTodoProactive` sources.-- `crate::cron::scheduler_gate` — `wait_for_capacity` capacity semaphore; gates proactive triage turns behind background-AI throttling.+- `crate::core::all`: `ControllerFuture`, `RegisteredController` for the RPC registry.+- `crate::core::bus` (`BUS`) + `crate::core::events::DomainEvent`: `BUS.publish`/`BUS.subscribe` for event publish/subscribe.+- `crate::config` (+ `config::rpc`), `Config`, `load_config_with_timeout`; reads the `[task_sources]` block for defaults and the master switch.+- `crate::integrations::composio::providers`: `NormalizedTask`, `TaskContainer`, `TaskFetchFilter`, `TaskKind` (contract types re-exported from `tinymemory_api::composio::tasks`). The old `get_provider` / `ProviderContext` / `ComposioProvider::fetch_tasks` registry no longer exists; `mod.rs`'s intra-doc link to `fetch_tasks` is stale.+- `crate::agent::triage`: `run_triage`, `apply_decision`, `TriageOutcome`, `TriggerEnvelope`; dispatches the proactive agent turn for `AgentTodoProactive` sources.+- `crate::cron::scheduler_gate`: `wait_for_capacity` capacity semaphore; gates proactive triage turns behind background-AI throttling.## Used by-- `crates/openhuman-core/src/core/all.rs` — registers controllers + schemas into the global RPC registry.-- `crates/openhuman-core/src/core/jsonrpc.rs` — at startup registers the connection subscriber (bus.rs).-- `crates/openhuman-core/src/core/runtime/services.rs` — at startup starts the periodic poll as part of the task-source polling bootstrap job.-- `crates/openhuman-core/src/channels/runtime/startup/start_channels.rs` — `start_channels` registers the subscriber and starts the poll for the channels runtime.-- `crates/openhuman-core/src/core/events.rs` — defines/classifies the three `TaskSource*` event variants under domain `"task_sources"`.-- `crates/openhuman-core/src/tools/mod.rs` — re-exports `tools.rs`'s agent tools into the global tool registry.-- `crates/openhuman-core/src/config/schema/` — `TaskSourcesConfig` block feeding domain defaults.+- `crates/openhuman-core/src/core/all.rs`: registers controllers + schemas into the global RPC registry.+- `crates/openhuman-core/src/core/jsonrpc.rs`: at startup registers the connection subscriber (bus.rs).+- `crates/openhuman-core/src/core/runtime/services.rs`: at startup starts the periodic poll as part of the task-source polling bootstrap job.+- `crates/openhuman-core/src/channels/runtime/startup/start_channels.rs`: `start_channels` registers the subscriber and starts the poll for the channels runtime.+- `crates/openhuman-core/src/core/events.rs`: defines/classifies the three `TaskSource*` event variants under domain `"task_sources"`.+- `crates/openhuman-core/src/tools/mod.rs`: re-exports `tools.rs`'s agent tools into the global tool registry.+- `crates/openhuman-core/src/config/schema/`: `TaskSourcesConfig` block feeding domain defaults.## Notes / gotchas@@ -152,5 +152,5 @@ The additive idempotent `ingested_tasks.card_id` migration preserves older datab- **Route-then-mark ordering.** A task is marked ingested only after routing succeeds, so a routing failure retries next pass instead of being silently dropped.- **Edit-aware dedup.** `content_hash` includes `url` deliberately (it drives external write-back); a changed hash re-ingests and re-routes.- **`update_source` TOCTOU.** Documented theoretical read-modify-write window across three connections; acceptable at settings-panel scale.-- **Enrichment is intentionally LLM-free** — deterministic and unit-testable; the heavy reasoning happens in the downstream triage turn.+- **Enrichment is intentionally LLM-free**, deterministic and unit-testable; the heavy reasoning happens in the downstream triage turn.- `clear_all` exists for the E2E `test_reset` RPC.diff --git a/crates/openhuman-core/src/mcp/README.md b/crates/openhuman-core/src/mcp/README.mdindex 7c6943ee99..73101bfe29 100644--- a/crates/openhuman-core/src/mcp/README.md+++ b/crates/openhuman-core/src/mcp/README.md@@ -1,4 +1,4 @@-# mcp — MCP host+# mcp, MCP hostHost-side half of Model Context Protocol support. Both transports, thestatic config-declared server set, the dynamic (Smithery/official-catalog)@@ -11,14 +11,14 @@ MCP hosts.## Responsibilities-- Hold the `tinymcp` service — one per workspace — and open it at boot+- Hold the `tinymcp` service, one per workspace, and open it at boot([`host`]).- Expose the `mcp_clients` RPC namespace (including the user's `mcp.json`document), the agent-facing `mcp_registry_*` tools, and theprompt-injection scan over remote tool definitions ([`registry`]).- Expose the RPC surface over the write-audit log ([`audit`]).- Run the `openhuman mcp` stdio/HTTP server that serves this application's- own tools to external MCP clients ([`server`]) — the *server* side, which+ own tools to external MCP clients ([`server`]), the *server* side, whichdid not move because it is bound to the tool registry, the permissionmodel and the agent turn machinery.@@ -29,8 +29,8 @@ than protocol:- **Prompt-injection detection** over remote tool definitions(`registry::tools_safe_for_agent`). The detector, its rules, and what a hit- means belong to this application's threat model. The *lexical* half —- control characters, prompt-template fences, length caps — lives in the+ means belong to this application's threat model. The *lexical* half,+ control characters, prompt-template fences, length caps, lives in thecontract instead, applied by the display accessors on every remotedescription.- **Events.** `tinymcp` reports what happened in its return values;@@ -41,31 +41,31 @@ than protocol:nothing.- **The proxy decision.** Whether a proxy applies to MCP traffic is decidedby this application's proxy scope setting, per-service list and no-proxy- list — `host::proxy_for_mcp` consults them and hands `tinymcp` the answer.+ list, `host::proxy_for_mcp` consults them and hands `tinymcp` the answer.## Key files| Path | Purpose || --- | --- || `mod.rs` | Family root, entry points, and the two re-export facades below. |-| `host.rs` / `host_tests.rs` | The per-workspace `tinymcp` service holder — see [its own doc comment](host.rs) for the shape (`HOSTS` map, `McpHost`, `for_config`/`try_service`/`init`, `client_config`, `proxy_for_mcp`). |+| `host.rs` / `host_tests.rs` | The per-workspace `tinymcp` service holder, see [its own doc comment](host.rs) for the shape (`HOSTS` map, `McpHost`, `for_config`/`try_service`/`init`, `client_config`, `proxy_for_mcp`). || [`registry/README.md`](registry/README.md) | `mcp_clients` RPC (incl. `mcp.json`), agent tools, reconnect-supervisor events. || [`audit/README.md`](audit/README.md) | `mcp_audit` RPC over the write-audit log. || [`server/README.md`](server/README.md) | The `openhuman mcp` server (this application as an MCP host's target). |## The two re-export modules-`mcp::http_client` and `mcp::config_servers` are not directories — they no+`mcp::http_client` and `mcp::config_servers` are not directories, they nolonger hold transport source, only `pub use` re-exports of `tinymcp`:-- `http_client` (ungated) — the Streamable HTTP transport:+- `http_client` (ungated), the Streamable HTTP transport:`tinymcp::transport::http::{McpHttpClient, McpHttpClientBuilder}`,`tinymcp::Error` as `McpError`, `redact_endpoint`, `render_tool_result`, andthe `tinymcp_bus` wire types (`McpRemoteTool`, `McpServerToolResult`,`McpSseEvent`, the OAuth challenge/metadata types). Always compiled becausethe ungated `gitbooks` tool (`tools/impl/network/gitbooks.rs`) dials`McpHttpClient`; `mcp::server`'s test-only HTTP round-trip names it too.-- `config_servers` (`mcp` feature) — the statically declared, TOML-configured+- `config_servers` (`mcp` feature), the statically declared, TOML-configuredserver set: `tinymcp::transport::stdio::McpStdioClient`,`McpRegistrySource`, `McpServerDefinition`, `McpServerRegistry`,`McpTransportClient`, and `tinymcp_bus::McpAuthConfig` re-exported as@@ -73,7 +73,7 @@ longer hold transport source, only `pub use` re-exports of `tinymcp`:`config::McpAuthConfig`, which the TOML file declares).Neither module implements a transport, a handshake, or OAuth discovery any-more — that all lives in `tinymcp` now. Read+more, that all lives in `tinymcp` now. Read[the tinymcp repo](https://github.com/tinyhumansai/tinymcp) for that half.## Startup wiring@@ -88,7 +88,7 @@ idempotent so the two callers can't double-register or double-spawn.## Compile-time gate (`mcp` feature)-`pub mod mcp;` is always compiled — the family root is a facade. `host` and+`pub mod mcp;` is always compiled, the family root is a facade. `host` and`http_client` are ungated because the startup path and always-on consumersreach them unconditionally. `registry`, `audit`, and `server` keeptheir own gate and their own `stub.rs`, so a build without the feature still@@ -98,14 +98,14 @@ serves `/rpc` without those namespaces; `config_servers` is simply## Dependencies- `tinymcp` (path dependency on `vendor/tinymcp`, `default-features = false`)- — the extracted client library.-- `tinymcp-bus` — the wire contract: payload types and member names, with no+, the extracted client library.+- `tinymcp-bus`: the wire contract: payload types and member names, with notransport and no runtime, also used to generate the desktop settingsschema.-- `crate::config` — `McpClientConfig`/`McpServerConfig`/`McpAuthConfig` and+- `crate::config`: `McpClientConfig`/`McpServerConfig`/`McpAuthConfig` andthe runtime proxy config `host::client_config`/`proxy_for_mcp` convertfrom.-- `crate::core::bus` / `crate::core::events` — `DomainEvent` publishing for+- `crate::core::bus` / `crate::core::events`: `DomainEvent` publishing foreverything that stayed host-side.See `Cargo.toml` (`crates/openhuman-core/Cargo.toml`, the `tinymcp` block)diff --git a/crates/openhuman-core/src/mcp/audit/README.md b/crates/openhuman-core/src/mcp/audit/README.mdindex 10aea0868f..1ea43c59ba 100644--- a/crates/openhuman-core/src/mcp/audit/README.md+++ b/crates/openhuman-core/src/mcp/audit/README.md@@ -1,7 +1,7 @@-# mcp/audit — write-audit RPC surface+# mcp/audit, write-audit RPC surface-RPC surface over the MCP write-audit log. The log itself — its store and-schema — moved to [`tinymcp`](https://github.com/tinyhumansai/tinymcp). What+RPC surface over the MCP write-audit log. The log itself, its store and+schema, moved to [`tinymcp`](https://github.com/tinyhumansai/tinymcp). Whatis here is the `mcp_audit` controller family and the payload types itspeaks, re-exported from the wire contract.@@ -36,7 +36,7 @@ schema's field comments repeat them for `/schema` readers only.## Compile-time gate (`mcp` feature)-`pub mod audit;` is always compiled — it is a facade. The RPC surface+`pub mod audit;` is always compiled, it is a facade. The RPC surface(`schemas`) is gated; with the `mcp` feature off, `stub` mirrors theconsumed surface (`record_write`, `list_writes`,`all_mcp_audit_internal_controllers`) so the audited subsystem simply@@ -44,23 +44,23 @@ appears never to have happened, rather than erroring.## Dependencies-- `tinymcp` (`AuditStore`) — the write-audit store, opened per workspace by+- `tinymcp` (`AuditStore`), the write-audit store, opened per workspace by`crate::mcp::host`.-- `tinymcp_bus` — `McpWriteListQuery`, `McpWriteRecord`, `NewMcpWriteRecord`.-- `crate::mcp::host` — resolves the per-workspace `AuditStore` via+- `tinymcp_bus`: `McpWriteListQuery`, `McpWriteRecord`, `NewMcpWriteRecord`.+- `crate::mcp::host`: resolves the per-workspace `AuditStore` via`for_config`.- `crate::core::all` (`RegisteredController`, `ControllerFuture`) and- `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`) — the+ `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`), thecontroller registration types. Unlike the other RPC domains the handlerreturns a raw `{ "records": [...] }` object, not an `RpcOutcome`.## Used by-- `crates/openhuman-core/src/mcp/server/write_dispatch.rs` — `audit_write`+- `crates/openhuman-core/src/mcp/server/write_dispatch.rs`: `audit_write`/ `audit_write_rejection[_without_config]` call `audit::record_write` offthe hot path (`spawn_blocking`, or a thread when no runtime is current)for every MCP write-tool attempt, success and rejection; `record_write`resolves the per-workspace `mcp::host` service and writes through its`AuditStore`.-- `crates/openhuman-core/src/core/all.rs` — registers+- `crates/openhuman-core/src/core/all.rs`: registers`all_mcp_audit_internal_controllers()`.diff --git a/crates/openhuman-core/src/mcp/registry/README.md b/crates/openhuman-core/src/mcp/registry/README.mdindex c2824067ee..dedd855377 100644--- a/crates/openhuman-core/src/mcp/registry/README.md+++ b/crates/openhuman-core/src/mcp/registry/README.md@@ -1,8 +1,8 @@-# mcp/registry — user-declared MCP servers+# mcp/registry, user-declared MCP serversHost half of the dynamic, user-declared MCP server surface. The registry-itself — the Smithery and official catalogs, the SQLite store, the live-connection map, and the subprocess/browser-sign-in supervisor — moved to+itself, the Smithery and official catalogs, the SQLite store, the live+connection map, and the subprocess/browser-sign-in supervisor, moved to[`tinymcp`](https://github.com/tinyhumansai/tinymcp). What is left here iswhat belongs to this application: the `mcp_clients` RPC surface, the`mcp.json` document that is the only way a server is added or removed, the@@ -15,7 +15,7 @@ install tool and no setup agent: a user finds a server in the Registry tab,opens its own page, and declares it in `mcp.json`.The RPC namespace and the on-disk database filename are still `mcp_clients`,-unchanged across the move — existing frontend code and existing on-disk state+unchanged across the move, existing frontend code and existing on-disk statekeep working. The Rust module path is `crate::mcp::registry`.## Key files@@ -23,12 +23,12 @@ keep working. The Rust module path is `crate::mcp::registry`.| File | Role || --- | --- || `mod.rs` | Module declarations, the `connections`/`store`/`boot`/`supervisor`/`oauth` re-export facades, and `tools_safe_for_agent` (the prompt-injection scan). |-| `ops.rs` / `ops_tests.rs` | `mcp_clients_*` RPC handler bodies — each delegates to the service `mcp::host` holds. |+| `ops.rs` / `ops_tests.rs` | `mcp_clients_*` RPC handler bodies, each delegates to the service `mcp::host` holds. || `config_doc.rs` / `config_doc_tests.rs` | The `mcp.json` contract: how the store renders as a document (credential names only), what a written one may say, and the reconciliation helpers. || `config_ops.rs` | `mcp_clients_config_get` / `config_set`: replace the store with what the document declares. || `schemas/` (`mod.rs`, `registry.rs`, `handlers.rs`, `params.rs`), `schemas_tests.rs` | Controller schema registry and dispatch. || `supervisor_events.rs` / `supervisor_events_tests.rs` | Maps a supervisor tick's `TickReport` into `DomainEvent`s. |-| `bus.rs` / `bus_tests.rs` | `McpClientEventSubscriber` — logs lifecycle events for observability. |+| `bus.rs` / `bus_tests.rs` | `McpClientEventSubscriber`: logs lifecycle events for observability. || `tools.rs` / `tools_tests.rs` | Agent-facing `mcp_registry_*` tools, thin shims over `ops.rs`. || `action_tool.rs` / `action_tool_tests.rs` | One deferred agent tool per action on a connected server. Stable names and sanitized schemas enter `tool_search`; execution checks the current connection and routes through `ops.rs`. || `helpers.rs` | Shared identifier validation, workspace-service resolution, and env-key injection used by the handlers. |@@ -38,11 +38,11 @@ keep working. The Rust module path is `crate::mcp::registry`.`mod.rs` defines several thin facade modules rather than fresh logic:-- `types` — the payload vocabulary, entirely re-exported from `tinymcp_bus`+- `types`: the payload vocabulary, entirely re-exported from `tinymcp_bus`(`InstalledServer`, `McpTool`, `ConnStatus`, `Transport`, the Smitherycatalog types, …). A parallel set of types here would mean a conversion atevery call site that nothing checks.-- `connections` — a thin view over the live connection map the `mcp::host`+- `connections`: a thin view over the live connection map the `mcp::host`service holds: `connected_overview[_for_config]`,`all_connected_tools[_for_config]`, `tools_for`/`server_tools_for_config`,`is_connected[_for_config]`, `auth_hint_for[_config]`, `connect`,@@ -50,15 +50,15 @@ keep working. The Rust module path is `crate::mcp::registry`."nothing" (empty list / `false` / `None`) when the workspace has no openhost yet, rather than erroring; only `connect` returns an error in thatcase.-- `store` — the one direct reach into the registry's store that outlived the+- `store`: the one direct reach into the registry's store that outlived theextraction: `set_cached`, used by an end-to-end test to seed the upstreamresponse cache without a real catalog call.-- `boot` — `spawn_installed_servers`, connecting every enabled installed+- `boot`: `spawn_installed_servers`, connecting every enabled installedserver at startup; never fails (a broken third-party server is logged andskipped).-- `supervisor` — `run()`, the reconnect-supervisor loop: one task per+- `supervisor`: `run()`, the reconnect-supervisor loop: one task perprocess, walking every workspace host the process has opened each tick.-- `oauth` — `complete`, finishing a browser sign-in from the redirect+- `oauth`: `complete`, finishing a browser sign-in from the redirectcallback and reconnecting the server.## RPC surface@@ -67,7 +67,7 @@ keep working. The Rust module path is `crate::mcp::registry`.`registry_get`, `installed_list`, `update_env`, `uninstall`, `detect_auth`,`oauth_begin`, `connect`, `disconnect`, `status`, `tool_call`,`registry_settings_get`, `registry_settings_set`, `set_enabled`.-`config_ops.rs` adds `config_get` and `config_set` — the `mcp.json`+`config_ops.rs` adds `config_get` and `config_set`: the `mcp.json`document. All are registered by `schemas::all_registered_controllers`(`schemas/registry.rs`).@@ -76,20 +76,20 @@ uninstalled, a new one is inserted as an `InstalledServer` built straightfrom its declaration (`command`/`args` → stdio, `url` → HTTP-remote), and onewhose dial changed is rewritten under the same `server_id` so the row thefrontend and the connection map address stays the same row. Credentials are-the exception: `env` (stdio) and `headers` (HTTP) are write-only — a read-renders only `envKeys` and `authConfigured` — so an entry saved without a+the exception: `env` (stdio) and `headers` (HTTP) are write-only, a read+renders only `envKeys` and `authConfigured`: so an entry saved without acredential block keeps what is stored, and a key set to `""` removes that onevalue. Enabled servers that were added or rewritten are connected in thebackground; the status poll reports the outcome.What stayed host-side inside these handlers, on purpose:-- **Events** — `tinymcp` reports outcomes in its return values and publishes+- **Events**, `tinymcp` reports outcomes in its return values and publishesnothing; the handlers turn those into `DomainEvent`s because the vocabularyis this application's.-- **The prompt-injection scan** — `tools_safe_for_agent` filters remote tool+- **The prompt-injection scan**, `tools_safe_for_agent` filters remote tooldefinitions before they reach the agent.-- **The document** — `tinymcp` has no notion of `mcp.json`; the shape, the+- **The document**, `tinymcp` has no notion of `mcp.json`; the shape, therefusals and the reconciliation are this application's.## Reconnect-supervisor events@@ -100,8 +100,8 @@ What stayed host-side inside these handlers, on purpose:`ReconnectFailed`, `Parked`. Every event is stamped with the workspace whosehost was ticked, because one process supervises every workspace it hasopened over its life and a subscriber persisting an event (the notification-bridge) needs to file it under the right one. An answered probe — the-nominal case — is deliberately not an event; `tinymcp` logs it at trace+bridge) needs to file it under the right one. An answered probe, the+nominal case, is deliberately not an event; `tinymcp` logs it at tracelevel. These events reach the developer Event Log (`GET /events/domain`) and,for the stays-down/restored/parked cases, the desktop notification bridge.@@ -111,7 +111,7 @@ for the stays-down/restored/parked cases, the desktop notification bridge.`mcp_registry_installed_list`, `mcp_registry_status`,`mcp_registry_list_tools`, `mcp_registry_connect`,`mcp_registry_disconnect`, `mcp_registry_tool_call`,-`mcp_registry_uninstall` — thin shims over `ops.rs`. Discovery/observe/+`mcp_registry_uninstall`: thin shims over `ops.rs`. Discovery/observe/connect/call tools are default-ON; `uninstall` (a persistent write ofinstalled state) ships default-OFF, gated behind the `mcp_manage` toggle in`tools/user_filter.rs`. There is no install tool: servers are declared by@@ -129,33 +129,33 @@ same real type in both builds.## Dependencies-- `tinymcp` / `tinymcp_bus` — the extracted registry library and its wire+- `tinymcp` / `tinymcp_bus`: the extracted registry library and its wirecontract.-- `crate::mcp::host` — the per-workspace service holder every function here+- `crate::mcp::host`: the per-workspace service holder every function hereresolves through.-- `crate::core::bus` / `crate::core::events` — `DomainEvent` publishing.-- `crate::security::prompt_injection` — `scan_tool_definition`, used by+- `crate::core::bus` / `crate::core::events`: `DomainEvent` publishing.+- `crate::security::prompt_injection`: `scan_tool_definition`, used by`tools_safe_for_agent`.## Used by-- `crates/openhuman-core/src/core/all.rs` (~line 444) — registers+- `crates/openhuman-core/src/core/all.rs` (~line 444), registers`all_mcp_registry_registered_controllers()`.-- `crates/openhuman-core/src/mcp/mod.rs` — `start`/`start_boot_jobs` wire up+- `crates/openhuman-core/src/mcp/mod.rs`: `start`/`start_boot_jobs` wire up`bus::init()`, `boot::spawn_installed_servers`, and the reconnectsupervisor.- `tinymcp`'s live connection map is the process cache: startup connectsinstalled servers, and connect, disconnect, config updates, and reconnectsupdate the map. `connected_overview()` reads tool snapshots from that map;it does not call an MCP server on each chat turn.-- `crates/openhuman-core/src/core/jsonrpc.rs` — the `/oauth/mcp/callback`+- `crates/openhuman-core/src/core/jsonrpc.rs`: the `/oauth/mcp/callback`route calls `oauth::complete`.- `crates/openhuman-core/src/tools/registry/ops.rs` and- `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` —+ `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs`:read `mcp::registry::connections` to list connected servers/tools for thetool catalog and the orchestrator prompt.-- `crates/openhuman-core/src/agent/session_host/turn/core_turn.rs` — reads+- `crates/openhuman-core/src/agent/session_host/turn/core_turn.rs`: reads`connections::connected_overview()` when assembling a turn.-- `crates/openhuman-core/src/platform/about_app/catalog_auth_channels_team.rs` — the+- `crates/openhuman-core/src/platform/about_app/catalog_auth_channels_team.rs`: the`channels.mcp_registry_browse` / `mcp_server_install` /`mcp_server_connect` capability entries.diff --git a/crates/openhuman-core/src/mcp/server/README.md b/crates/openhuman-core/src/mcp/server/README.mdindex 72a381bd05..684a1c175e 100644--- a/crates/openhuman-core/src/mcp/server/README.md+++ b/crates/openhuman-core/src/mcp/server/README.md@@ -1,6 +1,6 @@# mcp/server-Opt-in **Model Context Protocol (MCP) server** that exposes a curated, security-gated slice of OpenHuman's tool surface (memory-tree reads/writes, core/agent introspection, subagent execution, SearXNG search) and bundled prompt assets to external MCP clients (Claude Desktop, Cursor, Windsurf, …). Started via `openhuman-core mcp` — stdio transport by default, or `--transport http` for Streamable HTTP + SSE on a local bind address. It is a JSON-RPC dispatcher, not a registered RPC domain: it has no `schemas.rs`/controllers and is wired only through `crates/openhuman-core/src/core/cli.rs`, translating each MCP `tools/call` into an existing registered core RPC method.+Opt-in **Model Context Protocol (MCP) server** that exposes a curated, security-gated slice of OpenHuman's tool surface (memory-tree reads/writes, core/agent introspection, subagent execution, SearXNG search) and bundled prompt assets to external MCP clients (Claude Desktop, Cursor, Windsurf, …). Started via `openhuman-core mcp`: stdio transport by default, or `--transport http` for Streamable HTTP + SSE on a local bind address. It is a JSON-RPC dispatcher, not a registered RPC domain: it has no `schemas.rs`/controllers and is wired only through `crates/openhuman-core/src/core/cli.rs`, translating each MCP `tools/call` into an existing registered core RPC method.## Responsibilities@@ -10,7 +10,7 @@ Opt-in **Model Context Protocol (MCP) server** that exposes a curated, security-- Enforce `SecurityPolicy` per call: read tools require `ToolOperation::Read`; `agent.run_subagent` and the three write tools require `ToolOperation::Act`.- Run write tools (`memory.store`, `memory.note`, `tree.tag`) through a dedicated write-dispatch + audit pipeline that records every attempt (success and rejection) to the MCP write-audit log.- Serve bundled prompt assets (`IDENTITY.md`, `SOUL.md`, `USER.md`, and each built-in subagent's `prompt.md`) as static MCP resources under the `openhuman://prompts/...` URI scheme.-- Provide two transports — newline-delimited JSON-RPC over stdio, and Axum-based Streamable HTTP + SSE with session-id + protocol-version handshakes and optional bearer auth.+- Provide two transports, newline-delimited JSON-RPC over stdio, and Axum-based Streamable HTTP + SSE with session-id + protocol-version handshakes and optional bearer auth.- Capture client provenance from `initialize` `clientInfo.name` into a per-session `source_type` (e.g. `mcp:claude-desktop`) used for audit attribution.## Key files@@ -19,26 +19,26 @@ Opt-in **Model Context Protocol (MCP) server** that exposes a curated, security-| --- | --- || `crates/openhuman-core/src/mcp/server/mod.rs` | Module docstring + private submodule decls; re-exports `run_http`/`run_http_reporting`/`HttpServerConfig`, `run_stdio_from_cli`, `ensure_local_http`/`LocalMcpEndpoint`, `current_subagent_depth`/`HEADER_SUBAGENT_DEPTH`, `tool_specs`/`McpToolSpec`. || `crates/openhuman-core/src/mcp/server/protocol.rs` | JSON-RPC 2.0 dispatch core: parses lines/values (single + batch), routes `initialize`/`ping`/`tools/*`/`resources/*`, builds success/error envelopes, negotiates protocol version. |-| `crates/openhuman-core/src/mcp/server/tools/` | Tool catalog and dispatch, split into `mod.rs` (facade), `types.rs` (`McpToolSpec`, `ToolCallError`, the limit/tag constants — stays ungated so `McpToolSpec` is one real type in both builds), `specs.rs` (`tool_specs`/`base_tool_specs`/`searxng_tool_spec` builders), `params.rs` (argument parsing/validation → RPC params), `dispatch.rs` (`call_tool`/`list_tools_result`, act-policy enforcement, subagent handlers). |+| `crates/openhuman-core/src/mcp/server/tools/` | Tool catalog and dispatch, split into `mod.rs` (facade), `types.rs` (`McpToolSpec`, `ToolCallError`, the limit/tag constants, stays ungated so `McpToolSpec` is one real type in both builds), `specs.rs` (`tool_specs`/`base_tool_specs`/`searxng_tool_spec` builders), `params.rs` (argument parsing/validation → RPC params), `dispatch.rs` (`call_tool`/`list_tools_result`, act-policy enforcement, subagent handlers). || `crates/openhuman-core/src/mcp/server/write_dispatch.rs` | Write/audit pipeline for `memory.store`/`memory.note`/`tree.tag`: config load, act-policy enforcement, RPC dispatch to `openhuman.memory_doc_put`, audit-record write (success/rejection) via `crate::mcp::audit::record_write`, PII-redacting arg summaries. || `crates/openhuman-core/src/mcp/server/resources.rs` | Static `RESOURCE_CATALOG` of compile-time-embedded (`include_str!`) prompt markdown; `resources/list`, `resources/templates/list` (always empty), `resources/read`. Test cross-checks catalog vs `agent::agents::BUILTINS`. |-| `crates/openhuman-core/src/mcp/server/session.rs` | `McpSession` — captures + normalizes client name from `initialize` into a `source_type`; first observation locks the value. |-| `crates/openhuman-core/src/mcp/server/http.rs` | Axum Streamable HTTP + SSE transport (`run_http`, `HttpServerConfig`): POST/GET/DELETE on `/`, session map, protocol-version checks, optional `Authorization: Bearer`, SSE keep-alive, session-id redaction. Gated on `all(feature = "mcp", feature = "http-server")` — the transport is axum-only. |+| `crates/openhuman-core/src/mcp/server/session.rs` | `McpSession`: captures + normalizes client name from `initialize` into a `source_type`; first observation locks the value. |+| `crates/openhuman-core/src/mcp/server/http.rs` | Axum Streamable HTTP + SSE transport (`run_http`, `HttpServerConfig`): POST/GET/DELETE on `/`, session map, protocol-version checks, optional `Authorization: Bearer`, SSE keep-alive, session-id redaction. Gated on `all(feature = "mcp", feature = "http-server")`: the transport is axum-only. || `crates/openhuman-core/src/mcp/server/local.rs` | Lazily-started, process-wide in-process loopback HTTP MCP server (`ensure_local_http`, `LocalMcpEndpoint`). Lets the sandboxed `claude` subprocess (Claude Code provider) reach OpenHuman's memory/tools over loopback without the MCP server inheriting Claude Code's OS jail; a per-process random bearer token stops any other local process from talking to it. || `crates/openhuman-core/src/mcp/server/subagent_depth.rs` | Per-delegation-chain depth tracking for `agent.run_subagent`, propagated across the loopback MCP HTTP hop via the `X-OpenHuman-Subagent-Depth` header so nested Claude Code subagent calls are bounded without penalizing unrelated parallel callers. || `crates/openhuman-core/src/mcp/server/stdio.rs` | CLI entry `run_stdio_from_cli` (arg parse: `--transport`/`--host`/`--port`/`--auth-token`/`-v`/`--help`), logging init, stdio read/write loop (`run_stdio`). |-| `crates/openhuman-core/src/mcp/server/stub.rs` | The `mcp`-less mirror of `run_stdio_from_cli`, `ensure_local_http`/`LocalMcpEndpoint`, and `tool_specs` — disabled-error / empty-catalog bodies so always-on callers (`core/cli.rs`, the Claude Code driver, `tools/registry/ops.rs`) keep a stable surface. |+| `crates/openhuman-core/src/mcp/server/stub.rs` | The `mcp`-less mirror of `run_stdio_from_cli`, `ensure_local_http`/`LocalMcpEndpoint`, and `tool_specs`: disabled-error / empty-catalog bodies so always-on callers (`core/cli.rs`, the Claude Code driver, `tools/registry/ops.rs`) keep a stable surface. || `crates/openhuman-core/src/mcp/server/tools_tests.rs` | Sibling `#[cfg(test)]` suite for `tools/` (via `#[path]`). |## Public surfaceRe-exported from `mod.rs`:-- `run_stdio_from_cli(args: &[String]) -> Result<()>` — CLI entry point; builds its own tokio runtime and selects stdio vs HTTP transport.-- `run_http(config: HttpServerConfig) -> Result<()>`, `run_http_reporting` (the same, plus a oneshot that reports the bound address; `local.rs` uses it), and `HttpServerConfig { bind_addr, auth_token }` — HTTP/SSE server (`mcp` + `http-server`).-- `ensure_local_http() -> Result<LocalMcpEndpoint>` and `LocalMcpEndpoint { addr, token }` — the loopback in-process server for the Claude Code driver.-- `current_subagent_depth()` / `HEADER_SUBAGENT_DEPTH` — the delegation-depth hop for `agent.run_subagent`.-- `tool_specs() -> Vec<McpToolSpec>` and `McpToolSpec { name, title, description, rpc_method, input_schema, annotations }` — the advertised tool catalog.+- `run_stdio_from_cli(args: &[String]) -> Result<()>`: CLI entry point; builds its own tokio runtime and selects stdio vs HTTP transport.+- `run_http(config: HttpServerConfig) -> Result<()>`, `run_http_reporting` (the same, plus a oneshot that reports the bound address; `local.rs` uses it), and `HttpServerConfig { bind_addr, auth_token }`: HTTP/SSE server (`mcp` + `http-server`).+- `ensure_local_http() -> Result<LocalMcpEndpoint>` and `LocalMcpEndpoint { addr, token }`: the loopback in-process server for the Claude Code driver.+- `current_subagent_depth()` / `HEADER_SUBAGENT_DEPTH`: the delegation-depth hop for `agent.run_subagent`.+- `tool_specs() -> Vec<McpToolSpec>` and `McpToolSpec { name, title, description, rpc_method, input_schema, annotations }`: the advertised tool catalog.## RPC / controllers@@ -54,7 +54,7 @@ This module exposes **no** registered core RPC methods (no `schemas.rs`, no cont| `tree.list_sources` | `openhuman.memory_tree_list_sources` || `memory.store` / `memory.note` / `tree.tag` | `openhuman.memory_doc_put` || `searxng_search` | `openhuman.tools_searxng_search` |-| `core.list_tools` / `core.tool_instructions` / `agent.list_subagents` / `agent.run_subagent` | (no RPC mapping — handled in-process via `Agent` / `AgentDefinitionRegistry`) |+| `core.list_tools` / `core.tool_instructions` / `agent.list_subagents` / `agent.run_subagent` | (no RPC mapping, handled in-process via `Agent` / `AgentDefinitionRegistry`) |## Agent tools@@ -71,32 +71,32 @@ None. This module publishes/subscribes no `DomainEvent`s and has no `bus.rs`.## Persistence-No `store.rs`. The only durable side effect is the **MCP write-audit log**, written via `crate::mcp::audit::record_write` (the sibling `mcp::audit` domain) for every write-tool attempt — including pre-dispatch rejections. Audit rows store a PII-redacted `args_summary` (titles truncated to 128 chars; `content`/`note_text` bodies omitted, only lengths/counts kept), `client_info`, success flag, and resulting `document_id`. Audit inserts run off the hot path via `spawn_blocking` (or a thread fallback). HTTP session records (`Mcp-Session-Id` → negotiated protocol version) are kept in an in-memory map only.+No `store.rs`. The only durable side effect is the **MCP write-audit log**, written via `crate::mcp::audit::record_write` (the sibling `mcp::audit` domain) for every write-tool attempt, including pre-dispatch rejections. Audit rows store a PII-redacted `args_summary` (titles truncated to 128 chars; `content`/`note_text` bodies omitted, only lengths/counts kept), `client_info`, success flag, and resulting `document_id`. Audit inserts run off the hot path via `spawn_blocking` (or a thread fallback). HTTP session records (`Mcp-Session-Id` → negotiated protocol version) are kept in an in-memory map only.## Dependencies-- `crate::core::all` — `try_invoke_registered_rpc`, `schema_for_rpc_method`, `validate_params`: dispatch MCP tool calls into the registered core RPC layer and validate params against controller schemas.-- `crate::core::logging` (`CliLogDefault`, `init_for_cli_run`) — install the stderr tracing subscriber for the MCP subprocess.-- `crate::config` (`Config`, `rpc::load_config_with_timeout`, `McpAuthConfig`/`McpClientIdentityConfig` in tests) — load config for policy/searxng gating and per-call config.-- `crate::security` (`SecurityPolicy`, `ToolOperation`) — enforce read/act autonomy policy per tool call.-- `crate::agent` (`Agent`, `registry::agents::BUILTINS`, `harness::AgentDefinitionRegistry`) — build the orchestrator agent for `core.list_tools`/`core.tool_instructions`, list/run subagents, and cross-check the resource catalog.-- `tinyinference_llm::tool::ToolSchema` — directly materialize model-visible tool declarations for `core.tool_instructions`.-- `tinyagents_harness::tool::prompt_tool_instructions` — render the markdown tool-use instructions block for `core.tool_instructions`.-- `crate::tools` (`SEARXNG_MAX_RESULTS`, `normalize_categories`) — SearXNG bounds + category normalization for `searxng_search`.-- `crate::mcp::audit` (`record_write`, `NewMcpWriteRecord`, list/query helpers in tests) — durable write-audit log.-- `crate::mcp::http_client::McpHttpClient` — round-trip test harness for the HTTP transport (test-only).+- `crate::core::all`: `try_invoke_registered_rpc`, `schema_for_rpc_method`, `validate_params`: dispatch MCP tool calls into the registered core RPC layer and validate params against controller schemas.+- `crate::core::logging` (`CliLogDefault`, `init_for_cli_run`), install the stderr tracing subscriber for the MCP subprocess.+- `crate::config` (`Config`, `rpc::load_config_with_timeout`, `McpAuthConfig`/`McpClientIdentityConfig` in tests), load config for policy/searxng gating and per-call config.+- `crate::security` (`SecurityPolicy`, `ToolOperation`), enforce read/act autonomy policy per tool call.+- `crate::agent` (`Agent`, `registry::agents::BUILTINS`, `harness::AgentDefinitionRegistry`), build the orchestrator agent for `core.list_tools`/`core.tool_instructions`, list/run subagents, and cross-check the resource catalog.+- `tinyinference_llm::tool::ToolSchema`: directly materialize model-visible tool declarations for `core.tool_instructions`.+- `tinyagents_harness::tool::prompt_tool_instructions`: render the markdown tool-use instructions block for `core.tool_instructions`.+- `crate::tools` (`SEARXNG_MAX_RESULTS`, `normalize_categories`), SearXNG bounds + category normalization for `searxng_search`.+- `crate::mcp::audit` (`record_write`, `NewMcpWriteRecord`, list/query helpers in tests), durable write-audit log.+- `crate::mcp::http_client::McpHttpClient`: round-trip test harness for the HTTP transport (test-only).- External crates: `axum`/`tokio`/`tokio-stream` (HTTP+SSE), `serde_json`, `uuid`, `sha2`/`hex` (session-id redaction, slug fallback hash), `chrono` (audit timestamps).## Used by-- `crates/openhuman-core/src/core/cli.rs` — dispatches `mcp` / `mcp-server` subcommands to `run_stdio_from_cli`; the only production entry point for the stdio/HTTP transports. `crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs` lists it as `intelligence.mcp_server`.-- `crates/openhuman-core/src/inference/provider/claude_code/driver.rs` — calls `ensure_local_http` on each Claude Code turn to hand the sandboxed `claude` subprocess a loopback MCP endpoint.-- `crates/openhuman-core/src/tools/registry/ops.rs` — reads `McpToolSpec`/`tool_specs()` (via `crate::mcp::server::McpToolSpec`) to fold this server's advertised tools into the agent tool registry catalog.+- `crates/openhuman-core/src/core/cli.rs`: dispatches `mcp` / `mcp-server` subcommands to `run_stdio_from_cli`; the only production entry point for the stdio/HTTP transports. `crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs` lists it as `intelligence.mcp_server`.+- `crates/openhuman-core/src/inference/provider/claude_code/driver.rs`: calls `ensure_local_http` on each Claude Code turn to hand the sandboxed `claude` subprocess a loopback MCP endpoint.+- `crates/openhuman-core/src/tools/registry/ops.rs`: reads `McpToolSpec`/`tool_specs()` (via `crate::mcp::server::McpToolSpec`) to fold this server's advertised tools into the agent tool registry catalog.- The other `mcp/` members (`mcp::host`, `mcp::registry`, `mcp::audit`) are siblings in the broader MCP feature set, not consumers of this server's code paths. `mcp::http_client` is a re-export module of `tinymcp`, used here only by the test-only `McpHttpClient` HTTP round-trip.## Notes / gotchas-- **Not a controller-registry domain.** Don't look for `schemas.rs`/`all_controller_schemas` — exposure is via the CLI only, and tool calls re-enter the registry through `core::all`.+- **Not a controller-registry domain.** Don't look for `schemas.rs`/`all_controller_schemas`: exposure is via the CLI only, and tool calls re-enter the registry through `core::all`.- **`ToolCallError` variant → JSON-RPC code is deliberate:** `InvalidParams` → `-32602` (client-actionable, including policy denials so the reason text surfaces), `Internal` → `-32603` (config load / platform failures). Policy denials are intentionally `InvalidParams`, not `Internal`.- **Explicit rejection over silent clamping** throughout: over-cap `k`, oversize/over-count tags, blank required strings, and unexpected arguments all error rather than being trimmed/dropped.- **Write audit is fire-and-forget but mandatory:** rejections are audited even before config is loaded (`audit_write_rejection_without_config`), and `dispatch_write_tool` returns `Ok(tool_error(...))` (not `Err`) on RPC-handler failure so the client gets an MCP `isError` result while the failure is still recorded.diff --git a/crates/openhuman-core/src/media/README.md b/crates/openhuman-core/src/media/README.mdindex 3c829b9c15..e0c8bbc2e9 100644--- a/crates/openhuman-core/src/media/README.md+++ b/crates/openhuman-core/src/media/README.md@@ -8,13 +8,13 @@ thing the group tags is the `media_*` tool names (`tool_group()` in## Members-- [`generation`](generation/mod.rs) — the `media_generate_*` agent tools+- [`generation`](generation/mod.rs), the `media_generate_*` agent tools(image/video via GMI, proxied through the TinyHumans backend). Wired: builtby `build_media_tools()` and registered from`crates/openhuman-core/src/tools/ops.rs` under `#[cfg(feature = "media")]`.The builder returns no tools when `integrations::build_client()` yields no`IntegrationClient` for the config.-- [`image`](image/README.md) — image tool contracts scaffold+- [`image`](image/README.md), image tool contracts scaffold(`image_generation`, `view_image`). Currently unwired (#2997); nothingoutside `media/image/` references its types.@@ -44,9 +44,9 @@ per-modality wait budget elapses, download the resulting media intoExported tools (`tools.rs`):-- `MediaGenerateImageTool` — `name() == "media_generate_image"`-- `MediaGenerateVideoTool` — `name() == "media_generate_video"`-- `MediaListModelsTool` — `name() == "media_list_models"`+- `MediaGenerateImageTool`: `name() == "media_generate_image"`+- `MediaGenerateVideoTool`: `name() == "media_generate_video"`+- `MediaListModelsTool`: `name() == "media_list_models"`Tests: `generation/download_tests.rs` (file-extension derivation fromcontent type, URL, then kind), `generation/tools_tests.rs` (tool schemas anddiff --git a/crates/openhuman-core/src/search/tools/README.md b/crates/openhuman-core/src/search/tools/README.mdindex c98259a016..3684688cf7 100644--- a/crates/openhuman-core/src/search/tools/README.md+++ b/crates/openhuman-core/src/search/tools/README.md@@ -1,54 +1,55 @@-# Search Tools+# Search toolsAgent-facing `Tool` implementations for every search provider. One file perprovider family; `mod.rs` re-exports the full public surface with-`pub use crate::search::tools::*` consumed from `tools/mod.rs`.+`pub use crate::search::tools::*`, consumed from `tools/mod.rs`.## Providers| File | Exported tools | `name()` | Transport || --- | --- | --- | --- || `brave.rs` | `BraveWebSearchTool`, `BraveNewsSearchTool`, `BraveImageSearchTool`, `BraveVideoSearchTool` | `web_search_tool`, `brave_news_search`, `brave_image_search`, `brave_video_search` | Direct to `api.search.brave.com`, `X-Subscription-Token` header |-| `exa.rs` | `ExaSearchTool`, `ExaFindSimilarTool`, `ExaGetContentsTool` | `exa_search` or `web_search_tool` (constructor-selected), `exa_find_similar`, `exa_get_contents` | BYOK, direct to `api.exa.ai`, `x-api-key` header: never proxied |-| `parallel.rs` (+ `parallel/`: `search.rs`, `extract.rs`, `chat.rs`, `research.rs`, `enrich.rs`, `dataset.rs`) | `ParallelSearchTool`, `ParallelExtractTool`, `ParallelChatTool`, `ParallelResearchTool`, `ParallelEnrichTool`, `ParallelDatasetTool` | `parallel_search`, `parallel_extract`, `parallel_chat`, `parallel_research`, `parallel_enrich`, `parallel_dataset` | Backend-proxied via `crate::integrations::IntegrationClient` (`/agent-integrations/parallel/*`) |+| `exa.rs` | `ExaSearchTool`, `ExaFindSimilarTool`, `ExaGetContentsTool` | `exa_search` or `web_search_tool` (constructor-selected), `exa_find_similar`, `exa_get_contents` | BYOK, direct to `api.exa.ai`, `x-api-key` header, never proxied |+| `parallel.rs` (plus `parallel/`: `search.rs`, `extract.rs`, `chat.rs`, `research.rs`, `enrich.rs`, `dataset.rs`) | `ParallelSearchTool`, `ParallelExtractTool`, `ParallelChatTool`, `ParallelResearchTool`, `ParallelEnrichTool`, `ParallelDatasetTool` | `parallel_search`, `parallel_extract`, `parallel_chat`, `parallel_research`, `parallel_enrich`, `parallel_dataset` | Backend-proxied via `crate::integrations::IntegrationClient` (`/agent-integrations/parallel/*`) || `querit.rs` | `QueritSearchTool` | `querit_search` or `web_search_tool` (constructor-selected) | Direct to `api.querit.ai`, `Authorization: Bearer` header || `searxng.rs` | `SearxngSearchTool`, plus `normalize_categories`, `SearxngSearchArgs`, `SearxngSearchResponse`, `MAX_RESULTS` (re-exported as `SEARXNG_MAX_RESULTS`) | `searxng_search` | Direct to a user-configured, self-hosted SearXNG instance (`GET /search?format=json`) || `seltz.rs` | `SeltzSearchTool` | `seltz_search` | Direct to `api.seltz.ai`, `x-api-key` header |-| `tavily.rs` (+ `tavily/`: `client.rs`, `search_tool.rs`, `extract_tool.rs`, `types.rs`) | `TavilySearchTool`, `TavilyExtractTool` | `tavily_search` or `web_search_tool` (constructor-selected), `tavily_extract` | BYOK, direct to `api.tavily.com`, `Authorization: Bearer` header: never proxied |-| `tinyfish.rs` | `TinyFishSearchTool`, `TinyFishFetchTool`, `TinyFishAgentRunTool` | `tinyfish_search`, `tinyfish_fetch`, `tinyfish_agent_run` | Backend-proxied via `IntegrationClient` (`/agent-integrations/tinyfish/*`); search/fetch are read-oriented, agent-run drives goal-based browser automation |-| `web_search.rs` | `WebSearchTool` (+ crate-internal `resolve_managed_provider`) | `web_search_tool` | Backend-proxied managed search (`POST /agent-integrations/parallel/search` via `IntegrationClient`); `resolve_managed_provider` labels the response with the provider the backend reports, falling back to `Exa`, for UI attribution. `with_direct_search(Option<SeltzSearchTool>)` can short-circuit the proxy, but only `web_search_tests.rs` uses it |+| `tavily.rs` (plus `tavily/`: `client.rs`, `search_tool.rs`, `extract_tool.rs`, `types.rs`) | `TavilySearchTool`, `TavilyExtractTool` | `tavily_search` or `web_search_tool` (constructor-selected), `tavily_extract` | BYOK, direct to `api.tavily.com`, `Authorization: Bearer` header, never proxied |+| `tinyfish.rs` | `TinyFishSearchTool`, `TinyFishFetchTool`, `TinyFishAgentRunTool` | `tinyfish_search`, `tinyfish_fetch`, `tinyfish_agent_run` | Backend-proxied via `IntegrationClient` (`/agent-integrations/tinyfish/*`); search and fetch are read-oriented, agent-run drives goal-based browser automation |+| `web_search.rs` | `WebSearchTool` (plus crate-internal `resolve_managed_provider`) | `web_search_tool` | Backend-proxied managed search (`POST /agent-integrations/parallel/search` via `IntegrationClient`); `resolve_managed_provider` labels the response with the provider the backend reports, falling back to `Exa`, for UI attribution. `with_direct_search(Option<SeltzSearchTool>)` can short-circuit the proxy, but only `web_search_tests.rs` uses it |-Several providers construct their primary tool with a `tool_name` field so the-same struct can register under either its own name (e.g. `exa_search`,-`querit_search`, `tavily_search`) or the canonical `web_search_tool` slot when-that engine is the active `search.engine`: see `exa.rs`, `querit.rs`, and-`tavily/search_tool.rs`.+Several providers construct their primary tool with a `tool_name` field so+the same struct can register under either its own name (`exa_search`,+`querit_search`, `tavily_search`) or the canonical `web_search_tool` slot+when that engine is the active `search.engine`. See `exa.rs`, `querit.rs`,+and `tavily/search_tool.rs`.## Registration-Most families are selected by `search::registry::build_search_tools` based on-`Config.search.effective_engine()`, via `search/engines/`-([README](../README.md)). `tinyfish.rs` tools are pushed separately by-`registry.rs` (`build_backend_search_tools`) on top of whichever engine is-active, provided the engine is not `disabled`, an `IntegrationClient` can be-built (user signed in), and `config.integrations.tinyfish.is_active()`.--`SearxngSearchTool` and `SeltzSearchTool` are not reachable through the engine-registry at all: they are constructed per call by the `tools.searxng_search`-(`handle_searxng_search`) and `tools.seltz_search` (`handle_seltz_search`)-RPC handlers, both in `crates/openhuman-core/src/tools/schemas/web_search.rs`.-Those handlers take the query and `max_results` from the RPC-params but read endpoint, key, timeout, and the `enabled` gate from the-top-level `config.searxng` / `config.seltz` sections, not from-`Config.search`. `SEARXNG_MAX_RESULTS` and `normalize_categories` are also-reused by `mcp/server/tools/` to keep the MCP SearXNG surface consistent with-the RPC handler.+Most families are selected by `search::registry::build_search_tools` based+on `Config.search.effective_engine()`, via `search/engines/`+([README](../engines/README.md)). `tinyfish.rs` tools are pushed separately+by `registry.rs` (`build_backend_search_tools`) on top of whichever engine+is active, provided the engine is not `disabled`, an `IntegrationClient` can+be built (user signed in), and `config.integrations.tinyfish.is_active()`.++`SearxngSearchTool` and `SeltzSearchTool` are not reachable through the+engine registry at all. They are constructed per call by the+`tools.searxng_search` (`handle_searxng_search`) and `tools.seltz_search`+(`handle_seltz_search`) RPC handlers, both in+`crates/openhuman-core/src/tools/schemas/web_search.rs`. Those handlers take+the query and `max_results` from the RPC params but read the endpoint, key,+timeout, and `enabled` gate from the top-level `config.searxng` /+`config.seltz` sections, not from `Config.search`. `SEARXNG_MAX_RESULTS` and+`normalize_categories` are also reused by `mcp/server/tools/` to keep the+MCP SearXNG surface consistent with the RPC handler.## TestsEach provider has a sibling `*_tests.rs` (`brave_tests.rs`, `exa_tests.rs`,-etc.) wired in via `#[cfg(test)] #[path = "<provider>_tests.rs"] mod tests;`.-No test hits the network: `web_search_tests.rs` starts an in-process axum-router (`start_mock_backend`) and points an `IntegrationClient` at it; the-other backend-proxied families build their client against an unreachable+and so on) wired in via+`#[cfg(test)] #[path = "<provider>_tests.rs"] mod tests;`. No test hits the+network: `web_search_tests.rs` starts an in-process axum router+(`start_mock_backend`) and points an `IntegrationClient` at it; the other+backend-proxied families build their client against an unreachable`http://test` base and only exercise schema and response parsing.diff --git a/gitbooks/developing/testing-strategy.md b/gitbooks/developing/testing-strategy.mdindex 4335e321da..d84bc7dff4 100644--- a/gitbooks/developing/testing-strategy.md+++ b/gitbooks/developing/testing-strategy.md@@ -231,8 +231,8 @@ The mechanism is worth understanding because it is invisible in the output: afeature flag can gate the *registration* of a tool, a test's expected side is astatic allowlist while its actual side is computed by **introspecting the builtbinary**, and so the flag silently moves the actual. Nothing is stubbed, nothing-is skipped, and the failure names a product concept —-*"agents that carry tools but whose prompt names none of them"* — with no+is skipped, and the failure names a product concept,+*"agents that carry tools but whose prompt names none of them,"* with nomention of a feature anywhere.*Falsified, from the two runs side by side:* on `0f1ecc9d2`, `openhuman --lib`@@ -256,13 +256,13 @@ Tracked as openhuman#6512; per-profile detail in openhuman#6486.*Reported for `openhuman --lib`:* `web_chat` aborts with`fatal runtime error: stack overflow` without it, which is why `ci-lite.yml`-exports it. Not reproduced here — treat as the reason the CI command above+exports it. Not reproduced here: treat that as the reason the CI command abovecarries it, and re-verify before relying on it elsewhere.Two crates, one variable, opposite answers. That is the argument against asingle blanket recipe: do not add a prerequisite by reflex. One that is notneeded teaches contributors the docs are unreliable, and it is precisely how the-misleading note above came to exist — someone's defensively-accumulated setup,+misleading note above came to exist: someone's defensively-accumulated setup,written down as necessity, never falsified.### 4. Only now suspect a defect — and make the silence speak