Skip to content

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

Merge remote-tracking branch 'origin/main' into epic-8000-final-rollup

Steven Enamakel1cb14dd7fc56
diff --cc crates/openhuman-core/src/agent/harness/README.md
index b642eed663,4843cccf0f..01782b51c6
--- a/crates/openhuman-core/src/agent/harness/README.md
+++ b/crates/openhuman-core/src/agent/harness/README.md
@@@ -78,11 -77,12 +77,11 @@@ turn lifecycle are in `../session_host/
(`<tool_call>` tags, fenced blocks, bare JSON, `<invoke>` XML, GLM grammar,
p-format). This crate is a test-only dependency of `harness/`; the parsers
are not called from production code here.
- - `crate::agent::registry::agents`: built-in agent archetype TOML/prompt
- bundles loaded by `tinyagents_definition` (user TOML) and `builtin_definitions`.
+ - `crate::agent_registry::agents`: built-in agent archetype TOML/prompt
+ bundles; custom bundles are loaded by `tinyagents_definition`.
- `crate::security::SecurityPolicy`: workspace containment policy plumbed
into `artifact_offload::new_artifact_offload`.
-- `tinymemory-api`: provenance classification and untrusted-context wrapping,
- configured with connector prefixes from `memory::provenance`.
+- `tinymemory-api`: provenance classification and untrusted-context wrapping.
- `crate::memory`: text
sanitization (`artifact_offload::SanitizingRedactor` wraps `memory::safety::sanitize_text` for both artifact stores).
- `crate::config::AgentConfig`, `crate::skills::Workflow`,
diff --cc crates/openhuman-core/src/agent/harness/graph.rs
index e1d41a4204,29ab4c31b3..ed014dc4a1
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@@ -56,10 -56,10 +56,10 @@@ pub(crate) async fn run_channel_turn_vi
multimodal: MultimodalConfig,
multimodal_files: MultimodalFileConfig,
on_progress: Option<Sender<AgentProgress>>,
- origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ origin: Option<crate::security::turn_origin::AgentTurnOrigin>,
sandbox_mode: tinyagents_definition::SandboxMode,
approval: crate::security::approval::ApprovalTurnContext,
- memory_identity: crate::memory::scope::MemoryIdentity,
+ memory_identity: tinymemory_tools::layout::identity::Identity,
) -> Result<crate::agent::tinyagents::TinyagentsTurnOutcome> {
let extra_arc = Arc::new(extra_tools);
// A channel/CLI turn is entered without a run context: the model source
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
index 6e8599c950,44d3d50e2f..22ebe375ee
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@@ -9,14 -10,13 +10,13 @@@ use async_trait::async_trait
use tinyagents_harness::context::RunContext;
use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::{
- call_effect, dispatch_target, is_repeat_call_exempt, repeat_guard_marker, CallEffect,
- Middleware, StopLatch, ToolFactsLookup, ToolInvocationIdentity,
- };
- use tinyagents_harness::no_progress::{
- classified_step, clear_recovered, ClassifiedFailureTracker, ClassifiedStep, FailurePolicy,
- NoProgress, NoProgressTracker, RecoverableFailureLadder, ToolAttempt,
- call_effect, dispatch_target, is_repeat_call_exempt, repeat_guard_marker, FailureScope,
- FailureScopeMiddleware, FailureScopePolicy, FailureStopKind, Middleware, ToolFactsLookup,
- ToolInvocationIdentity,
++ FailureScope, FailureScopeMiddleware, FailureScopePolicy, FailureStopKind, Middleware,
++ ToolFactsLookup, ToolInvocationIdentity, call_effect, dispatch_target, is_repeat_call_exempt,
++ repeat_guard_marker,
};
+ use tinyagents_harness::no_progress::FailurePolicy;
use tinyagents_harness::steering::SteeringHandle;
+ use tinyagents_hooks::stop::StopLatch;
use tinyinference_llm::tool::ToolCall as TaToolCall;
use tinytools::ToolResult as TaToolResult;
@@@ -26,9 -27,14 +27,14 @@@ use crate::inference::failure_copy::
recoverable_identical_halt_summary, recoverable_no_progress_halt_summary,
terminal_inference_failure_kind, terminal_inference_halt_summary,
};
- use tinyagents_harness::middleware::{EphemeralInstructionMiddleware, EphemeralInstructionQueue};
+ use tinyagents_harness::middleware::EphemeralInstructionMiddleware;
use tinyinference_llm::failure::is_recoverable_failure_text as is_recoverable_tool_failure;
+ #[cfg(test)]
+ use tinyagents_harness::no_progress::{
- classified_step, ClassifiedFailureTracker, ClassifiedStep, RecoverableFailureLadder,
++ ClassifiedFailureTracker, ClassifiedStep, RecoverableFailureLadder, classified_step,
+ };
+
/// `after_tool`: stop (or nudge) the run when tool calls keep failing with no
/// progress (issue #4249). The legacy tool loop's progress guard surfaced a
/// root-cause halt summary — a security/approval denial re-issued unchanged, an
diff --cc crates/openhuman-core/src/backend/transport/transport_tests.rs
index 13ba5d3baa,0000000000..dba89c8a24
mode 100644,000000..100644
--- a/crates/openhuman-core/src/backend/transport/transport_tests.rs
+++ b/crates/openhuman-core/src/backend/transport/transport_tests.rs
@@@ -1,326 -1,0 +1,328 @@@
+use super::*;
+use crate::security::credentials::session_support::BackendCredential;
+use serde_json::json;
+use std::sync::Arc;
+use wiremock::matchers::{header, method, path};
+use wiremock::{Mock, MockServer, ResponseTemplate};
+
+struct NamedTransport(&'static str);
+
+#[test]
+fn transports_without_memory_support_return_no_memory_bearer_adapter() {
+ let transport = NamedTransport("plain");
- assert!(transport
- .memory_bearer_source(Arc::new(crate::config::Config::default()))
- .is_none());
++ assert!(
++ transport
++ .memory_bearer_source(Arc::new(crate::config::Config::default()))
++ .is_none()
++ );
+}
+
+#[async_trait]
+impl BackendTransport for NamedTransport {
+ async fn send_json(&self, _req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
+ Ok(json!({"from": self.0}))
+ }
+
+ async fn send_multipart(
+ &self,
+ _req: BackendRequest<'_>,
+ _form: reqwest::multipart::Form,
+ ) -> Result<Value, BackendTransportError> {
+ Ok(Value::Null)
+ }
+
+ fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
+ reqwest::Client::new()
+ }
+
+ // URL and attribution answers delegate to the plain transport: this
+ // double is installed process-wide while other tests resolve base URLs.
+ fn base_url(&self, configured: Option<&str>, purpose: BaseUrlPurpose) -> String {
+ plain::PlainHttpTransport::new().base_url(configured, purpose)
+ }
+
+ fn product_identity(&self) -> String {
+ plain::TEST_PRODUCT_IDENTITY.to_string()
+ }
+
+ fn attribution_headers(&self) -> reqwest::header::HeaderMap {
+ plain::PlainHttpTransport::new().attribution_headers()
+ }
+
+ fn name(&self) -> &'static str {
+ self.0
+ }
+}
+
+/// The global slot is process state; serialise the tests that touch it.
+fn global_lock() -> &'static tokio::sync::Mutex<()> {
+ static LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
+ LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
+}
+
+#[test]
+fn unwrap_envelope_returns_data_and_strips_success_flag() {
+ assert_eq!(
+ unwrap_envelope(json!({"success": true, "data": {"a": 1}})).unwrap(),
+ json!({"a": 1})
+ );
+ assert_eq!(
+ unwrap_envelope(json!({"success": true, "jwt": "t"})).unwrap(),
+ json!({"jwt": "t"})
+ );
+ assert_eq!(
+ unwrap_envelope(json!({"plain": true})).unwrap(),
+ json!({"plain": true})
+ );
+ assert_eq!(unwrap_envelope(json!([1, 2])).unwrap(), json!([1, 2]));
+}
+
+#[test]
+fn unwrap_envelope_turns_failure_into_typed_error() {
+ let err = unwrap_envelope(json!({
+ "success": false,
+ "error": "Insufficient balance",
+ "errorCode": "E_BAL",
+ "details": {"needed": 3}
+ }))
+ .unwrap_err();
+ match err {
+ BackendTransportError::Envelope {
+ error,
+ error_code,
+ details,
+ } => {
+ assert_eq!(error, "Insufficient balance");
+ assert_eq!(error_code.as_deref(), Some("E_BAL"));
+ assert_eq!(details, json!({"needed": 3}));
+ }
+ other => panic!("expected Envelope, got {other:?}"),
+ }
+ // `message` is accepted as the failure text, and a bare `success:false`
+ // still fails with a generic reason rather than being handed back as data.
+ assert!(matches!(
+ unwrap_envelope(json!({"success": false, "message": "nope"})),
+ Err(BackendTransportError::Envelope { error, .. }) if error == "nope"
+ ));
+ assert!(matches!(
+ unwrap_envelope(json!({"success": false})),
+ Err(BackendTransportError::Envelope { error, .. }) if error == "request unsuccessful"
+ ));
+}
+
+#[test]
+fn credential_headers_put_session_on_bearer_and_api_key_on_x_api_key() {
+ let session =
+ credential_headers(&BackendCredential::Session(" jwt.token.sig \n".into())).unwrap();
+ assert_eq!(
+ session.get(reqwest::header::AUTHORIZATION).unwrap(),
+ "Bearer jwt.token.sig"
+ );
+ assert!(session.get(API_KEY_HEADER).is_none());
+
+ let key = credential_headers(&BackendCredential::ApiKey("th_key".into())).unwrap();
+ assert_eq!(key.get(API_KEY_HEADER).unwrap(), "th_key");
+ assert!(key.get(reqwest::header::AUTHORIZATION).is_none());
+}
+
+#[test]
+fn compose_url_joins_base_path_and_omits_none_query_values() {
+ let url = compose_url(
+ "https://api.example.test/",
+ "teams/me/usage",
+ &[("a", Some("1".into())), ("b", None)],
+ )
+ .unwrap();
+ assert_eq!(url.as_str(), "https://api.example.test/teams/me/usage?a=1");
+ let url = compose_url("https://api.example.test", "/x", &[]).unwrap();
+ assert_eq!(url.as_str(), "https://api.example.test/x");
+ assert!(matches!(
+ compose_url("not a url", "/x", &[]),
+ Err(BackendTransportError::Url(_))
+ ));
+}
+
+#[test]
+fn parse_body_text_handles_empty_json_and_plain_text() {
+ assert_eq!(parse_body_text(String::new()), Value::Null);
+ assert_eq!(parse_body_text("{\"a\":1}".into()), json!({"a": 1}));
+ assert_eq!(parse_body_text("nope".into()), json!("nope"));
+}
+
+#[test]
+fn global_install_replaces_and_clears() {
+ let _guard = global_lock().blocking_lock();
+ clear_backend_transport();
+ assert!(installed_backend_transport().is_none());
+
+ install_backend_transport(Arc::new(NamedTransport("first")));
+ assert_eq!(installed_backend_transport().unwrap().name(), "first");
+
+ install_backend_transport(Arc::new(NamedTransport("second")));
+ assert_eq!(installed_backend_transport().unwrap().name(), "second");
+
+ clear_backend_transport();
+ assert!(installed_backend_transport().is_none());
+}
+
+#[test]
+fn resolve_prefers_global_over_test_fallback() {
+ let _guard = global_lock().blocking_lock();
+ clear_backend_transport();
+ // Under cfg(test) the plain transport is the floor, never `Unavailable`.
+ assert_eq!(resolve_backend_transport().unwrap().name(), "plain-test");
+
+ install_backend_transport(Arc::new(NamedTransport("host")));
+ assert_eq!(resolve_backend_transport().unwrap().name(), "host");
+ clear_backend_transport();
+}
+
+#[test]
+fn error_status_accessor_only_reports_status_variant() {
+ assert_eq!(
+ BackendTransportError::Status {
+ status: 404,
+ body: Value::Null
+ }
+ .status(),
+ Some(404)
+ );
+ assert_eq!(BackendTransportError::Unavailable.status(), None);
+}
+
+#[tokio::test]
+async fn plain_transport_sends_attribution_and_credential_headers() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/teams/me/usage"))
+ .and(header("authorization", "Bearer jwt.a.b"))
+ .and(header(
+ plain::TEST_PRODUCT_HEADER,
+ plain::TEST_PRODUCT_IDENTITY,
+ ))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "success": true,
+ "data": {"remainingUsd": 4.5}
+ })))
+ .mount(&server)
+ .await;
+
+ let transport = plain::PlainHttpTransport::new();
+ let credential = BackendCredential::Session("jwt.a.b".into());
+ let value = transport
+ .send_json(BackendRequest {
+ profile: TransportProfile::Api,
+ base_url: &server.uri(),
+ method: reqwest::Method::GET,
+ path: "/teams/me/usage",
+ query: &[],
+ body: None,
+ credential: Some(&credential),
+ unwrap_envelope: true,
+ })
+ .await
+ .unwrap();
+ assert_eq!(value, json!({"remainingUsd": 4.5}));
+}
+
+#[tokio::test]
+async fn plain_transport_maps_non_2xx_to_status_and_keeps_raw_when_not_unwrapping() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/agent-integrations/x"))
+ .and(header(API_KEY_HEADER, "k1"))
+ .respond_with(ResponseTemplate::new(402).set_body_string("Insufficient balance"))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/raw"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"success": true, "data": 1})))
+ .mount(&server)
+ .await;
+
+ let transport = plain::PlainHttpTransport::new();
+ let credential = BackendCredential::ApiKey("k1".into());
+ let body = json!({"q": 1});
+ let err = transport
+ .send_json(BackendRequest {
+ profile: TransportProfile::Integrations,
+ base_url: &server.uri(),
+ method: reqwest::Method::POST,
+ path: "agent-integrations/x",
+ query: &[],
+ body: Some(&body),
+ credential: Some(&credential),
+ unwrap_envelope: false,
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ BackendTransportError::Status { status: 402, ref body } if body == "Insufficient balance"
+ ));
+
+ let base = server.uri();
+ let mut req = BackendRequest::new(TransportProfile::Api, &base, reqwest::Method::GET, "/raw");
+ req.unwrap_envelope = false;
+ assert_eq!(
+ transport.send_json(req).await.unwrap(),
+ json!({"success": true, "data": 1})
+ );
+}
+
+#[tokio::test]
+async fn backend_client_reports_unavailable_when_transport_returns_unavailable() {
+ struct Absent;
+ #[async_trait]
+ impl BackendTransport for Absent {
+ async fn send_json(
+ &self,
+ _req: BackendRequest<'_>,
+ ) -> Result<Value, BackendTransportError> {
+ Err(BackendTransportError::Unavailable)
+ }
+ async fn send_multipart(
+ &self,
+ _req: BackendRequest<'_>,
+ _form: reqwest::multipart::Form,
+ ) -> Result<Value, BackendTransportError> {
+ Err(BackendTransportError::Unavailable)
+ }
+ fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
+ reqwest::Client::new()
+ }
+ fn base_url(&self, configured: Option<&str>, purpose: BaseUrlPurpose) -> String {
+ plain::PlainHttpTransport::new().base_url(configured, purpose)
+ }
+ fn product_identity(&self) -> String {
+ plain::TEST_PRODUCT_IDENTITY.to_string()
+ }
+ fn attribution_headers(&self) -> reqwest::header::HeaderMap {
+ plain::PlainHttpTransport::new().attribution_headers()
+ }
+ fn name(&self) -> &'static str {
+ "absent"
+ }
+ }
+
+ let _guard = global_lock().lock().await;
+ install_backend_transport(Arc::new(Absent));
+ let client = crate::backend::BackendClient::new("https://api.example.test").unwrap();
+ let err = client
+ .authed_json("jwt", reqwest::Method::GET, "/payments/summary", None)
+ .await
+ .unwrap_err();
+ clear_backend_transport();
+
+ assert!(matches!(
+ err.downcast_ref::<crate::backend::BackendApiError>(),
+ Some(crate::backend::BackendApiError::BackendUnavailable { method, path })
+ if method == "GET" && path == "/payments/summary"
+ ));
+ let flat = crate::backend::flatten_authed_error(err);
+ assert!(flat.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX));
+ assert_eq!(
+ crate::core::observability::expected_error_kind(&flat),
+ Some(crate::core::observability::ExpectedErrorKind::BackendUnavailable)
+ );
+}
diff --cc crates/openhuman-core/src/flows/memory_tools.rs
index 8390df87d3,c2073b06a4..b3d584e02c
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@@ -27,15 -27,17 +27,15 @@@ use std::sync::Arc
use async_trait::async_trait;
use serde_json::json;
-use tinymemory_api::{
- Citation, ForgetTarget, LearningKind, MemoryMeta, MetaFilter, SourceKind, SourceRef,
-};
+use tinymemory_api::{Citation, LearningKind, MemoryMeta, MetaFilter, SourceKind, SourceRef};
use tinytools::{PermissionLevel, Tool, ToolResult};
- use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
-use crate::memory::types::{LearnParams, RecallParams};
-use crate::memory::{MemoryError, MemoryResult};
+use crate::memory::types::{ForgetParams, ItemsListParams, LearnParams, RecallParams, MAX_LIMIT};
use crate::security::policy::ToolOperation;
+ use crate::security::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::security::SecurityPolicy;
+use tinymemory_api::{Error, Result};
/// Prefix of a flow's own tag (see [`flow_tag`]).
pub const FLOW_TAG_PREFIX: &str = "flow:";
diff --cc crates/openhuman-core/src/memory/README.md
index 3478613a34,2f5ad1069b..429c5664e7
--- a/crates/openhuman-core/src/memory/README.md
+++ b/crates/openhuman-core/src/memory/README.md
@@@ -18,27 -18,27 +18,24 @@@ Chat thread persistence is not memory.
Every memory operation starts with `engine::resolve(config)`, which turns
the `[memory]` config into either `Binding::On(BoundEngine)` or
--`Binding::Off` with a reason. Two engines are supported:
++`Binding::Off` with a reason. Built-in and host-provided engines are bound
++through TinyMemory's native binder:
-| Engine | Endpoint | Credential | Off when |
-| --- | --- | --- | --- |
+| Engine | Endpoint | Credential | Off when |
+| ------------ | ----------------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------- |
- | `tinyhumans` | `[memory.engines.tinyhumans] endpoint`, else `backend::base_url` | the host's backend credential, resolved per request | signed out, or no default backend transport installed |
+ | `tinyhumans` | registered by `openhuman-tinyhumans` through `engine_registry` (`[memory.engines.tinyhumans] endpoint`, else its control-plane origin) | the host's backend credential, resolved per request | not registered, or signed out |
-| `cortexdb` | `[memory.engines.cortexdb] endpoint`, else CortexDB's managed API | the API key stored in the keyring as `memory-cortexdb` | no key stored |
-
-The core never keeps a TinyHumans credential of its own. The bearer is
-fetched from the host's credential seam (`resolve_backend_credential`) on
-every request, so a refreshed session takes effect at once and signing out
-turns memory off. The hosted engine lives in `openhuman-tinyhumans`
-(`memory/engine.rs`): it hands TinyMemory's CortexDB client an
-`EngineSettings` with the endpoint, the attribution headers and an
-`EngineCredential::Dynamic(HostBearer)` through the core's generic
-`engine::build_cached`, and TinyMemory's own HTTP client calls the backend's
-`/memory/*` routes. With nothing registered, `tinyhumans` answers off
-("no TinyHumans backend is available"). The
+| `cortexdb` | `[memory.engines.cortexdb] endpoint`, else CortexDB's managed API | the API key stored in the keyring as `memory-cortexdb` | no key stored |
+
- The core never keeps a TinyHumans credential of its own. The bearer is
- resolved on every request, so a refreshed session takes effect at once and
- signing out turns memory off. A host `BackendTransport` may provide a
- `memory_bearer_source` adapter; standalone core builds use the same safe
- `resolve_backend_credential` resolver directly, preserving a configured
- memory endpoint without an installed SDK transport. The hosted engine does
- not send memory HTTP through `BackendTransport`: [`engine.rs`](./engine.rs)
- hands TinyMemory's CortexDB client the endpoint, attribution headers and an
- `EngineCredential::Dynamic` backed by the native `CallbackBearerSource`, and
- TinyMemory's HTTP client calls the backend's `/memory/*` routes. The
++The core never keeps a TinyHumans credential or owns that engine's
++configuration. The registered host builder resolves the bearer on every
++request, so a refreshed session takes effect at once and signing out turns
++memory off. The hosted engine lives in `openhuman-tinyhumans`
++(`memory/engine.rs`): it supplies the endpoint, attribution headers and a
++dynamic bearer source to the native binder. The
`cortexdb` engine calls CortexDB directly with the stored key
-(`EngineCredential::Static`). Built engines are cached per config fingerprint (engine
-id, endpoint, credential identity, layout), so a config change, a sign-in or
-a new key rebuilds the engine on the next call without any event plumbing.
+(`EngineCredential::Static`). TinyMemory's native binder caches by settings,
+credential identity and layout, so changes rebuild the engine without event
+plumbing.
An embedding host can install its own engine with `install_host_engine`.
It wins over the configured one for every config in the process, so a host
diff --cc crates/openhuman-core/src/memory/backfill.rs
index b5d47757a1,58f6acd856..b312dec2ff
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@@ -1,32 -1,89 +1,32 @@@
//! Storing past chats: conversations from before turns were logged.
//!
-//! The lifecycle logs each turn as it happens (`lifecycle::hooks`). This walks
-//! the thread store instead and stores every earlier message of every thread
-//! the same way — one conversation item per message, user message `2n` and
-//! its reply `2n + 1`, at the main agent's node (`agent:<id>` under the
-//! layout root) — plus a [`BACKFILL_TAG`] so they can be told apart.
-//!
-//! The turn builder is `tinymemory_tools::backfill`; this file keeps the thread-store
-//! reading, the state file, consent and the run.
-//!
-//! - **Turns.** A thread's messages become turns the way the chat shows them:
-//! each user message opens a turn and the replies after it, up to the next
-//! user message, are its answer. Replies before any user message form a turn
-//! with no user side.
-//! - **No overlap with live logging.** A thread's turns from the first one the
-//! lifecycle logged on are already in memory; the backfill stops short of
-//! them (it asks the engine where logging began).
-//! - **Resumable and repeatable.** How far each thread has been stored is kept
-//! in `<workspace>/memory/conversations_backfill.json`, so an interrupted run
-//! resumes and a later run sends only what is new. A re-sent item is a
-//! replay (its id is a content digest), never a duplicate.
-//! - **Accepted, then visible.** Every batch but the last goes in with
-//! accepted writes: the engine returns once it holds them durably, and
-//! indexes them after. The last waits until it is visible, and the scope's
-//! log is ordered, so a `done` run is searchable. An engine without
-//! accepted writes stores every batch as before.
-//! - **Consent.** It uploads chat history to the selected engine, so
-//! [`start`] refuses without `consent`.
-
-use crate::core::runtime::DispatchCtx;
-use std::collections::{BTreeMap, HashSet};
-use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
+//! The TinyMemory backfill driver owns planning, progress, batching and
+//! idempotent writes. This host adapter supplies the conversation thread
- //! source, the existing state-file path, consent, engine binding and task
++//! source, the state-KV checkpoint, consent, engine binding and task
+//! lifetime.
- use std::path::{Path, PathBuf};
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
++use std::path::PathBuf;
+use std::sync::Arc;
use crate::config::Config;
-use crate::memory::engine::{self, BoundEngine};
-use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::ops::store_many_on_with;
-use crate::memory::scope::{MemoryIdentity, ResolvedIdentity};
-use crate::memory::types::ImportPhase;
+use crate::core::runtime::DispatchCtx;
+use crate::memory::engine;
+use crate::memory::run_slots::{self, BACKFILL, IMPORT, MIGRATION};
use crate::threads::store::blocking as threads;
-
-use tinymemory_tools::backfill::{first_live_turn, group_items, turn_groups, ThreadMessage};
-pub use tinymemory_tools::backfill::{pending_range, turns_of, PastTurn, BACKFILL_TAG, MAIN_AGENT};
-
-/// Backfills running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// Progress of the last (or current) backfill.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct BackfillState {
- /// Idle, running, done, or stopped on an error.
- pub phase: ImportPhase,
- /// Threads with turns to store when the run started.
- pub threads_total: u64,
- /// Of those, threads finished.
- pub threads_done: u64,
- /// Turns stored by the run.
- pub turns_stored: u64,
- /// Conversation items stored by the run.
- pub items_stored: u64,
- /// Why it stopped, when it failed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// When the last run finished.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub finished_at: Option<DateTime<Utc>>,
-}
-
-/// `memory_conversations_backfill_status` / `_start` result.
-#[derive(Debug, Clone, Serialize)]
-pub struct BackfillView {
- /// The run's progress.
- pub state: BackfillState,
- /// Threads that still have earlier turns to store.
- pub pending_threads: u64,
- /// Turns still to store across them.
- pub pending_turns: u64,
-}
+use async_trait::async_trait;
+use tinymemory_api::{Error, Result};
+use tinymemory_tools::backfill::{
+ BackfillFile, Backfiller, CounterStore, ThreadMessage, ThreadSource,
+};
+use tinymemory_tools::layout::identity::Identity;
+
+pub use tinymemory_tools::backfill::{
- pending_range, turns_of, BackfillPhase, BackfillState, BackfillView, PastTurn, BACKFILL_TAG,
- MAIN_AGENT,
++ BACKFILL_TAG, BackfillPhase, BackfillState, BackfillView, MAIN_AGENT, PastTurn, pending_range,
++ turns_of,
+};
/// `memory_conversations_backfill_start` params.
-#[derive(Debug, Clone, Default, Deserialize)]
+#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct BackfillStartParams {
/// The caller agrees to upload past chats to the engine.
#[serde(default)]
@@@ -66,52 -118,67 +66,45 @@@ impl ThreadSource for HostThreadSource
}
}
-/// One thread's plan: its turns and the range still to store.
-struct ThreadPlan {
- thread_id: String,
- turns: Vec<PastTurn>,
- range: std::ops::Range<usize>,
+struct FileCounterStore {
+ workspace_dir: PathBuf,
}
- impl FileCounterStore {
- fn path(&self) -> PathBuf {
- self.workspace_dir
- .join("memory")
- .join("conversations_backfill.json")
- }
- }
-
-async fn plan(
- ctx: &DispatchCtx,
- workspace_dir: &Path,
- bound: Option<&BoundEngine>,
- stored: &BTreeMap<String, u32>,
-) -> MemoryResult<Vec<ThreadPlan>> {
- let listed = threads::list_threads(ctx.clone(), workspace_dir.to_path_buf())
- .await
- .map_err(|error| MemoryError::Engine(format!("reading chat threads failed: {error}")))?;
- let mut plans = Vec::new();
- for thread in listed {
- let messages = match threads::get_messages(
- ctx.clone(),
- workspace_dir.to_path_buf(),
- thread.id.clone(),
- )
- .await
- {
- Ok(messages) => messages,
- Err(error) => {
- tracing::warn!(error = %error, "[memory:backfill] a thread was unreadable; skipped");
- continue;
- }
- };
- let messages: Vec<ThreadMessage> = messages
- .into_iter()
- .map(|m| ThreadMessage::new(m.sender, m.content, m.created_at))
- .collect();
- let turns = turns_of(&messages);
- let first_live = match bound {
- Some(bound) => first_live_turn(bound.engine.as_ref(), &thread.id).await,
- None => None,
- };
- let range = pending_range(
- turns.len(),
- first_live,
- stored.get(&thread.id).copied().unwrap_or(0),
- );
- if !range.is_empty() {
- plans.push(ThreadPlan {
- thread_id: thread.id,
- turns,
- range,
- });
- }
+impl CounterStore for FileCounterStore {
+ fn load(&self) -> BackfillFile {
- std::fs::read_to_string(self.path())
- .ok()
- .and_then(|text| serde_json::from_str(&text).ok())
++ super::state_store::load(&self.workspace_dir, "conversations_backfill")
++ .unwrap_or_else(|error| {
++ tracing::warn!(%error, "[memory:backfill] reading state failed");
++ None
++ })
+ .unwrap_or_default()
+ }
+
+ fn save(&self, file: &BackfillFile) -> std::result::Result<(), String> {
- let bytes = serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?;
- crate::security::secret_storage::file_store::write_atomic(&self.path(), &bytes)
++ super::state_store::save(&self.workspace_dir, "conversations_backfill", file)
+ .map_err(|error| error.to_string())
}
- Ok(plans)
}
-fn is_running(workspace_dir: &Path) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(workspace_dir)
+fn driver(
+ ctx: DispatchCtx,
+ config: &Config,
+ engine: Arc<dyn tinymemory_api::MemoryEngine>,
+) -> Backfiller {
+ let identity =
+ Identity::agent(MAIN_AGENT).resolve(&crate::memory::scope::identity_pins(config));
+ Backfiller::new(
+ engine,
+ identity.layout,
+ identity.agent_id,
+ Arc::new(HostThreadSource {
+ ctx,
+ workspace_dir: config.workspace_dir.clone(),
+ }),
+ Arc::new(FileCounterStore {
+ workspace_dir: config.workspace_dir.clone(),
+ }),
+ )
}
/// `memory_conversations_backfill_status`.
diff --cc crates/openhuman-core/src/memory/backfill_tests.rs
index 70d69a89ae,3f35e825b6..586134dee7
--- a/crates/openhuman-core/src/memory/backfill_tests.rs
+++ b/crates/openhuman-core/src/memory/backfill_tests.rs
@@@ -300,71 -296,3 +300,77 @@@ async fn batches_are_stored_accepted_an
"an engine without accepted writes still stores everything"
);
}
+
+#[tokio::test]
+async fn a_peer_driver_blocks_backfill_without_claiming_its_slot_or_state() {
+ #[derive(Clone, Copy)]
+ enum Peer {
+ Import,
+ Migration,
+ }
+
+ for (index, peer) in [Peer::Import, Peer::Migration].into_iter().enumerate() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ bind_reference(&config);
+ seed_thread(
+ &config.workspace_dir,
+ &format!("thread-{index}"),
+ &[("user", "past question"), ("agent", "past answer")],
+ )
+ .await;
+ let workspace = config.workspace_dir.clone();
+ let peer_guard = match peer {
+ Peer::Import => crate::memory::run_slots::reserve(
+ &crate::memory::run_slots::IMPORT,
+ &workspace,
+ &[
+ &crate::memory::run_slots::BACKFILL,
+ &crate::memory::run_slots::MIGRATION,
+ ],
+ ),
+ Peer::Migration => crate::memory::run_slots::reserve(
+ &crate::memory::run_slots::MIGRATION,
+ &workspace,
+ &[
+ &crate::memory::run_slots::IMPORT,
+ &crate::memory::run_slots::BACKFILL,
+ ],
+ ),
+ }
+ .expect("peer owns its driver-specific slot");
- let state_path = workspace.join("memory/conversations_backfill.json");
-
+ let blocked = start(
+ &DispatchCtx::ambient(),
+ &config,
+ BackfillStartParams { consent: true },
+ )
+ .await
+ .unwrap();
+ assert_eq!(blocked.state.phase, BackfillPhase::Idle);
+ assert_eq!((blocked.pending_threads, blocked.pending_turns), (1, 1));
+ assert!(!is_running(&workspace));
- assert!(!state_path.exists());
++ assert!(
++ crate::memory::state_store::load::<BackfillFile>(&workspace, "conversations_backfill")
++ .unwrap()
++ .is_none()
++ );
+
+ drop(peer_guard);
+ let started = start(
+ &DispatchCtx::ambient(),
+ &config,
+ BackfillStartParams { consent: true },
+ )
+ .await
+ .unwrap();
+ assert_eq!(started.state.phase, BackfillPhase::Running);
+ let done = wait_done(&config).await;
+ assert_eq!(done.state.phase, BackfillPhase::Done, "{:?}", done.state);
+ assert_eq!(done.state.items_stored, 2);
- assert!(state_path.is_file());
++ assert!(
++ crate::memory::state_store::load::<BackfillFile>(&workspace, "conversations_backfill")
++ .unwrap()
++ .is_some()
++ );
+ }
+}
diff --cc crates/openhuman-core/src/memory/brain.rs
index caee994556,2a47cc0451..d6ba64d3fb
--- a/crates/openhuman-core/src/memory/brain.rs
+++ b/crates/openhuman-core/src/memory/brain.rs
@@@ -11,18 -11,21 +11,18 @@@
//! the identity in scope (the default root outside an agent).
use serde::{Deserialize, Serialize};
-use tinymemory_api::{ExploreRequest, Facet, Hit, Namespace, StoreItem, WriteOptions};
+use tinymemory_api::{Error, Hit, Namespace, StoreItem, WriteOptions};
+use tinymemory_integrations::brain::MAX_INGEST_BYTES;
use tinymemory_integrations::documents::RawDocument;
use tinymemory_tools::layout::placement::{brain_node_with, files_source};
-use tinymemory_tools::{Brain, BrainSource, MemoryLayout};
+use tinymemory_tools::{Brain, BrainSource, BrainSourcesView, MemoryLayout};
--use crate::config::schema::MemorySourceKind;
use crate::config::Config;
++use crate::config::schema::MemorySourceKind;
use super::engine;
-use super::error::{MemoryError, MemoryResult};
use super::lifecycle::jobs;
-use super::scope::MemoryIdentity;
-
-/// Largest file `memory_brain_ingest` reads, in bytes.
-pub const MAX_INGEST_BYTES: u64 = 25 * 1024 * 1024;
+use tinymemory_api::Result;
/// The brain source a synced item belongs to: the connector it came from,
/// so removing it erases one source. GitHub to `github`, links and feeds to
diff --cc crates/openhuman-core/src/memory/brain_tests.rs
index a6571a7683,ea7391bfa3..d65760fecb
--- a/crates/openhuman-core/src/memory/brain_tests.rs
+++ b/crates/openhuman-core/src/memory/brain_tests.rs
@@@ -198,73 -188,21 +198,75 @@@ async fn ingest_refuses_bad_input()
},
] {
assert!(matches!(
- ingest(&config, &MemoryIdentity::root(), params).await,
- Err(MemoryError::InvalidRequest(_))
+ ingest(
+ &config,
+ &tinymemory_tools::layout::identity::Identity::root(),
+ params
+ )
+ .await,
+ Err(Error::InvalidRequest(_))
));
}
-- assert!(search(
- &config,
- &tinymemory_tools::layout::identity::Identity::root(),
- BrainSearchParams {
- query: " ".into(),
- source: None,
- limit: None
- }
- )
- .await
- .is_err());
++ assert!(
++ search(
++ &config,
++ &tinymemory_tools::layout::identity::Identity::root(),
++ BrainSearchParams {
++ query: " ".into(),
++ source: None,
++ limit: None
++ }
++ )
++ .await
++ .is_err()
++ );
+}
+
+#[tokio::test]
+async fn ingest_keeps_the_legacy_blank_source_error() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ bind_reference(&config);
+ let error = ingest(
&config,
- &MemoryIdentity::root(),
- BrainSearchParams {
- query: " ".into(),
- source: None,
- limit: None
- }
+ &tinymemory_tools::layout::identity::Identity::root(),
+ BrainIngestParams {
+ path: None,
+ text: Some("body".into()),
+ source: Some(" ".into()),
+ title: None,
+ },
)
.await
- .is_err());
+ .unwrap_err();
+
+ assert_eq!(
+ error.to_string(),
+ "invalid request: invalid request: a brain source id must not be blank"
+ );
+}
+
+#[tokio::test]
+async fn ingest_keeps_the_legacy_oversized_file_error() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ bind_reference(&config);
+ let path = tmp.path().join("oversized.bin");
+ let size = MAX_INGEST_BYTES + 1;
+ std::fs::File::create(&path).unwrap().set_len(size).unwrap();
+
+ let error = ingest(
+ &config,
+ &tinymemory_tools::layout::identity::Identity::root(),
+ path_params(path.display().to_string()),
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.to_string(),
+ format!("invalid request: the file is {size} bytes; the limit is {MAX_INGEST_BYTES}")
+ );
}
#[tokio::test]
@@@ -294,8 -232,8 +296,8 @@@ async fn a_file_is_converted_and_filed_
#[tokio::test]
async fn an_ingest_queues_a_belief_build_only_for_an_engine_that_waits_for_one() {
use std::sync::Arc;
-- use tinymemory_api::conformance::ReferenceEngine;
use tinymemory_api::Consolidation;
++ use tinymemory_api::conformance::ReferenceEngine;
for (consolidation, queued) in [(Consolidation::OnDemand, 1), (Consolidation::Automatic, 0)] {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/memory/bus_tests.rs
index b066b757cc,b066b757cc..e44c385b3b
--- a/crates/openhuman-core/src/memory/bus_tests.rs
+++ b/crates/openhuman-core/src/memory/bus_tests.rs
@@@ -61,7 -61,7 +61,7 @@@ fn the_deletions_subscriber_listens_on_
#[tokio::test]
async fn a_sign_in_drains_the_deletions_queued_while_signed_out() {
-- use crate::memory::deletion::{enqueue, pending, PendingDeletion};
++ use crate::memory::deletion::{PendingDeletion, enqueue, pending};
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
@@@ -86,7 -86,7 +86,7 @@@
#[tokio::test]
async fn the_background_job_retries_pending_deletions() {
-- use crate::memory::deletion::{enqueue, pending, PendingDeletion};
++ use crate::memory::deletion::{PendingDeletion, enqueue, pending};
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
diff --cc crates/openhuman-core/src/memory/confinement_tests.rs
index bf98d178da,0000000000..f216ed1c38
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/confinement_tests.rs
+++ b/crates/openhuman-core/src/memory/confinement_tests.rs
@@@ -1,270 -1,0 +1,272 @@@
+use std::sync::Arc;
+
+use tinymemory_api::{
+ Error, LearningKind, MemoryEngine, MemoryMeta, MetaFilter, Namespace, Reach, SourceKind,
+ SourceRef, StoreItem,
+};
+use tinymemory_tools::confine::{Confinement, Policy};
+use tinymemory_tools::layout::identity::Identity;
+
+use crate::memory::explore::{self, ItemsGetParams, PathStep};
+use crate::memory::test_fixtures::{bind_reference, config_in};
+use crate::memory::types::{FetchParams, ForgetParams, ItemsListParams, LearnParams, RecallParams};
+
+fn ns(raw: &str) -> Namespace {
+ raw.parse().unwrap()
+}
+
+fn confinement(config: &crate::config::Config, identity: &Identity) -> Confinement {
+ let resolved = identity.resolve(&crate::memory::scope::identity_pins(config));
+ Confinement {
+ allowed: Reach::subtree(resolved.root().clone()),
+ policy: Policy::Refuse,
+ }
+}
+
+fn learning_at(text: &str, namespace: &str) -> StoreItem {
+ StoreItem::learning(
+ text,
+ LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: ns(namespace),
+ source: SourceRef {
+ kind: SourceKind::Agent,
+ id: None,
+ },
+ ..MemoryMeta::default()
+ },
+ )
+}
+
+async fn two_roots(tmp: &tempfile::TempDir) -> (crate::config::Config, String, String) {
+ let mut config = config_in(tmp);
+ config.memory.root = Some("team:acme".to_string());
+ let engine = bind_reference(&config);
+ let mine = engine
+ .store(learning_at("acme ships on fridays", "team:acme"))
+ .await
+ .unwrap()
+ .id
+ .0;
+ let theirs = engine
+ .store(learning_at("other team secret plan", "team:other"))
+ .await
+ .unwrap()
+ .id
+ .0;
+ (config, mine, theirs)
+}
+
+fn ids(hits: &[tinymemory_api::Hit]) -> Vec<String> {
+ hits.iter().map(|hit| hit.id.0.clone()).collect()
+}
+
+#[test]
+fn rpc_refuse_uses_the_identity_subtree_and_rejects_wider_reaches() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = Some("project:q4".to_string());
+ let rpc = confinement(&config, &Identity::root());
+ assert_eq!(rpc.allowed, Reach::subtree(ns("project:q4")));
+ assert_eq!(rpc.reach(None).unwrap(), Reach::subtree(ns("project:q4")));
+
+ let narrow = Reach::exact(ns("project:q4/agent:writer"));
+ assert_eq!(rpc.reach(Some(narrow.clone())).unwrap(), narrow);
+ for wider in [
+ Reach::subtree(Namespace::ROOT),
+ Reach::subtree(ns("team:other")),
+ Reach::of(ns("project:q4/agent:writer")),
+ ] {
+ assert!(matches!(
+ rpc.reach(Some(wider)),
+ Err(Error::InvalidRequest(_))
+ ));
+ }
+
+ let team = confinement(&config_in(&tmp), &Identity::team_member("acme", "scout"));
+ assert_eq!(team.allowed, Reach::subtree(ns("team:acme")));
+}
+
+#[tokio::test]
+async fn rpc_list_fetch_and_recall_never_read_another_root() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (config, mine, theirs) = two_roots(&tmp).await;
+ let rpc = confinement(&config, &Identity::root());
+
+ let listed = crate::memory::ops::items_list(
+ &config,
+ ItemsListParams {
+ filter: Some(rpc.filter(None).unwrap()),
+ ..ItemsListParams::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(ids(&listed.items), std::slice::from_ref(&mine));
+
+ let page = crate::memory::ops::fetch(
+ &config,
+ FetchParams {
+ refers_to: None,
+ query: "plan".into(),
+ mode: None,
+ filter: Some(rpc.filter(None).unwrap()),
+ limit: Some(100),
+ cursor: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert!(!ids(&page.hits).contains(&theirs), "{:?}", ids(&page.hits));
+
+ let answer = crate::memory::ops::recall(
+ &config,
+ RecallParams {
+ refers_to: None,
+ question: "secret plan".into(),
+ filter: Some(rpc.filter(None).unwrap()),
+ limit: Some(10),
+ },
+ )
+ .await
+ .unwrap();
- assert!(answer
- .citations
- .iter()
- .all(|citation| citation.id.0 != theirs));
++ assert!(
++ answer
++ .citations
++ .iter()
++ .all(|citation| citation.id.0 != theirs)
++ );
+}
+
+#[tokio::test]
+async fn rpc_filter_and_explorer_paths_outside_the_identity_are_refused() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (config, _, _) = two_roots(&tmp).await;
+ let rpc = confinement(&config, &Identity::root());
+ let outside = MetaFilter {
+ reach: Some(Reach::subtree(ns("team:other"))),
+ ..MetaFilter::default()
+ };
+ assert!(matches!(
+ rpc.filter(Some(outside.clone())),
+ Err(Error::InvalidRequest(_))
+ ));
+
+ let path = vec![PathStep {
+ facet: tinymemory_api::Facet::Namespace,
+ value: "team:other".to_string(),
+ }];
+ let narrowed = explore::narrowed(None, &path).unwrap();
+ assert!(matches!(
+ rpc.filter(Some(narrowed)),
+ Err(Error::InvalidRequest(_))
+ ));
+
+ let response = crate::memory::ops::items_list(
+ &config,
+ ItemsListParams {
+ filter: Some(rpc.filter(None).unwrap()),
+ ..ItemsListParams::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.items.len(), 1);
+}
+
+#[tokio::test]
+async fn rpc_items_get_and_forget_cannot_reach_another_root() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (config, _, theirs) = two_roots(&tmp).await;
+ let rpc = confinement(&config, &Identity::root());
+
+ let get = explore::items_get(
+ &config,
+ ItemsGetParams {
+ ids: vec![theirs.clone()],
+ reach: Some(rpc.reach(None).unwrap()),
+ },
+ )
+ .await
+ .unwrap();
+ assert!(get.items.is_empty());
+
+ let forgotten = crate::memory::ops::forget(
+ &config,
+ ForgetParams {
+ ids: vec![theirs.clone()],
+ reach: Some(rpc.reach(None).unwrap()),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(forgotten.forgotten, 0);
+
+ let engine: Arc<dyn MemoryEngine> = crate::memory::engine::resolve(&config)
+ .engine()
+ .unwrap()
+ .engine;
+ assert_eq!(
+ ids(&engine
+ .list(tinymemory_api::ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::subtree(ns("team:other"))),
+ ..MetaFilter::default()
+ },
+ limit: 10,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items)
+ .as_slice(),
+ [theirs]
+ );
+}
+
+#[tokio::test]
+async fn rpc_learn_uses_the_layout_default_and_refuses_an_explicit_outside_namespace() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = Some("team:acme".to_string());
+ let engine = bind_reference(&config);
+ let identity = Identity::root().resolve(&crate::memory::scope::identity_pins(&config));
+ let rpc = confinement(&config, &Identity::root());
+ let default_meta = rpc.learn_meta(None, identity.layout.learnings()).unwrap();
+ let result = crate::memory::ops::learn(
+ &config,
+ LearnParams {
+ text: "my learning".into(),
+ kind: None,
+ confidence: None,
+ meta: Some(default_meta.clone()),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ let item = engine
+ .list(tinymemory_api::ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::subtree(ns("team:acme"))),
+ ..MetaFilter::default()
+ },
+ limit: 10,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items
+ .into_iter()
+ .find(|item| item.id.0 == result.id)
+ .unwrap();
+ assert_eq!(item.meta.namespace, default_meta.namespace);
+
+ let mut outside = MemoryMeta::default();
+ outside.namespace = ns("team:other");
+ assert!(matches!(
+ rpc.learn_meta(Some(outside), identity.layout.learnings()),
+ Err(Error::InvalidRequest(_))
+ ));
+}
diff --cc crates/openhuman-core/src/memory/deletion.rs
index ce54723247,25a4be5af9..71abecf1fa
--- a/crates/openhuman-core/src/memory/deletion.rs
+++ b/crates/openhuman-core/src/memory/deletion.rs
@@@ -4,7 -4,7 +4,7 @@@
//! thread it owned) or removing a source asks the engine to delete for good. When memory is off
//! (signed out, no credential) the engine cannot be reached, and when it
//! fails the deletion has not happened. Either way the deletion is recorded
--//! here, in `<workspace>/memory/pending_deletions.json`, and [`drain`] runs
++//! here, in the memory state KV value `pending_deletions`, and [`drain`] runs
//! it again on the next sign-in ([`super::bus`], on `CredentialChanged`) and
//! on every background tick, until it succeeds.
//!
@@@ -25,52 -25,33 +25,52 @@@ pub use tinymemory_tools::deletion::Pen
use crate::config::Config;
use super::engine;
-use super::error::{MemoryError, MemoryResult};
+use tinymemory_api::Error;
- fn path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("pending_deletions.json")
+ const STATE: &str = "pending_deletions";
+
++fn quarantine_corrupt_legacy_file(workspace_dir: &Path) {
++ let legacy = super::state_store::legacy_path(workspace_dir, STATE);
++ let Ok(bytes) = std::fs::read(&legacy) else {
++ return;
++ };
++ if serde_json::from_slice::<Vec<PendingDeletion>>(&bytes).is_ok() {
++ return;
++ }
++ if let Err(error) = std::fs::rename(&legacy, legacy.with_extension("json.corrupt")) {
++ tracing::warn!(%error, "[memory:deletion] could not set the file aside");
++ }
+}
+
- /// `<workspace>/memory/pending_deletions.json`: owner-only, written through a
- /// temporary file and a rename so a stop mid-write never loses the queue. An
- /// unparsable file is set aside; an empty queue removes the file.
+ /// The workspace's `pending_deletions` state value: a stop mid-write never
+ /// loses the queue (the storage write is atomic). An unparsable value is
+ /// dropped and logged; an empty queue removes the value.
struct FileStore {
- file: PathBuf,
+ workspace_dir: PathBuf,
}
impl ListStore<PendingDeletion> for FileStore {
- fn load(&self) -> Result<Vec<PendingDeletion>, StoreError> {
- super::state_store::load(&self.workspace_dir, STATE)
- .map(Option::unwrap_or_default)
- .or_else(|error| {
- tracing::warn!(%error, "[memory:deletion] pending deletions unreadable; dropped");
+ fn load(&self) -> std::result::Result<Vec<PendingDeletion>, StoreError> {
- let Ok(text) = std::fs::read_to_string(&self.file) else {
- return Ok(Vec::new());
- };
- Ok(serde_json::from_str(&text).unwrap_or_else(|error| {
- tracing::warn!(%error, "[memory:deletion] pending deletions unparsable; set aside");
- if let Err(error) =
- std::fs::rename(&self.file, self.file.with_extension("json.corrupt"))
- {
- tracing::warn!(%error, "[memory:deletion] could not set the file aside");
++ match super::state_store::load(&self.workspace_dir, STATE) {
++ Ok(Some(pending)) => Ok(pending),
++ Ok(None) => {
++ quarantine_corrupt_legacy_file(&self.workspace_dir);
+ Ok(Vec::new())
- })
+ }
- Vec::new()
- }))
++ Err(error) => {
++ tracing::warn!(%error, "[memory:deletion] reading pending deletions failed");
++ quarantine_corrupt_legacy_file(&self.workspace_dir);
++ Err(StoreError("pending deletions unreadable".into()))
++ }
++ }
}
- fn save(&self, all: &[PendingDeletion]) -> Result<(), StoreError> {
+ fn save(&self, all: &[PendingDeletion]) -> std::result::Result<(), StoreError> {
if all.is_empty() {
- return match std::fs::remove_file(&self.file) {
- Ok(()) => Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
- Err(error) => Err(StoreError(error.to_string())),
- };
+ return super::state_store::remove(&self.workspace_dir, STATE)
+ .map_err(|error| StoreError(error.to_string()));
}
- let temp = self.file.with_extension("json.tmp");
- self.file
- .parent()
- .map_or(Ok(()), super::files::create_private_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;
- super::files::write_private(&temp, &json)?;
- std::fs::rename(&temp, &self.file)
- })
+ super::state_store::save(&self.workspace_dir, STATE, &all)
.map_err(|error| StoreError(error.to_string()))
}
}
diff --cc crates/openhuman-core/src/memory/deletion_tests.rs
index a865cb7feb,531023ad66..4e7078e7e9
--- a/crates/openhuman-core/src/memory/deletion_tests.rs
+++ b/crates/openhuman-core/src/memory/deletion_tests.rs
@@@ -22,110 -20,6 +22,113 @@@ fn thread(id: &str) -> PendingDeletion
}
}
+#[tokio::test]
+async fn offline_conversation_purge_queues_exact_thread_ids_in_its_workspace() {
- use crate::threads::store::{ensure_thread, purge_threads, CreateConversationThread};
++ use crate::threads::store::{CreateConversationThread, ensure_thread, purge_threads};
+
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let workspace = config.workspace_dir.clone();
+ let other_workspace = tmp.path().join("other-workspace");
+ let ctx = crate::core::runtime::DispatchCtx::unbound();
+ let create = |id: &str| CreateConversationThread {
+ id: id.to_string(),
+ title: format!("Title {id}"),
+ created_at: "2026-10-18T00:00:00Z".to_string(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ working_dir: None,
+ };
+
+ ensure_thread(&ctx, workspace.clone(), create("channel-thread-a")).unwrap();
+ ensure_thread(&ctx, workspace.clone(), create("channel-thread-b")).unwrap();
+ enqueue(&other_workspace, thread("other-workspace-thread"));
+
+ let stats = purge_threads(&ctx, workspace.clone()).unwrap();
+
+ assert_eq!(stats.thread_count, 2);
+ assert_eq!(
+ pending(&workspace)
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>(),
+ [thread("channel-thread-a"), thread("channel-thread-b")]
+ .into_iter()
+ .collect()
+ );
+ assert_eq!(
+ pending(&other_workspace),
+ vec![thread("other-workspace-thread")]
+ );
+
+ let engine = bind_reference(&config);
+ engine
+ .store(conversation("channel-thread-a", "temporary transcript A"))
+ .await
+ .unwrap();
+ engine
+ .store(conversation("channel-thread-b", "temporary transcript B"))
+ .await
+ .unwrap();
+ engine
+ .store(conversation("unrelated-thread", "keep this transcript"))
+ .await
+ .unwrap();
+ engine
+ .store(StoreItem::learning(
+ "durable preference",
+ LearningKind::Preference,
+ 0.9,
+ MemoryMeta {
+ thread_id: Some("channel-thread-a".to_string()),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+ engine
+ .store(StoreItem::document(
+ "durable brain document",
+ MemoryMeta {
+ thread_id: Some("channel-thread-a".to_string()),
+ channel: Some("telegram".to_string()),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(drain(&config).await, 2);
+
+ let left = stored(&engine, MetaFilter::default()).await;
+ assert_eq!(left.len(), 3);
- assert!(left
- .iter()
- .any(|item| { item.kind == ItemKind::Learning && item.text == "durable preference" }));
- assert!(left
- .iter()
- .any(|item| { item.kind == ItemKind::Document && item.text == "durable brain document" }));
++ assert!(
++ left.iter()
++ .any(|item| { item.kind == ItemKind::Learning && item.text == "durable preference" })
++ );
++ assert!(
++ left.iter().any(|item| {
++ item.kind == ItemKind::Document && item.text == "durable brain document"
++ })
++ );
+ assert!(left.iter().any(|item| {
+ item.kind == ItemKind::Conversation
+ && item.meta.thread_id.as_deref() == Some("unrelated-thread")
+ }));
+ assert!(!left.iter().any(|item| {
+ item.kind == ItemKind::Conversation
+ && matches!(
+ item.meta.thread_id.as_deref(),
+ Some("channel-thread-a" | "channel-thread-b")
+ )
+ }));
+ assert!(pending(&workspace).is_empty());
+ assert_eq!(
+ pending(&other_workspace),
+ vec![thread("other-workspace-thread")]
+ );
+}
+
#[tokio::test]
async fn a_deleted_threads_conversation_is_forgotten_for_good() {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/memory/engine.rs
index 0b94d4a465,2a2a514673..b217dd2db0
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@@ -5,7 -5,7 +5,7 @@@
//!
//! | Engine | Endpoint | Credential | Off when |
//! | --- | --- | --- | --- |
- //! | `tinyhumans` | `[memory.engines.tinyhumans] endpoint`, else [`crate::backend::base_url`] | the host's backend credential, resolved per request through [`resolve_backend_credential`] | signed out, or no default backend transport |
-//! | `tinyhumans` | registered by the host layer that owns it ([`super::engine_registry`]) | the host's backend credential, resolved per request | not registered, or signed out |
++//! | `tinyhumans` | registered by the host layer that owns it | the host's backend credential, resolved per request | not registered, or signed out |
//! | `cortexdb` | `[memory.engines.cortexdb] endpoint`, else CortexDB's managed API | the API key stored as [`MEMORY_CORTEXDB_KEY_NAME`] | no key stored |
//!
//! Built engines are cached per config fingerprint (engine id, endpoint,
@@@ -26,38 -26,32 +26,37 @@@
//! it then wins over the configured one for every config in the process — one
//! OpenHuman runtime per process — so a host with its own store, or a test
//! binary with an in-memory engine, runs the whole lifecycle without a
-//! TinyHumans credential or a CortexDB key. It is wrapped in the same
-//! scrubber as a configured engine.
+//! TinyHumans credential or a CortexDB key. It is wrapped by TinyMemory's
+//! native binder under the same host scrub policy as a configured engine.
//!
- //! The core never holds a TinyHumans credential of its own: the bearer comes
- //! from the host's credential seam on every request, so a refreshed session is
- //! used at once and signing out turns memory off.
+ //! The core never holds a TinyHumans credential of its own: a registered
+ //! engine's bearer comes from the host's credential seam on every request, so
+ //! a refreshed session is used at once and signing out turns memory off.
use std::collections::HashMap;
-use std::sync::{Arc, LazyLock, RwLock};
+#[cfg(test)]
+use std::sync::RwLock;
+use std::sync::{Arc, LazyLock};
use sha2::{Digest, Sha256};
- use tinymemory_api::MemoryEngine;
- use tinymemory_integrations::{EngineCredential, EngineSettings};
-
+pub use tinymemory_api::Error as MemoryError;
+ use tinymemory_api::MemoryEngine;
-pub use tinymemory_integrations::{BearerSource, EngineCredential, EngineSettings};
+pub use tinymemory_integrations::cortex::CallbackBearerSource;
- pub use tinymemory_integrations::{BearerSource, Binding, BoundEngine, EngineBinder};
++pub use tinymemory_integrations::{
++ BearerSource, Binding, BoundEngine, EngineBinder, EngineCredential, EngineSettings,
++};
--use crate::config::schema::MEMORY_CORTEXDB_KEY_NAME;
use crate::config::Config;
--use crate::security::credentials::session_support::resolve_backend_credential;
++use crate::config::schema::MEMORY_CORTEXDB_KEY_NAME;
use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};
-use super::error::{MemoryError, MemoryResult};
+use tinymemory_api::{Error, Result};
/// Engine id of CortexDB behind the TinyHumans backend.
-pub const TINYHUMANS_ENGINE: &str = tinymemory_integrations::cortex::TINYHUMANS_ENGINE_ID;
+pub use tinymemory_integrations::cortex::TINYHUMANS_ENGINE_ID as TINYHUMANS_ENGINE;
/// Engine id of CortexDB reached directly.
-pub const CORTEXDB_ENGINE: &str = tinymemory_integrations::cortex::CORTEXDB_ENGINE_ID;
+pub use tinymemory_integrations::cortex::CORTEXDB_ENGINE_ID as CORTEXDB_ENGINE;
/// Pseudo-engine id for memory turned off on purpose: nothing is bound, so
/// nothing is stored or recalled until another engine is selected.
@@@ -336,97 -410,50 +347,6 @@@ fn off(engine: Option<&str>, endpoint:
}
}
- /// Builds TinyHumans settings for the selected memory layout and fingerprints
- /// the layout separately in the engine cache. The backend owns the TinyHumans
- /// tenant root, so no person-specific root is sent. With `legacy_read`, the
- /// earlier `user:<id>` root is also read and forgotten, never written.
- fn resolve_tinyhumans(config: &Config, root: Option<&str>) -> Binding {
- let endpoint = match config.memory.endpoint_for(TINYHUMANS_ENGINE) {
- Some(endpoint) => endpoint,
- None => match crate::backend::base_url(&config.api_url) {
- Ok(url) => url,
- Err(error) => {
- tracing::debug!(error = %error, "[memory:engine] no backend origin for tinyhumans");
- return off(
- Some(TINYHUMANS_ENGINE),
- None,
- "no TinyHumans backend is available",
- );
- }
- },
-/// The engine settings' layout for the person's root `root` (`org:<id>`,
-/// `None` the legacy tree), and the fingerprint suffix that keeps each
-/// layout's engine apart in the cache. On the TinyHumans wire (`tenant`)
-/// the root is the tenant's own, pinned by the backend, so none is sent;
-/// on CortexDB's own API it is the root, owned by the actor `user:<id>`.
-/// With `legacy_read`, the earlier `user:<id>` root is still read and
-/// forgotten (never written).
-pub fn rooted(
- settings: EngineSettings,
- root: Option<&str>,
- tenant: bool,
- legacy_read: bool,
-) -> (EngineSettings, String) {
- let Some(root) = root else {
- return (settings, "|root=legacy".to_string());
-- };
- if let Err(error) = resolve_backend_credential(config) {
- tracing::debug!(error = %error, "[memory:engine] no usable TinyHumans credential");
- return off(
- Some(TINYHUMANS_ENGINE),
- Some(endpoint),
- "sign in to use TinyHumans memory",
- );
- }
- // The backend expects the host's attribution (`x-sdk-name`, …) on every
- // request, as every other backend caller sends it; the transport owns it.
- let headers = attribution_headers();
- let actor = super::scope::actor_of_root(root);
- let retired = legacy_read.then(|| actor.clone());
-- let fingerprint = format!(
- "{TINYHUMANS_ENGINE}|{endpoint}|{}|{headers:?}",
- config.config_path.display()
- "|root={root}|tenant={tenant}|retired={}",
- retired.as_deref().unwrap_or("-")
-- );
- let source = backend_bearer_source(Arc::new(config.clone()));
- let (settings, layout) = EngineBinder::rooted(
- let settings = if tenant {
-- EngineSettings {
- endpoint: Some(endpoint),
- headers,
- ..EngineSettings::default()
- },
- root,
- true,
- config.memory.legacy_user_segment_read,
- );
- build_cached(
- TINYHUMANS_ENGINE,
- settings,
- fingerprint + &layout,
- EngineCredential::Dynamic(source),
- )
- }
-
- /// The installed transport's attribution headers, as engine settings carry
- /// them. A value that is not text is left out (and logged by name only).
- fn attribution_headers() -> std::collections::BTreeMap<String, String> {
- crate::backend::attribution_headers()
- .iter()
- .filter_map(|(name, value)| match value.to_str() {
- Ok(value) => Some((name.as_str().to_string(), value.to_string())),
- Err(_) => {
- tracing::debug!(header = %name, "[memory:engine] skipping a non-text attribution header");
- None
- }
- })
- .collect()
- }
-
- /// Resolve the backend credential on every memory request. An installed host
- /// transport can supply its own adapter; standalone core builds retain the
- /// explicit-endpoint path through the shared safe credential resolver.
- fn backend_bearer_source(config: Arc<Config>) -> Arc<dyn BearerSource> {
- if let Ok(transport) = crate::backend::resolve_backend_transport() {
- if let Some(source) = transport.memory_bearer_source(Arc::clone(&config)) {
- return source;
- tenant_root: true,
- retired_scope_root: retired,
- ..settings
-- }
- }
-
- Arc::new(CallbackBearerSource::new(move || {
- let config = Arc::clone(&config);
- async move {
- resolve_backend_credential(&config)
- .map(crate::security::credentials::session_support::BackendCredential::into_secret)
- .map_err(|error| {
- tracing::debug!(error = %error, "[memory:engine] backend credential unavailable");
- MemoryError::Unauthorized("the backend credential is unavailable".to_string())
- })
- } else {
- EngineSettings {
- scope_root: Some(root.to_string()),
- scope_owner: Some(actor),
- retired_scope_root: retired,
- ..settings
-- }
- }))
- };
- tracing::debug!(
- tenant,
- legacy_read,
- "[memory:engine] binding layout v3 below the person's org root"
- );
- (settings, fingerprint)
--}
--
fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {
let configured = config.memory.endpoint_for(CORTEXDB_ENGINE);
let endpoint = configured
@@@ -439,7 -466,7 +359,7 @@@
Some(CORTEXDB_ENGINE),
Some(endpoint),
"add a CortexDB API key to use CortexDB memory",
-- )
++ );
}
Err(error) => {
tracing::warn!(error = %error, "[memory:engine] reading the CortexDB key failed");
@@@ -480,22 -507,36 +400,39 @@@ pub fn build_cached
fingerprint: String,
credential: EngineCredential,
) -> Binding {
- let endpoint = settings.endpoint.clone().unwrap_or_default();
- if let Some(bound) = CACHE
- .read()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .get(&fingerprint)
- .cloned()
- {
- return Binding::On(bound);
- }
- match tinymemory_integrations::build_engine(id, &settings, credential) {
- Ok(engine) => {
- tracing::info!(engine = %id, "[memory:engine] engine bound");
- let bound = BoundEngine {
- engine: super::guard::ScrubbingEngine::wrap(engine),
- id: id.to_string(),
- endpoint: endpoint.to_string(),
- };
- CACHE
- .write()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(fingerprint, bound.clone());
- Binding::On(bound)
- }
- Err(error) => {
- tracing::warn!(engine = %id, error = %error, "[memory:engine] engine build refused");
- off(Some(id), Some(endpoint.to_string()), &error.to_string())
+ let binding = ENGINE_BINDER.bind_configured(
+ id,
+ settings,
+ &fingerprint,
+ credential,
+ crate::security::scrub::host_policy(),
+ );
+ match &binding {
+ Binding::On(_) => tracing::info!(engine = %id, "[memory:engine] engine bound"),
+ Binding::Off { reason, .. } => {
+ tracing::warn!(engine = %id, error = %reason, "[memory:engine] engine build refused");
}
}
+ binding
+}
+
++/// Applies TinyMemory's identity-root settings and returns the cache-key
++/// suffix that distinguishes legacy and user-scoped bindings.
++pub fn rooted(
++ settings: EngineSettings,
++ root: Option<&str>,
++ tenant: bool,
++ legacy_read: bool,
++) -> (EngineSettings, String) {
++ EngineBinder::rooted(settings, root, tenant, legacy_read)
++}
++
++/// Wraps a host-supplied engine with OpenHuman's scrubber and TinyMemory's
++/// operation timing decorator.
++pub fn bind_external(engine: Arc<dyn MemoryEngine>, endpoint: impl Into<String>) -> BoundEngine {
++ ENGINE_BINDER.bind_external(engine, endpoint, crate::security::scrub::host_policy())
+ }
+
/// A short, non-reversible identity of a key for the cache fingerprint.
fn key_digest(key: &str) -> String {
let digest = Sha256::digest(key.as_bytes());
@@@ -557,7 -601,7 +494,7 @@@ pub fn clear_cortexdb_key(config: &Conf
#[must_use]
pub fn has_key(config: &Config, id: &str) -> bool {
match id {
-- TINYHUMANS_ENGINE => resolve_backend_credential(config).is_ok(),
++ TINYHUMANS_ENGINE => resolve(config).is_on(),
CORTEXDB_ENGINE => matches!(read_cortexdb_key(config), Ok(Some(_))),
_ => false,
}
diff --cc crates/openhuman-core/src/memory/engine_registry.rs
index 0000000000,ba1d8de240..8d4dd2af3d
mode 000000,100644..100644
--- a/crates/openhuman-core/src/memory/engine_registry.rs
+++ b/crates/openhuman-core/src/memory/engine_registry.rs
@@@ -1,0 -1,102 +1,100 @@@
+ //! Registered memory engines, keyed by engine id.
+ //!
+ //! [`engine::resolve`](super::engine::resolve) builds the engines the core
+ //! knows (`cortexdb`, `none`). An outside crate registers another under its own
+ //! id with [`register_memory_engine`]: the builder turns the `[memory]` config
+ //! (and the layout root) into a [`Binding`], and an optional predicate says
+ //! whether background memory work is free for it.
+ //!
+ //! Unlike [`install_host_engine`](super::engine::install_host_engine), which
+ //! binds one engine for the whole process and is ignored under SaaS, a
+ //! registered engine is resolved per config like any configured engine, so it
+ //! is admitted for every tenant: the builder receives that tenant's config and
+ //! root. Registered ids win over the built-in match, and with nothing
+ //! registered the engine selection and the free-period check are unchanged.
+ //!
+ //! Free background work ([`free_period_active`](super::billing::free_period_active)):
+ //! an engine with no registration is free, a registered engine is free unless
+ //! its predicate says otherwise (a registration without one is free), and an
+ //! unbound engine is not free.
+
+ use std::future::Future;
+ use std::pin::Pin;
+ use std::sync::Arc;
+
+ use tinymemory_api::MemoryEngine;
+
+ use super::engine::{Binding, BoundEngine};
+ use crate::config::Config;
+ use crate::core::slots::{Extensions, HookSlot};
+
+ /// A boxed `Send` future.
+ pub type EngineFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
+
+ /// What a registered engine builder is asked to bind.
+ pub struct EngineRequest<'a> {
+ /// The tenant's configuration.
+ pub config: &'a Config,
+ /// The layout root: `None` the legacy tree, `Some("user:<id>")` the
+ /// person's subtree.
+ pub root: Option<&'a str>,
+ }
+
+ /// Binds the engine for a config and layout root.
+ pub type EngineBuilder = Arc<dyn for<'a> Fn(&EngineRequest<'a>) -> Binding + Send + Sync>;
+
+ /// Whether background memory work is free for the bound engine and config.
+ pub type FreeBackground = Arc<dyn Fn(Config, BoundEngine) -> EngineFuture<bool> + Send + Sync>;
+
+ /// A registered memory engine.
+ #[derive(Clone)]
+ pub struct EngineEntry {
+ /// Binds the engine.
+ pub build: EngineBuilder,
+ /// Optional "background work is free" predicate; `None` means always free.
+ pub free_background: Option<FreeBackground>,
+ }
+
+ static ENGINES: HookSlot<EngineEntry> = HookSlot::new("memory::engines");
+
+ /// Registers the memory engine `engine_id` for the whole process.
+ pub fn register_memory_engine(engine_id: impl Into<String>, entry: EngineEntry) {
+ ENGINES.register(engine_id, entry);
+ }
+
+ /// Registers the memory engine `engine_id` for the context built from
+ /// `extensions`.
+ pub fn register_memory_engine_in(
+ extensions: &Extensions,
+ engine_id: impl Into<String>,
+ entry: EngineEntry,
+ ) {
+ ENGINES.register_in(extensions, engine_id, entry);
+ }
+
+ /// Removes the process-wide memory engine `engine_id`.
+ pub fn unregister_memory_engine(engine_id: &str) -> bool {
+ ENGINES.unregister(engine_id)
+ }
+
+ /// The registered entry for `engine_id`, if any.
+ pub(crate) fn lookup(engine_id: &str) -> Option<EngineEntry> {
+ ENGINES.get(engine_id)
+ }
+
+ /// Wraps `engine` as a [`BoundEngine`] with the same write scrubbing every
+ /// configured engine gets. A registered builder returns
+ /// `Binding::On(bound_engine(..))`.
+ pub fn bound_engine(
+ id: impl Into<String>,
+ endpoint: impl Into<String>,
+ engine: Arc<dyn MemoryEngine>,
+ ) -> BoundEngine {
- BoundEngine {
- id: id.into(),
- endpoint: endpoint.into(),
- engine: super::guard::ScrubbingEngine::wrap(engine),
- }
++ let mut bound = super::engine::bind_external(engine, endpoint);
++ bound.id = id.into();
++ bound
+ }
+
+ #[cfg(test)]
+ #[path = "engine_registry_tests.rs"]
+ mod tests;
diff --cc crates/openhuman-core/src/memory/engine_registry_tests.rs
index 0000000000,58319cdfcf..d09364fc8e
mode 000000,100644..100644
--- a/crates/openhuman-core/src/memory/engine_registry_tests.rs
+++ b/crates/openhuman-core/src/memory/engine_registry_tests.rs
@@@ -1,0 -1,102 +1,102 @@@
+ use super::*;
+ use crate::memory::billing::free_period_active;
+ use crate::memory::engine::{bind_with_root, resolve};
+ use crate::memory::test_fixtures::config_in;
-use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Mutex;
++use std::sync::atomic::{AtomicBool, Ordering};
+ use tinymemory_api::conformance::ReferenceEngine;
+
+ const ID: &str = "registry-test-engine";
+
+ fn config_for(tmp: &tempfile::TempDir) -> Config {
+ let mut config = config_in(tmp);
+ config.memory.engine = ID.to_string();
+ config
+ }
+
+ fn entry(roots: Arc<Mutex<Vec<Option<String>>>>, free: Option<FreeBackground>) -> EngineEntry {
+ EngineEntry {
+ build: Arc::new(move |request| {
+ roots.lock().unwrap().push(request.root.map(str::to_string));
+ Binding::On(bound_engine(
+ ID,
+ "registered://engine",
+ Arc::new(ReferenceEngine::new()),
+ ))
+ }),
+ free_background: free,
+ }
+ }
+
+ #[test]
+ fn an_unregistered_engine_id_stays_off() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ assert!(!resolve(&config).is_on());
+ }
+
+ #[test]
+ fn a_registered_engine_is_bound_with_its_endpoint() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ register_memory_engine(ID, entry(Arc::default(), None));
+ let binding = resolve(&config);
+ unregister_memory_engine(ID);
+ let bound = binding.engine().expect("bound");
+ assert_eq!(bound.id, ID);
+ assert_eq!(bound.endpoint, "registered://engine");
+ }
+
+ #[test]
+ fn the_layout_root_reaches_the_registered_builder() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ let roots = Arc::new(Mutex::new(Vec::new()));
+ register_memory_engine(ID, entry(Arc::clone(&roots), None));
+ let _ = bind_with_root(&config, Some("user:abc"));
+ let _ = bind_with_root(&config, None);
+ unregister_memory_engine(ID);
+ assert_eq!(
+ *roots.lock().unwrap(),
+ vec![Some("user:abc".to_string()), None]
+ );
+ }
+
+ #[tokio::test]
+ async fn a_registered_engine_without_a_predicate_is_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ register_memory_engine(ID, entry(Arc::default(), None));
+ let free = free_period_active(&config).await;
+ unregister_memory_engine(ID);
+ assert!(free);
+ }
+
+ #[tokio::test]
+ async fn the_registered_predicate_decides_whether_background_work_is_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ let answer = Arc::new(AtomicBool::new(false));
+ let shared = Arc::clone(&answer);
+ let predicate: FreeBackground = Arc::new(move |_, bound| {
+ let shared = Arc::clone(&shared);
+ Box::pin(async move {
+ assert_eq!(bound.id, ID);
+ shared.load(Ordering::SeqCst)
+ })
+ });
+ register_memory_engine(ID, entry(Arc::default(), Some(predicate)));
+ let paused = free_period_active(&config).await;
+ answer.store(true, Ordering::SeqCst);
+ let free = free_period_active(&config).await;
+ unregister_memory_engine(ID);
+ assert!(!paused);
+ assert!(free);
+ }
+
+ #[tokio::test]
+ async fn an_unbound_engine_is_not_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_for(&tmp);
+ assert!(!free_period_active(&config).await);
+ }
diff --cc crates/openhuman-core/src/memory/engine_tests.rs
index 7977ef934f,698bcf841a..4c3ffb2009
--- a/crates/openhuman-core/src/memory/engine_tests.rs
+++ b/crates/openhuman-core/src/memory/engine_tests.rs
@@@ -1,24 -1,7 +1,21 @@@
use super::*;
use crate::memory::test_fixtures::config_in;
- use crate::security::credentials::api_key::store_api_key;
-
- use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
+struct ClearInstalledHostEngine;
+
+impl Drop for ClearInstalledHostEngine {
+ fn drop(&mut self) {
+ clear_host_engine();
+ }
+}
+
+struct RemoveTestEngine(std::path::PathBuf);
+
+impl Drop for RemoveTestEngine {
+ fn drop(&mut self) {
+ remove_test_engine(&self.0);
+ }
+}
fn off_reason(binding: Binding) -> String {
match binding {
@@@ -27,145 -10,8 +24,145 @@@
}
}
+async fn assert_host_scrubbing(
+ bound: BoundEngine,
+ reference: &tinymemory_api::conformance::ReferenceEngine,
+) {
+ const SECRET: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+ const PHONE: &str = "+15551234567";
+ const BARE_NUMBER: &str = "79927398713";
+
+ bound
+ .engine
+ .store(tinymemory_api::StoreItem::document(
+ format!("contact {PHONE}; key={SECRET}; reference {BARE_NUMBER}"),
+ tinymemory_api::MemoryMeta::default(),
+ ))
+ .await
+ .expect("the bound engine accepts the test item");
+
+ let saved = reference
+ .list(tinymemory_api::ListRequest::new(
+ tinymemory_api::MetaFilter::default(),
+ 5,
+ ))
+ .await
+ .expect("reference engine lists the saved item");
+ let text = saved
+ .items
+ .iter()
+ .find(|hit| hit.text.contains(BARE_NUMBER))
+ .map(|hit| hit.text.as_str())
+ .expect("the corroborated host policy preserves an unqualified number");
+
+ assert!(
+ !text.contains(SECRET),
+ "credentials are scrubbed before store"
+ );
+ assert!(
+ !text.contains(PHONE),
+ "phone numbers are scrubbed before store"
+ );
+}
+
+#[tokio::test]
+async fn installed_host_engine_binding_uses_the_host_scrub_policy() {
+ const CHILD_FLAG: &str = "OPENHUMAN_MEMORY_HOST_POLICY_CHILD";
+ const CHILD_MARKER: &str = "HOST_ENGINE_POLICY_CHILD_EXECUTED";
+
+ if std::env::var_os(CHILD_FLAG).as_deref() != Some(std::ffi::OsStr::new("1")) {
+ let exact_test =
+ "memory::engine::tests::installed_host_engine_binding_uses_the_host_scrub_policy";
+ let child = std::process::Command::new(std::env::current_exe().unwrap())
+ .arg("--exact")
+ .arg(exact_test)
+ .arg("--nocapture")
+ .env(CHILD_FLAG, "1")
+ .output()
+ .expect("test child starts");
+ let stdout = String::from_utf8_lossy(&child.stdout);
+ let stderr = String::from_utf8_lossy(&child.stderr);
+ assert!(
+ child.status.success(),
+ "host-engine child failed: stdout={stdout}\nstderr={stderr}"
+ );
+ assert_eq!(
+ stdout.matches(CHILD_MARKER).count(),
+ 1,
+ "the exact child test must execute once: stdout={stdout}\nstderr={stderr}"
+ );
+ return;
+ }
+
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
+
+ clear_host_engine();
+ let _cleanup = ClearInstalledHostEngine;
+ install_host_engine(reference.clone());
+ let bound = resolve(&config)
+ .engine()
+ .expect("installed host engine binds");
+ assert_host_scrubbing(bound, &reference).await;
+ println!("{CHILD_MARKER}");
+}
+
+#[tokio::test]
+async fn test_engine_binding_uses_the_host_scrub_policy() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
+
+ let _cleanup = RemoveTestEngine(config.workspace_dir.clone());
+ install_test_engine(&config.workspace_dir, reference.clone());
+ let bound = resolve(&config).engine().expect("test engine binds");
+ assert_host_scrubbing(bound, &reference).await;
+}
+
+#[tokio::test]
+async fn profile_engine_binding_uses_the_host_scrub_policy() {
+ let tmp = tempfile::tempdir().unwrap();
+ let profile_id = "6512ab0f6512ab0f6512ab0f";
+ let mut config = config_in(&tmp);
+ config.memory.agent_id = Some(profile_id.to_string());
+ config.memory.root = Some(format!("user:{profile_id}"));
+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
+ let capabilities = Arc::new(crate::profiles::capabilities::ProfileCapabilities::new(
+ None,
+ None,
+ None,
+ Default::default(),
+ Vec::new(),
+ Some(reference.clone()),
+ ));
+ let mut overrides = crate::agent::host_overrides::HostOverrides::default();
+ overrides.profile_capabilities = Some(capabilities);
+ let parent = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(config.workspace_dir.clone()),
+ );
+ let profile = parent.derive_with(
+ crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .profile(profile_id)
+ .host_overrides(Arc::new(overrides)),
+ );
+
+ crate::core::runtime::CoreContext::scope(profile, async {
+ let bound = resolve(&config)
+ .engine()
+ .expect("profile engine binds with its forced root");
+ assert_host_scrubbing(bound, &reference).await;
+ })
+ .await;
+}
+
#[test]
- fn tinyhumans_without_a_credential_is_off() {
+ fn tinyhumans_with_nothing_registered_is_unavailable() {
let tmp = tempfile::tempdir().unwrap();
let mut config = config_in(&tmp);
config.memory.engine = TINYHUMANS_ENGINE.to_string();
@@@ -188,63 -28,25 +179,9 @@@
Binding::On(_) => unreachable!(),
}
let error = resolve(&config).engine().unwrap_err();
- assert_eq!(error.code(), super::super::error::MEMORY_OFF);
-}
-
-#[test]
-fn a_local_session_token_is_not_a_tinyhumans_credential() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- AuthService::from_config(&config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- "desktop.test.local",
- std::collections::HashMap::new(),
- true,
- )
- .unwrap();
- assert!(!has_key(&config, TINYHUMANS_ENGINE));
+ assert_eq!(error.code(), "MEMORY_OFF");
}
- #[test]
- fn tinyhumans_with_a_local_session_token_is_off() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.engine = TINYHUMANS_ENGINE.to_string();
- config
- .memory
- .engines
- .entry(TINYHUMANS_ENGINE.to_string())
- .or_default()
- .endpoint = Some("https://memory.example.test".to_string());
- AuthService::from_config(&config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- "desktop.test.local",
- std::collections::HashMap::new(),
- true,
- )
- .unwrap();
-
- let binding = resolve(&config);
-
- assert!(!binding.is_on());
- assert!(!has_key(&config, TINYHUMANS_ENGINE));
- assert!(off_reason(binding).contains("sign in"));
- }
-
- #[test]
- fn tinyhumans_with_the_host_credential_binds_and_caches() {
- let _stable = CACHE_STABLE
- .write()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config
- .memory
- .engines
- .entry(TINYHUMANS_ENGINE.to_string())
- .or_default()
- .endpoint = Some("https://memory.example.test".to_string());
- store_api_key(&config, "test-api-key-not-real").unwrap();
- assert!(has_key(&config, TINYHUMANS_ENGINE));
-
- let first = resolve(&config).engine().expect("bound");
- assert_eq!(first.id, TINYHUMANS_ENGINE);
- assert_eq!(first.endpoint, "https://memory.example.test");
- let second = resolve(&config).engine().expect("bound again");
- assert!(
- Arc::ptr_eq(&first.engine, &second.engine),
- "cached engine reused"
- );
- }
-
#[test]
fn unknown_and_blank_engine_ids_are_off() {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/memory/explore.rs
index cb8bb4f4fe,c10fe2cfe1..edb012ed1c
--- a/crates/openhuman-core/src/memory/explore.rs
+++ b/crates/openhuman-core/src/memory/explore.rs
@@@ -19,7 -18,22 +19,7 @@@ use tinymemory_tools::ops::ExploreOptio
use crate::config::Config;
use super::engine;
- pub use tinymemory_tools::ops::{narrowed, PathStep, DEFAULT_BUCKETS, MAX_PATH_STEPS};
-use super::error::{MemoryError, MemoryResult};
-
-/// Default bucket count of `memory_explore`.
-pub const DEFAULT_BUCKETS: usize = 50;
-
-/// Most steps an explorer path may take (one per facet is the useful most).
-pub const MAX_PATH_STEPS: usize = 16;
-
-/// One step down the explorer: the items whose `facet` is `value`.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct PathStep {
- /// The facet.
- pub facet: Facet,
- /// Its chosen value, as a bucket reported it.
- pub value: String,
-}
++pub use tinymemory_tools::ops::{DEFAULT_BUCKETS, MAX_PATH_STEPS, PathStep, narrowed};
/// `memory_explore` params.
#[derive(Debug, Clone, Deserialize)]
diff --cc crates/openhuman-core/src/memory/guard_tests.rs
index 8589826f70,6b1483b1fe..f53a2e488d
--- a/crates/openhuman-core/src/memory/guard_tests.rs
+++ b/crates/openhuman-core/src/memory/guard_tests.rs
@@@ -1,18 -1,310 +1,18 @@@
-use super::*;
+use std::sync::Arc;
-use tinymemory_api::conformance::ReferenceEngine;
-use tinymemory_api::{MemoryMeta, MetaFilter};
+use tinymemory_api::{MemoryEngine, StoreItem};
- use tinymemory_integrations::safety::{scrub_item_with, Policy};
+use tinymemory_integrations::EngineBinder;
++use tinymemory_integrations::safety::{Policy, scrub_item_with};
-const SECRET: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
-
-async fn texts(engine: &ReferenceEngine) -> Vec<String> {
- engine
- .list(ListRequest {
- filter: MetaFilter::default(),
- limit: 50,
- cursor: None,
- })
- .await
- .unwrap()
- .items
- .into_iter()
- .map(|hit| hit.text)
- .collect()
-}
-
-#[tokio::test]
-async fn every_write_path_is_scrubbed() {
- let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
- let item =
- |text: &str| StoreItem::document(format!("{text} key={SECRET}"), MemoryMeta::default());
-
- guarded.store(item("one")).await.unwrap();
- guarded
- .store_with(item("two"), WriteOptions::accepted())
- .await
- .unwrap();
- guarded
- .store_many(vec![item("three"), item("four")])
- .await
- .unwrap();
- guarded
- .store_many_with(vec![item("five"), item("six")], WriteOptions::accepted())
- .await
- .unwrap();
-
- let stored = texts(&reference).await;
- assert_eq!(stored.len(), 6);
- assert!(
- stored.iter().all(|text| !text.contains(SECRET)),
- "a secret reached the engine: {stored:?}"
- );
- assert_eq!(guarded.descriptor().id, reference.descriptor().id);
-}
-
-#[test]
-fn a_timed_call_reports_ok_or_the_error_code() {
- assert_eq!(outcome(&Ok::<(), _>(())), "ok");
- let refused: Result<()> = Err(tinymemory_api::Error::Unauthorized("bad key".into()));
- assert_eq!(outcome(&refused), "UNAUTHORIZED");
-}
-
-#[tokio::test]
-async fn every_read_passes_through_the_timer_unchanged() {
- let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
- let id = guarded
- .store(StoreItem::document("oolong tea", MemoryMeta::default()))
- .await
- .unwrap()
- .id;
- let reach = tinymemory_api::Reach::subtree(tinymemory_api::Namespace::ROOT);
-
- assert_eq!(guarded.health().await, reference.health().await);
- assert_eq!(
- guarded
- .recall(RecallRequest::new("oolong", 5))
- .await
- .unwrap(),
- reference
- .recall(RecallRequest::new("oolong", 5))
- .await
- .unwrap()
- );
- let fetch = || FetchRequest::new("oolong", tinymemory_api::FetchMode::Keyword, 5);
- assert_eq!(
- guarded.fetch(fetch()).await.unwrap(),
- reference.fetch(fetch()).await.unwrap()
- );
- let get = || GetRequest {
- ids: vec![id.clone()],
- reach: None,
- };
- assert_eq!(guarded.get(get()).await.unwrap().len(), 1);
- let explore = || ExploreRequest::new(tinymemory_api::Facet::Kind, 5);
- assert_eq!(
- guarded.explore(explore()).await.ok(),
- reference.explore(explore()).await.ok()
- );
- assert_eq!(
- guarded
- .consolidate(ConsolidateRequest::new(reach.clone()))
- .await
- .ok(),
- reference
- .consolidate(ConsolidateRequest::new(reach.clone()))
- .await
- .ok()
- );
- assert_eq!(
- guarded
- .beliefs(BeliefsRequest::new(reach.clone(), 5))
- .await
- .ok(),
- reference.beliefs(BeliefsRequest::new(reach, 5)).await.ok()
- );
- assert_eq!(
- guarded
- .forget(ForgetTarget::Ids(vec![id]))
- .await
- .unwrap()
- .forgotten,
- 1
- );
-}
-
-#[test]
-fn scrubbing_keeps_the_page_breaks_a_document_is_chunked_by() {
- let body = format!("Page one key={SECRET}\u{c}Page two.\u{c}Page three.");
- let scrubbed = scrub(StoreItem::document(body, MemoryMeta::default()));
- let StoreItem::Document {
- body: tinymemory_api::DocumentBody::Text(text),
- ..
- } = scrubbed
- else {
- panic!("a document");
- };
- assert!(!text.contains(SECRET), "{text}");
- assert_eq!(text.matches('\u{c}').count(), 2, "{text:?}");
- assert!(text.ends_with("\u{c}Page two.\u{c}Page three."), "{text:?}");
+fn wrap(engine: Arc<dyn MemoryEngine>) -> Arc<dyn MemoryEngine> {
+ EngineBinder::default()
+ .bind_external(engine, "test://engine", Policy::corroborated())
+ .engine
}
-#[tokio::test]
-async fn export_and_erase_reach_the_wrapped_engine() {
- let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
- let namespace: tinymemory_api::Namespace = "agent:a".parse().unwrap();
- guarded
- .store(StoreItem::document(
- "kept whole",
- MemoryMeta {
- namespace: namespace.clone(),
- ..MemoryMeta::default()
- },
- ))
- .await
- .unwrap();
- let page = guarded
- .export(ListRequest::new(MetaFilter::default(), 10))
- .await
- .expect("export is forwarded, not refused by the wrapper");
- assert_eq!(page.items.len(), 1);
- let report = guarded
- .erase(EraseRequest::new(tinymemory_api::Reach::exact(namespace)))
- .await
- .expect("erase is forwarded, not refused by the wrapper");
- assert_eq!(report.erased_scopes, 1);
- assert!(texts(&reference).await.is_empty());
+fn scrub(item: StoreItem) -> StoreItem {
+ scrub_item_with(item, Policy::corroborated()).value
}
-/// Records the wait each bulk store asks for, storing through a reference
-/// engine.
-#[derive(Default)]
-struct Recording {
- inner: ReferenceEngine,
- waits: std::sync::Mutex<Vec<WaitFor>>,
- reaches: std::sync::Mutex<Vec<Reach>>,
-}
-
-#[async_trait::async_trait]
-impl MemoryEngine for Recording {
- fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {
- self.inner.descriptor()
- }
- async fn health(&self) -> tinymemory_api::EngineHealth {
- self.inner.health().await
- }
- async fn recall(&self, req: RecallRequest) -> Result<tinymemory_api::RecallAnswer> {
- self.inner.recall(req).await
- }
- async fn fetch(&self, req: FetchRequest) -> Result<tinymemory_api::FetchPage> {
- self.inner.fetch(req).await
- }
- async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {
- self.inner.store(item).await
- }
- async fn store_many_with(
- &self,
- items: Vec<StoreItem>,
- options: WriteOptions,
- ) -> Result<Vec<StoreReceipt>> {
- self.waits.lock().unwrap().push(options.wait);
- self.inner.store_many(items).await
- }
- async fn forget(
- &self,
- target: tinymemory_api::ForgetTarget,
- ) -> Result<tinymemory_api::ForgetReport> {
- self.inner.forget(target).await
- }
- async fn forget_within(&self, ids: Vec<ItemId>, reach: Reach) -> Result<ForgetReport> {
- self.reaches.lock().unwrap().push(reach.clone());
- self.inner.forget_within(ids, reach).await
- }
- async fn list(&self, req: ListRequest) -> Result<tinymemory_api::ListPage> {
- self.inner.list(req).await
- }
-}
-
-#[tokio::test]
-async fn forget_within_reaches_the_wrapped_engine_with_its_reach() {
- let recording = Arc::new(Recording::default());
- let guarded = ScrubbingEngine::wrap(recording.clone());
- let reach = Reach::subtree("agent:ann".parse::<tinymemory_api::Namespace>().unwrap());
- guarded
- .forget_within(vec![ItemId::new("a")], reach.clone())
- .await
- .unwrap();
- assert_eq!(
- *recording.reaches.lock().unwrap(),
- vec![reach],
- "the guard forwards forget_within instead of the default's forget by id"
- );
-}
-
-#[tokio::test]
-async fn a_bulk_store_keeps_its_wait_through_the_guard() {
- let recording = Arc::new(Recording::default());
- let guarded = ScrubbingEngine::wrap(recording.clone());
- let items = || vec![StoreItem::document("tea", MemoryMeta::default())];
- guarded
- .store_many_with(items(), WriteOptions::accepted())
- .await
- .unwrap();
- guarded
- .store_many_with(items(), WriteOptions::visible())
- .await
- .unwrap();
- assert_eq!(
- *recording.waits.lock().unwrap(),
- vec![WaitFor::Accepted, WaitFor::Visible],
- "the guard passes the wait on instead of serving it as store_many"
- );
-}
-
-/// The reference engine, with a preview listing that says it is one, so a
-/// wrapper that fell back to `list` would show.
-struct MarkedPreview(ReferenceEngine);
-
-#[async_trait]
-impl MemoryEngine for MarkedPreview {
- fn descriptor(&self) -> &EngineDescriptor {
- self.0.descriptor()
- }
- async fn health(&self) -> EngineHealth {
- self.0.health().await
- }
- async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {
- self.0.recall(req).await
- }
- async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {
- self.0.fetch(req).await
- }
- async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {
- self.0.store(item).await
- }
- async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {
- self.0.forget(target).await
- }
- async fn list(&self, req: ListRequest) -> Result<ListPage> {
- self.0.list(req).await
- }
- async fn list_preview(&self, req: ListRequest) -> Result<ListPage> {
- let mut page = self.0.list(req).await?;
- for hit in &mut page.items {
- hit.text = format!("preview: {}", hit.text);
- }
- Ok(page)
- }
-}
-
-#[tokio::test]
-async fn a_preview_listing_reaches_the_wrapped_engine() {
- let guarded = ScrubbingEngine::wrap(Arc::new(MarkedPreview(ReferenceEngine::new())));
- guarded
- .store(StoreItem::document("oolong tea", MemoryMeta::default()))
- .await
- .unwrap();
- let req = || ListRequest {
- filter: MetaFilter::default(),
- limit: 5,
- cursor: None,
- };
- let preview = guarded.list_preview(req()).await.unwrap();
- assert_eq!(preview.items.len(), 1);
- assert!(
- preview.items[0].text.starts_with("preview: "),
- "{}",
- preview.items[0].text
- );
- let whole = guarded.list(req()).await.unwrap();
- assert!(!whole.items[0].text.starts_with("preview: "));
-}
+#[path = "guard_inner_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/memory/import.rs
index 3f973f7d5f,02bc2a9394..7cec741375
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@@ -1,11 -1,15 +1,11 @@@
//! Importing a v1 memory store into the selected engine.
//!
-//! The driver (batching, checkpoints, backoff, failed-item list, retry) is
-//! `tinymemory_integrations::import::Importer`. This file is the host
-//! adapter around it: the consent gate, the one-run-per-workspace registry,
-//! the durable state value `import_state`, the tokio
-//! clock, the scheduler pause, the credits resume policy, and what follows a
-//! finished import (organizing the tree).
+//! TinyMemory owns import batching, checkpoints, retry and backoff. This host
- //! adapter keeps consent, the existing atomic checkpoint path, billing and
++//! adapter keeps consent, the state-KV checkpoint, billing and
+//! scheduler policy, executor context, and post-import layout migration.
-use std::collections::HashSet;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::Arc;
use std::time::Duration;
use tinymemory_integrations::import::{
@@@ -14,31 -17,54 +14,33 @@@
};
use crate::config::Config;
- use crate::security::secret_storage::file_store::write_atomic;
use super::engine;
-use super::error::{MemoryError, MemoryResult};
-use super::types::{ImportCounts, ImportPhase, ImportScanView, ImportState};
+use super::run_slots::{self, BACKFILL, IMPORT, MIGRATION};
+use super::types::{ImportCounts, ImportScanView};
+use tinymemory_api::{Error, Result};
/// Whether background work is paused right now. An automatic resume asks
/// before it starts and again before every batch it stores.
pub(crate) type PauseCheck = Arc<dyn Fn() -> bool + Send + Sync>;
-/// Whether memory work that uploads on its own, with no user action (an
-/// automatic import, or resuming one paused for credits), may run now.
+/// Whether memory work that uploads on its own may run now.
pub(crate) type BillingCheck = Arc<dyn Fn(&Config) -> bool + Send + Sync>;
- /// The state file, written atomically (staged, synced, renamed): a crash
- /// mid-write leaves the previous state, never a torn file that reads back as
- /// a fresh start and re-sends everything.
- pub(crate) struct FileCheckpointStore {
- path: PathBuf,
-/// Imports running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// Held while an import or a layout migration decides to start: each checks
-/// the other is not going, then registers itself, under this one lock, so
-/// neither can slip in between the other's check and its registration.
-pub(crate) static START_GATE: Mutex<()> = Mutex::new(());
-
-fn running(workspace_dir: &Path) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(workspace_dir)
-}
-
-fn release(workspace_dir: &Path) {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(workspace_dir);
-}
-
-/// The `import_state` value in the memory state KV store. The first read
-/// imports a legacy workspace file; later reads and writes use the storage
-/// port, so a crash cannot turn a partial file write into a fresh start.
++/// The imported state-KV checkpoint.
+ pub(crate) struct StateKvCheckpointStore {
+ workspace_dir: PathBuf,
}
- impl FileCheckpointStore {
+ const STATE: &str = "import_state";
+
++/// Backwards-compatible name for the former file checkpoint adapter.
++pub(crate) type FileCheckpointStore = StateKvCheckpointStore;
++
+ impl StateKvCheckpointStore {
pub(crate) fn new(workspace_dir: &Path) -> Self {
Self {
- path: workspace_dir.join("memory").join("import_state.json"),
+ workspace_dir: workspace_dir.to_path_buf(),
}
}
}
@@@ -51,9 -79,9 +55,9 @@@ impl CheckpointStore for StateKvCheckpo
.unwrap_or_default()
}
- fn save(&self, file: &ImportFile) -> Result<(), String> {
+ fn save(&self, file: &ImportFile) -> std::result::Result<(), String> {
- let json = serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?;
- write_atomic(&self.path, &json).map_err(|error| error.to_string())
+ super::state_store::save(&self.workspace_dir, STATE, file)
+ .map_err(|error| error.to_string())
}
}
diff --cc crates/openhuman-core/src/memory/import_tests.rs
index 9fadea5f55,db2ccfadd5..c764a34aa1
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@@ -1,10 -1,10 +1,10 @@@
use super::*;
-use crate::memory::test_fixtures::config_in;
+use crate::memory::test_fixtures::{bind_reference, config_in};
#[test]
- fn the_state_file_round_trips_through_the_atomic_store() {
+ fn the_state_round_trips_through_the_store() {
let tmp = tempfile::tempdir().unwrap();
- let store = FileCheckpointStore::new(tmp.path());
+ let store = StateKvCheckpointStore::new(tmp.path());
assert_eq!(
store.load(),
ImportFile::default(),
@@@ -127,88 -126,6 +126,90 @@@ async fn a_paused_scheduler_leaves_an_i
);
}
+#[tokio::test]
+async fn a_live_import_blocks_migration_and_does_not_make_a_stale_migration_look_live() {
- use crate::memory::layout_migration::{self, state, test_host::FakeHost, Phase, Trigger};
++ use crate::memory::layout_migration::{self, Phase, Trigger, state, test_host::FakeHost};
+
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let host = Arc::new(FakeHost::with(2, &config).await);
+ let workspace = config.workspace_dir.clone();
+ let _reservation = crate::memory::run_slots::reserve(
+ &crate::memory::run_slots::IMPORT,
+ &workspace,
+ &[
+ &crate::memory::run_slots::BACKFILL,
+ &crate::memory::run_slots::MIGRATION,
+ ],
+ )
+ .expect("the test owns a live import slot");
+
+ let mut stale = state::load(&workspace).unwrap();
+ stale.phase = Phase::Copying;
+ state::save(&workspace, &stale).unwrap();
+
+ let migration_status = layout_migration::status(&config).unwrap();
+ assert!(!migration_status.running);
+ assert!(migration_status.interrupted);
+ assert!(
+ !layout_migration::start(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config.clone(),
+ host,
+ Trigger::Auto,
+ Arc::new(|| false),
+ ),
+ "an active import prevents migration from reserving the workspace"
+ );
+ assert!(!layout_migration::ops::is_running(&config));
+}
+
+#[tokio::test]
+async fn a_credit_paused_import_waits_for_billing_and_records_a_resume_failure() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let mut file = ImportFile::default();
+ file.state.phase = ImportPhase::Error;
+ file.paused_for_credits = true;
+ FileCheckpointStore::new(&config.workspace_dir)
+ .save(&file)
+ .unwrap();
+
+ assert!(
+ !resume_interrupted_with(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ Arc::new(|| false),
+ Arc::new(|_: &Config| false),
+ )
+ .await
+ );
+ assert_eq!(read_file(&config.workspace_dir), file);
+
+ assert!(
+ !resume_interrupted_with(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ Arc::new(|| false),
+ Arc::new(|_: &Config| true),
+ )
+ .await,
+ "a permitted resume still reports failure when no engine can be bound"
+ );
+ let stopped = read_file(&config.workspace_dir);
+ assert_eq!(stopped.state.phase, ImportPhase::Error);
- assert!(stopped
- .state
- .error
- .as_deref()
- .unwrap()
- .contains("could not resume"));
++ assert!(
++ stopped
++ .state
++ .error
++ .as_deref()
++ .unwrap()
++ .contains("could not resume")
++ );
+ assert!(!stopped.paused_for_credits);
+ assert!(!is_running(&config.workspace_dir));
+}
+
#[test]
fn a_store_with_no_legacy_files_counts_nothing() {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/memory/layout_migration/app_host.rs
index 646b03326f,765365c1c7..5cda1cac79
--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
@@@ -6,15 -6,14 +6,15 @@@
use async_trait::async_trait;
use tinymemory_api::Error as EngineError;
use tinymemory_tools::layout_migration as lm;
-use tinymemory_tools::layout_migration::{Engines, FlowPlacement, LegacyClaim, Placement};
+use tinymemory_tools::layout_migration::{
+ Engines, FlowPlacement, FsLegacyClaim, LegacyClaim, Placement,
+};
- use super::state::FileStateStore;
-use super::claim::ClaimKey;
+ use super::state::StateKvMigrationStore;
use crate::config::{Config, MemoryLayoutMode};
use crate::memory::engine::{self, CORTEXDB_ENGINE};
-use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::scope::{self, MemoryIdentity};
+use crate::memory::scope;
+use tinymemory_api::{Error, Result};
/// The app's [`lm::LayoutHost`], bound to one account's config.
pub struct AppHost {
diff --cc crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
index 36724271af,bc4006ee83..97504afa6b
--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
@@@ -1,7 -1,7 +1,7 @@@
use std::sync::Arc;
--use tinymemory_api::conformance::ReferenceEngine;
use tinymemory_api::MemoryEngine;
++use tinymemory_api::conformance::ReferenceEngine;
use super::*;
use crate::memory::engine::install_test_engine_for_root;
diff --cc crates/openhuman-core/src/memory/layout_migration/mod.rs
index 6e4ad78f08,a8a2d6896a..ee3927c315
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@@ -8,11 -19,13 +8,12 @@@ pub mod ops
pub mod state;
#[cfg(test)]
-mod test_host;
+pub(crate) mod test_host;
pub use app_host::AppHost;
- pub use ops::{retry, scan, start, status, tick, StartParams};
-pub use service::{retry, scan, start, status, tick, StartParams};
-#[allow(deprecated)]
++pub use ops::{StartParams, retry, scan, start, status, tick};
pub use state::FileStateStore;
+ pub use state::StateKvMigrationStore;
pub use tinymemory_tools::layout_migration::{
LayoutHost, MigrationState, MigrationStateStore, MigrationStatus, Outcome, Phase, ScanView,
Trigger,
diff --cc crates/openhuman-core/src/memory/layout_migration/ops.rs
index 79df46226f,0000000000..f85022dc64
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/layout_migration/ops.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/ops.rs
@@@ -1,109 -1,0 +1,109 @@@
+//! OpenHuman's scheduling and RPC adapter for Native layout migration.
+//!
+//! TinyMemory owns the migration job, policy, live slot and retry behavior.
+//! This module supplies the host executor, workspace key, cross-driver gate,
+//! billing-independent scheduler pause and wire error mapping.
+
+use std::sync::Arc;
+
+use tinymemory_tools::layout_migration as lm;
+use tinymemory_tools::layout_migration::{MigrationSpawner, MigrationTask};
+
- use super::app_host::{from_module, AppHost};
++use super::app_host::{AppHost, from_module};
+use super::{LayoutHost, MigrationState, MigrationStatus, ScanView, Trigger};
+use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
+use crate::memory::run_slots::{self, BACKFILL, MIGRATION};
+use tinymemory_api::Result;
+
+/// `memory_migration_start` params.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+pub struct StartParams {
+ /// The user's consent to take a legacy tree other accounts may share.
+ #[serde(default)]
+ pub takeover: bool,
+}
+
+struct ContextSpawner(DispatchCtx);
+
+impl MigrationSpawner for ContextSpawner {
+ fn spawn(&self, task: MigrationTask) -> std::result::Result<(), String> {
+ if tokio::runtime::Handle::try_current().is_err() {
+ drop(task);
+ return Err("no Tokio runtime is available".to_string());
+ }
+ self.0.spawn(task);
+ Ok(())
+ }
+}
+
+fn service(
+ ctx: &DispatchCtx,
+) -> lm::MigrationService<tinymemory_tools::run_slots::RunStartGate, ContextSpawner> {
+ lm::MigrationService::new(
+ MIGRATION.clone(),
+ run_slots::START_GATE.clone(),
+ ContextSpawner(ctx.clone()),
+ )
+}
+
+/// Whether this workspace currently owns a migration task.
+pub(crate) fn is_running(config: &Config) -> bool {
+ MIGRATION.is_running(&config.workspace_dir)
+}
+
+/// Whether `host`'s account has legacy memory to move.
+pub async fn scan(host: &dyn LayoutHost) -> Result<ScanView> {
+ lm::scan(host).await.map_err(from_module)
+}
+
+/// The migration's progress for `config`'s workspace.
+pub fn status(config: &Config) -> Result<MigrationStatus> {
+ lm::status(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
+}
+
+/// Starts a migration; Native atomically checks peer activity and reserves the
+/// migration-only run slot under the shared start gate.
+pub fn start(
+ ctx: &DispatchCtx,
+ config: Config,
+ host: Arc<dyn LayoutHost>,
+ trigger: Trigger,
+ paused: Arc<dyn Fn() -> bool + Send + Sync>,
+) -> bool {
+ service(ctx).start(
+ config.workspace_dir.clone(),
+ host,
+ || {
+ crate::memory::import::in_progress(&config)
+ || BACKFILL.is_running(&config.workspace_dir)
+ },
+ trigger,
+ move || paused(),
+ )
+}
+
+/// Puts failed migration items back in line.
+pub fn retry(config: &Config) -> Result<MigrationState> {
+ lm::retry(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
+}
+
+/// Memory's background job: starts or resumes an automatic run unless the
+/// migration is done, paused, or already running.
+pub fn tick(
+ ctx: &DispatchCtx,
+ config: &Config,
+ host: Arc<dyn LayoutHost>,
+ paused: Arc<dyn Fn() -> bool + Send + Sync>,
+) -> bool {
+ service(ctx).tick(
+ config.workspace_dir.clone(),
+ host,
+ || crate::memory::import::in_progress(config) || BACKFILL.is_running(&config.workspace_dir),
+ move || paused(),
+ )
+}
+
+#[cfg(test)]
+#[path = "ops_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/memory/layout_migration/ops_tests.rs
index 7d712aaddc,a6ee856d23..16909dcf3e
--- a/crates/openhuman-core/src/memory/layout_migration/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/ops_tests.rs
@@@ -1,11 -1,11 +1,11 @@@
--use std::sync::atomic::Ordering;
use std::sync::Arc;
++use std::sync::atomic::Ordering;
use tinymemory_api::MemoryEngine;
use super::*;
--use crate::memory::layout_migration::test_host::{count, fact, FakeHost};
--use crate::memory::layout_migration::{state, Phase};
++use crate::memory::layout_migration::test_host::{FakeHost, count, fact};
++use crate::memory::layout_migration::{Phase, state};
fn never() -> Arc<dyn Fn() -> bool + Send + Sync> {
Arc::new(|| false)
diff --cc crates/openhuman-core/src/memory/layout_migration/state.rs
index 4c45af42e3,ada4161647..bf1a4fc214
--- a/crates/openhuman-core/src/memory/layout_migration/state.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs
@@@ -6,15 -7,20 +7,20 @@@
use std::path::{Path, PathBuf};
-use tinymemory_tools::layout_migration::{Error, Result};
+use tinymemory_tools::layout_migration::{Error as MigrationError, Result as MigrationResult};
use super::{MigrationState, MigrationStateStore};
-use crate::memory::error::{MemoryError, MemoryResult};
+use tinymemory_api::{Error, Result};
- /// The state file of `workspace_dir`.
+ const STATE: &str = "layout_migration";
+
+ /// Whether a migration state exists in `workspace_dir`: the migration has
+ /// begun there (a state that cannot be read counts: it was begun).
#[must_use]
- pub fn path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("layout_migration.json")
+ pub fn exists(workspace_dir: &Path) -> bool {
+ crate::memory::state_store::load_strict::<serde_json::Value>(workspace_dir, STATE)
+ .map(|state| state.is_some())
+ .unwrap_or(true)
}
/// The migration state kept in one workspace.
@@@ -23,7 -29,11 +29,10 @@@ pub struct StateKvMigrationStore
workspace_dir: PathBuf,
}
- impl FileStateStore {
-/// Backwards-compatible name for [`StateKvMigrationStore`].
-#[deprecated(note = "use StateKvMigrationStore; it persists through the memory state KV port")]
++/// Compatibility name for callers that used the former file adapter.
+ pub type FileStateStore = StateKvMigrationStore;
+
+ impl StateKvMigrationStore {
/// The store of `workspace_dir`.
#[must_use]
pub fn new(workspace_dir: &Path) -> Self {
@@@ -33,13 -43,13 +42,13 @@@
}
}
- impl MigrationStateStore for FileStateStore {
+ impl MigrationStateStore for StateKvMigrationStore {
- fn load(&self) -> Result<MigrationState> {
- load(&self.workspace_dir).map_err(|error| Error::State(detail(error)))
+ fn load(&self) -> MigrationResult<MigrationState> {
+ load(&self.workspace_dir).map_err(|error| MigrationError::State(detail(error)))
}
- fn save(&self, state: &MigrationState) -> Result<()> {
- save(&self.workspace_dir, state).map_err(|error| Error::State(detail(error)))
+ fn save(&self, state: &MigrationState) -> MigrationResult<()> {
+ save(&self.workspace_dir, state).map_err(|error| MigrationError::State(detail(error)))
}
}
@@@ -54,39 -64,26 +63,30 @@@ fn detail(error: Error) -> String
///
/// # Errors
///
-/// A state that cannot be read or parsed: the migration must not start
-/// over and copy everything again on a damaged value.
-pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {
+/// A state file that cannot be read or parsed: the migration must not start
+/// over and copy everything again on a damaged file.
+pub fn load(workspace_dir: &Path) -> Result<MigrationState> {
- let file = path(workspace_dir);
- match std::fs::read(&file) {
- Ok(bytes) => serde_json::from_slice(&bytes)
- .map_err(|error| Error::Engine(format!("layout migration state unreadable: {error}"))),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(MigrationState::default()),
- Err(error) => Err(Error::Engine(format!(
- "layout migration state unreadable: {error}"
- ))),
- }
+ crate::memory::state_store::load_strict(workspace_dir, STATE)
- .map(Option::unwrap_or_default)
- .map_err(|error| {
- MemoryError::Engine(format!("layout migration state unreadable: {error:#}"))
- })
++ .map(|state| state.unwrap_or_default())
++ .map_err(|error| Error::Engine(format!("layout migration state unreadable: {error}")))
}
- /// Saves `state` whole: a temporary file, synced, then renamed over the old.
+ /// Saves `state` whole (one storage write, so a crash leaves the previous
+ /// state or the new one).
///
/// # Errors
///
-/// When the state cannot be written.
-pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {
- crate::memory::state_store::save(workspace_dir, STATE, state).map_err(|error| {
- MemoryError::Engine(format!("layout migration state not saved: {error:#}"))
- })
+/// When the file cannot be written.
+pub fn save(workspace_dir: &Path, state: &MigrationState) -> Result<()> {
- let file = path(workspace_dir);
- let write = || -> std::io::Result<()> {
- if let Some(dir) = file.parent() {
- crate::memory::files::create_private_dir_all(dir)?;
- }
- let temp = file.with_extension("json.tmp");
- let bytes = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;
- let mut out = crate::memory::files::create_private(&temp)?;
- std::io::Write::write_all(&mut out, &bytes)?;
- out.sync_all()?;
- std::fs::rename(&temp, &file)
- };
- write().map_err(|error| Error::Engine(format!("layout migration state not saved: {error}")))
++ crate::memory::state_store::save(workspace_dir, STATE, state)
++ .map_err(|error| Error::Engine(format!("layout migration state not saved: {error}")))
++}
++
++/// Legacy file path used by one-shot state-store import and compatibility
++/// tests.
++#[must_use]
++pub fn path(workspace_dir: &Path) -> PathBuf {
++ crate::memory::state_store::legacy_path(workspace_dir, STATE)
}
#[cfg(test)]
diff --cc crates/openhuman-core/src/memory/layout_migration/test_host.rs
index 763c2e9b4f,69ec1ad01e..4e45ab13a4
--- a/crates/openhuman-core/src/memory/layout_migration/test_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/test_host.rs
@@@ -7,13 -7,13 +7,13 @@@ use tinymemory_api::conformance::Refere
use tinymemory_api::{
LearningKind, ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Namespace, StoreItem,
};
++use tinymemory_tools::MemoryLayout;
use tinymemory_tools::layout_migration::{
- Engines, FlowPlacement, LayoutHost, LegacyClaim, MigrationStateStore, Placement, Result,
+ Engines, FlowPlacement, FsLegacyClaim, LayoutHost, LegacyClaim, MigrationStateStore, Placement,
+ Result,
};
--use tinymemory_tools::MemoryLayout;
- use super::state::FileStateStore;
-use super::claim::ClaimKey;
+ use super::state::StateKvMigrationStore;
use crate::config::Config;
/// Two in-memory engines and the switches a real host keeps, with the real
diff --cc crates/openhuman-core/src/memory/lifecycle/adapter_tests.rs
index d246119df1,0000000000..40121b6824
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/lifecycle/adapter_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/adapter_tests.rs
@@@ -1,173 -1,0 +1,175 @@@
+use super::*;
+
+use tinymemory_api::{Hit, ItemId, ItemKind, MemoryMeta};
+use tinymemory_tools::lifecycle::turn::TurnPack as NativeTurnPack;
+
+#[test]
+fn native_pack_hits_convert_to_the_web_chat_citation_view() {
+ let hit = |id: &str| Hit {
+ id: ItemId(id.to_string()),
+ kind: ItemKind::Learning,
+ text: id.to_string(),
+ meta: MemoryMeta::default(),
+ score: 1.0,
+ confidence: None,
+ };
+ let native = NativeTurnPack {
+ markdown: "shown memory".into(),
+ tokens: 2,
+ refs: vec!["first".into(), "second".into()],
+ engine: "test".into(),
+ citations: vec![hit("first"), hit("second")],
+ refusal: None,
+ };
+
+ let turn_pack = TurnPack::from_native(native);
+ assert_eq!(turn_pack.refs, ["first", "second"]);
+ assert_eq!(
+ turn_pack
+ .citations
+ .iter()
+ .map(|citation| citation.id.as_str())
+ .collect::<Vec<_>>(),
+ ["first", "second"]
+ );
+}
+
+#[tokio::test]
+async fn background_prefetch_records_citations_only_when_returning_the_pack() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = std::sync::Arc::new(config_in(&tmp));
+ let engine = bind_reference(&config);
+ engine
+ .store(StoreItem::learning(
+ "The preferred colour is teal",
+ LearningKind::Preference,
+ 0.9,
+ MemoryMeta::default(),
+ ))
+ .await
+ .unwrap();
+ let identity = tinymemory_tools::layout::identity::Identity::agent("citation-agent")
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let ctx = crate::core::runtime::DispatchCtx::ambient();
+
- assert!(super::super::super::prefetch::pre_turn(
- &ctx,
- config.clone(),
- identity.clone(),
- "citation-thread".into(),
- 0,
- "what colour is preferred?".into(),
- 0,
- Utc::now(),
- false,
- None,
- None,
- )
- .is_none());
++ assert!(
++ super::super::super::prefetch::pre_turn(
++ &ctx,
++ config.clone(),
++ identity.clone(),
++ "citation-thread".into(),
++ 0,
++ "what colour is preferred?".into(),
++ 0,
++ Utc::now(),
++ false,
++ None,
++ None,
++ )
++ .is_none()
++ );
+ assert!(crate::web_chat::citations::take_turn_citations(&ctx, "citation-thread").is_empty());
+
+ super::super::super::prefetch::settle_for_test(
+ &ctx,
+ &config,
+ &identity,
+ "citation-thread",
+ false,
+ )
+ .await;
+ let pack = super::super::super::prefetch::pre_turn(
+ &ctx,
+ config,
+ identity,
+ "citation-thread".into(),
+ 2,
+ "what colour is preferred?".into(),
+ 0,
+ Utc::now(),
+ false,
+ None,
+ None,
+ )
+ .expect("completed prefetch pack");
+ assert!(
+ pack.refusal.is_none(),
+ "a refusal is not a shown citation pack"
+ );
+ assert!(!pack.citations.is_empty(), "the visible pack has citations");
+ let recorded = crate::web_chat::citations::take_turn_citations(&ctx, "citation-thread");
+ assert_eq!(
+ recorded
+ .iter()
+ .map(|citation| citation.id.as_str())
+ .collect::<Vec<_>>(),
+ pack.citations
+ .iter()
+ .map(|citation| citation.id.as_str())
+ .collect::<Vec<_>>()
+ );
+}
+
+#[tokio::test]
+async fn replaying_a_committed_reply_does_not_queue_its_build_twice() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.recall.build_beliefs_every = 2;
+ bind_reference(&config);
+ let identity = tinymemory_tools::layout::identity::Identity::agent("writer")
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let committed = reply("replayed-thread", 1, "The reply is committed.");
+
+ run_post_turn(&config, &identity, committed.clone()).await;
+ let first = crate::memory::lifecycle::jobs::snapshot(&config)
+ .await
+ .pending;
+ assert_eq!(first.len(), 1);
+
+ run_post_turn(&config, &identity, committed).await;
+ assert_eq!(
+ crate::memory::lifecycle::jobs::snapshot(&config)
+ .await
+ .pending,
+ first
+ );
+}
+
+#[test]
+fn memory_turn_keeps_its_core_context_without_owning_the_core() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = std::sync::Arc::new(config_in(&tmp));
+ let identity = tinymemory_tools::layout::identity::Identity::agent("context-agent")
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let core = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(config.workspace_dir.clone()),
+ );
+ let weak = std::sync::Arc::downgrade(&core);
+ let turn = MemoryTurn {
+ config,
+ identity,
+ thread_id: "context-thread".into(),
+ pack: None,
+ in_prompt_from: std::sync::Arc::new(
+ tinymemory_tools::lifecycle::window::InPromptFrom::new(2, 4),
+ ),
+ core: Some(weak.clone()),
+ };
+
+ assert_eq!(turn.in_prompt().from_turn, 2);
+ assert!(std::sync::Arc::ptr_eq(
+ turn.dispatch_ctx().core().unwrap(),
+ &core
+ ));
+ assert_eq!(
+ std::sync::Arc::strong_count(&core),
+ 1,
+ "MemoryTurn stores only a weak core"
+ );
+ drop(core);
+ assert!(
+ weak.upgrade().is_none(),
+ "the turn does not retain the core lease"
+ );
+}
diff --cc crates/openhuman-core/src/memory/lifecycle/hooks.rs
index d901874a38,395266741f..26d383e825
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@@ -1,35 -1,63 +1,35 @@@
-//! The turn-side hooks: pre-turn, post-turn and compaction.
-//!
-//! The agent loop calls these; each is bounded, logs instead of failing, and
-//! returns nothing the turn depends on. See `crates/openhuman-core/src/agent/
-//! session_host/runtime_session.rs` (pre-turn), `memory::bus` (post-turn,
-//! through `ConversationTurnCommitted`) and `agent/tinyagents/
-//! memory_summarizer.rs` (compaction).
-//!
-//! Turn indices follow the committed transcript: the user message of the
-//! turn that follows `n` committed turns is `2n`, its reply `2n + 1`. They
-//! are stable across retries and restarts, which is what lets TinyMemory
-//! recognise a retried turn as a duplicate.
+//! OpenHuman adapters for TinyMemory's runtime-neutral turn hooks.
+use std::sync::{Arc, Weak};
use std::time::Duration;
+use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use futures::future::BoxFuture;
use serde::Serialize;
-use tinymemory_api::{ToolCallRef, Turn};
-use tinymemory_tools::{Compaction, ContextPack, PostTurn, PreTurn, SessionStart};
+use tinymemory_api::{Hit, ObservedActor, ThreadWindow, ToolCallRef, Turn};
+use tinymemory_tools::layout::identity::ResolvedIdentity;
+use tinymemory_tools::lifecycle::turn::{
+ self as native_turn, CitationSink, Clock, EngineResolver, JobsSink, LoggedToolCall,
+ PreTurnOptions, TurnHooks as NativeTurnHooks, TurnPack as NativeTurnPack,
+};
+use tinymemory_tools::{AgentMemory, BackgroundJob, Compaction, PostTurn, PreTurn};
use crate::config::Config;
+use crate::core::runtime::{CoreContext, DispatchCtx};
use crate::memory::engine;
-use crate::memory::error::MemoryError;
-use crate::memory::scope::ResolvedIdentity;
- pub use native_turn::{user_turn_index, CLOSE_TAG, MAX_TOOL_LINE_CHARS, OPEN_TAG};
-use super::{agent_memory_on, jobs, log_only};
++pub use native_turn::{CLOSE_TAG, MAX_TOOL_LINE_CHARS, OPEN_TAG, user_turn_index};
-/// Opening tag of an injected pack.
-pub const OPEN_TAG: &str = "<memory-context>";
-/// Closing tag of an injected pack.
-pub const CLOSE_TAG: &str = "</memory-context>";
-
-/// Longest tool result line appended to a logged reply, in characters.
-const MAX_TOOL_LINE_CHARS: usize = 240;
-
-/// The user message's index for a turn that follows `committed_turns`.
-#[must_use]
-pub fn user_turn_index(committed_turns: usize) -> u32 {
- u32::try_from(committed_turns.saturating_mul(2)).unwrap_or(u32::MAX - 1)
-}
-
-/// The context a turn is given: one rendered pack and what it cites.
+/// A native turn pack with the citation view used by OpenHuman's chat UI.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TurnPack {
- /// The block, rendered by TinyMemory; never empty.
- pub markdown: String,
- /// Its estimated tokens.
- pub tokens: usize,
- /// The ids of every item it cites, in order.
- pub refs: Vec<String>,
- /// The engine that answered.
- pub engine: String,
- /// The cited items, for the chat's memory chips.
+ /// TinyMemory's authoritative pack and refusal state.
+ #[serde(flatten)]
+ pub native: NativeTurnPack,
+ /// The citation view attached to the chat reply, not serialized with the pack.
#[serde(skip)]
- pub citations: Vec<crate::memory::types::TurnCitation>,
- /// Set when nothing was recalled because the engine refused the whole
- /// account (a `MemoryError` code such as `INSUFFICIENT_CREDITS`): the
- /// block is then a notice saying so, not recalled memory.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub refusal: Option<&'static str>,
+ pub citations: Vec<crate::web_chat::TurnCitation>,
}
impl TurnPack {
diff --cc crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs
index ccc320b2d2,4e40311d05..2fa57e628b
--- a/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs
@@@ -179,16 -121,15 +179,18 @@@ async fn recall_off_still_logs_and_logg
.unwrap();
config.memory.recall.enabled = false;
- let quiet = MemoryIdentity::agent("a").resolve(&config);
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &quiet,
- input("t", 0, "when do deploys happen?")
- )
- .await
- .is_none());
+ let quiet = tinymemory_tools::layout::identity::Identity::agent("a")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &quiet,
- input("t", 0, "when do deploys happen?")
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &quiet,
++ input("t", 0, "when do deploys happen?")
++ )
++ .await
++ .is_none()
++ );
assert_eq!(
stored(&engine, MetaFilter::kinds([ItemKind::Conversation]))
.await
@@@ -217,33 -157,31 +219,37 @@@
);
config.memory.recall.enabled = false;
- let none = MemoryIdentity::agent("a").resolve(&config);
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &none,
- input("t", 4, "hi")
- )
- .await
- .is_none());
+ let none = tinymemory_tools::layout::identity::Identity::agent("a")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &none,
- input("t", 4, "hi")
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &none,
++ input("t", 4, "hi")
++ )
++ .await
++ .is_none()
++ );
}
#[tokio::test]
async fn pre_turn_without_an_engine_runs_the_turn_without_a_pack() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
- let identity = MemoryIdentity::agent("a").resolve(&config);
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &identity,
- input("t", 0, "hello")
- )
- .await
- .is_none());
- post_turn(&config, &identity, reply("t", 1, "hi")).await;
+ let identity = tinymemory_tools::layout::identity::Identity::agent("a")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &identity,
- input("t", 0, "hello")
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &identity,
++ input("t", 0, "hello")
++ )
++ .await
++ .is_none()
++ );
+ run_post_turn(&config, &identity, reply("t", 1, "hi")).await;
}
#[tokio::test]
@@@ -304,24 -240,11 +310,26 @@@ async fn compaction_recalls_from_the_dr
Turn::new(Role::User, "the project codename is Heron"),
Turn::new(Role::Assistant, "Noted: Heron."),
];
- let pack = compaction(&config, &identity, "t", dropped).await;
+ let pack = compaction_work(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ &config,
+ &identity,
+ "t",
+ dropped,
+ )
+ .await;
assert!(pack.expect("a pack").markdown.contains("Heron"));
- assert!(compaction_work(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &identity,
- "t",
- Vec::new()
- )
- .await
- .is_none());
- assert!(compaction(&config, &identity, "t", Vec::new())
++ assert!(
++ compaction_work(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &identity,
++ "t",
++ Vec::new()
++ )
+ .await
- .is_none());
++ .is_none()
++ );
}
#[tokio::test]
@@@ -388,17 -312,49 +396,19 @@@ async fn an_engine_fault_that_is_not_ac
"index corrupt".into(),
))
.bind(&config);
- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);
+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- assert!(pre_turn(
-- &crate::core::runtime::DispatchCtx::ambient(),
-- &config,
-- &identity,
-- input("t", 0, "hello")
-- )
-- .await
-- .is_none());
-}
-
-#[test]
-fn a_refusal_is_read_back_from_a_skipped_section() {
- let outcomes = vec![Ok(ContextPack {
- markdown: String::new(),
- tokens: 0,
- refs: Vec::new(),
- sections: Vec::new(),
- skipped: vec![
- tinymemory_tools::recall::SkippedSection {
- heading: "Learnings".into(),
- reason: "empty".into(),
- },
- tinymemory_tools::recall::SkippedSection {
- heading: "History".into(),
- reason: "unauthorized: [UNAUTHORIZED] memory API fetch (HTTP 401)".into(),
- },
- ],
- engine: "tinyhumans".into(),
- })];
- let refusal = refusal_of(&outcomes).expect("refusal");
- assert_eq!(refusal.code(), crate::memory::error::UNAUTHORIZED);
-
- let quiet = vec![Ok(ContextPack {
- markdown: String::new(),
- tokens: 0,
- refs: Vec::new(),
- sections: Vec::new(),
- skipped: Vec::new(),
- engine: "tinyhumans".into(),
- })];
- assert!(refusal_of(&quiet).is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &identity,
++ input("t", 0, "hello")
++ )
++ .await
++ .is_none()
++ );
}
// ── the pack's token budget against a large store (#6718, #7023) ────────────
@@@ -594,16 -546,15 +604,18 @@@ async fn a_blank_turn_is_refused_withou
let tmp = tempfile::tempdir().unwrap();
let mut config = config_in(&tmp);
let engine = bind_reference(&config);
- let identity = MemoryIdentity::agent("orchestrator").resolve(&config);
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &identity,
- input("t-blank", 0, " ")
- )
- .await
- .is_none());
+ let identity = tinymemory_tools::layout::identity::Identity::agent("orchestrator")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &identity,
- input("t-blank", 0, " ")
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &identity,
++ input("t-blank", 0, " ")
++ )
++ .await
++ .is_none()
++ );
assert!(
stored(&engine, MetaFilter::kinds([ItemKind::Conversation]))
.await
@@@ -612,26 -563,25 +624,30 @@@
);
config.memory.conversations.enabled = false;
- let reader = MemoryIdentity::agent("orchestrator").resolve(&config);
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &reader,
- input("t-blank", 2, " ")
- )
- .await
- .is_none());
+ let reader = tinymemory_tools::layout::identity::Identity::agent("orchestrator")
+ .resolve(&crate::memory::scope::identity_pins(&config));
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &reader,
- input("t-blank", 2, " ")
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &reader,
++ input("t-blank", 2, " ")
++ )
++ .await
++ .is_none()
++ );
let mut resumed = input(" ", 4, "where were we?");
- resumed.resumed_after_compaction = true;
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &reader,
- resumed
- )
- .await
- .is_none());
+ resumed.5 = true;
- assert!(run_pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- &config,
- &reader,
- resumed
- )
- .await
- .is_none());
++ assert!(
++ run_pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &reader,
++ resumed
++ )
++ .await
++ .is_none()
++ );
}
/// With `date_hint` on, the turn's text goes to the chat model with the date
diff --cc crates/openhuman-core/src/memory/lifecycle/jobs.rs
index 6cf8f903a2,69288a4853..7cb576b932
--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
@@@ -1,8 -1,8 +1,8 @@@
//! The background job queue: the slow memory work TinyMemory hands back.
//!
//! The queue itself (dedupe, retry, history) is `tinymemory_tools::queue`;
--//! this module is the host adapter: one queue per workspace over a file
- //! store (`<workspace>/memory/jobs.json`), the engine and `[memory.recall]
-//! store (the `memory`/`state`/`jobs` storage value), the engine and `[memory.recall]
++//! this module is the host adapter: one queue per workspace over the
++//! `memory`/`state`/`jobs` storage value, the engine and `[memory.recall]
//! build_delay_secs` it runs against, and the `memory_background` cron hook.
//!
//! `post_turn` and brain ingests return `BackgroundJob` values (belief builds,
@@@ -19,13 -19,13 +19,13 @@@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
use tinymemory_api::Namespace;
--use tinymemory_tools::queue::{JobQueue as Queue, QueueError, QueueState, QueueStore};
use tinymemory_tools::BackgroundJob;
++use tinymemory_tools::queue::{JobQueue as Queue, QueueError, QueueState, QueueStore};
-pub use tinymemory_tools::queue::{JobRun, QueuedJob, Selection, MAX_ATTEMPTS, MAX_HISTORY};
+use tinymemory_tools::queue::{JobRun, Selection};
use crate::config::Config;
use crate::memory::engine;
@@@ -37,39 -37,29 +37,53 @@@ pub const BACKGROUND_JOB: &str = "memor
/// Minutes between queue runs.
pub const BACKGROUND_INTERVAL_MINS: u64 = 5;
+ /// The persisted queue as the UI reads it.
+ pub type JobQueue = QueueState;
+
+ const STATE: &str = "jobs";
+
++fn quarantine_corrupt_legacy_file(workspace_dir: &Path) {
++ let legacy = path(workspace_dir);
++ let Ok(bytes) = std::fs::read(&legacy) else {
++ return;
++ };
++ if serde_json::from_slice::<QueueState>(&bytes).is_ok() {
++ return;
++ }
++ if let Err(error) = std::fs::rename(&legacy, legacy.with_extension("json.corrupt")) {
++ tracing::warn!(%error, "[memory:jobs] could not set queue file aside");
++ }
++}
++
+/// The queue file of a workspace.
+fn path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("jobs.json")
++ super::super::state_store::legacy_path(workspace_dir, STATE)
+}
+
- /// A [`QueueStore`] over `<workspace>/memory/jobs.json`.
+ /// A [`QueueStore`] over the workspace's `jobs` state value.
struct FileQueueStore {
- file: PathBuf,
+ workspace_dir: PathBuf,
}
impl QueueStore for FileQueueStore {
fn load(&self) -> QueueState {
- let Ok(text) = std::fs::read_to_string(&self.file) else {
- return QueueState::default();
- };
- serde_json::from_str(&text).unwrap_or_else(|error| {
- tracing::warn!(%error, "[memory:jobs] queue unparsable; set aside");
- if let Err(error) =
- std::fs::rename(&self.file, self.file.with_extension("json.corrupt"))
- {
- tracing::warn!(%error, "[memory:jobs] could not set queue file aside");
- crate::memory::state_store::load(&self.workspace_dir, STATE)
- .unwrap_or_else(|error| {
++ match super::super::state_store::load(&self.workspace_dir, STATE) {
++ Ok(Some(queue)) => queue,
++ Ok(None) => {
++ quarantine_corrupt_legacy_file(&self.workspace_dir);
++ QueueState::default()
++ }
++ Err(error) => {
+ tracing::warn!(%error, "[memory:jobs] reading the queue failed");
- None
- })
- .unwrap_or_default()
++ quarantine_corrupt_legacy_file(&self.workspace_dir);
++ QueueState::default()
+ }
- QueueState::default()
- })
++ }
}
- fn save(&self, state: &QueueState) -> Result<(), String> {
- crate::memory::state_store::save(&self.workspace_dir, STATE, state)
+ fn save(&self, state: &QueueState) -> std::result::Result<(), String> {
- serde_json::to_vec_pretty(state)
++ super::super::state_store::save(&self.workspace_dir, STATE, state)
.map_err(|error| error.to_string())
- .and_then(|json| {
- crate::security::secret_storage::file_store::write_atomic(&self.file, &json)
- .map_err(|error| error.to_string())
- })
}
}
@@@ -81,15 -71,14 +95,15 @@@ static QUEUES: LazyLock<Mutex<HashMap<P
fn queue_of(workspace_dir: &Path) -> Arc<WorkspaceQueue> {
let mut queues = QUEUES.lock().unwrap_or_else(|e| e.into_inner());
- queues
- .entry(workspace_dir.to_path_buf())
- .or_insert_with(|| {
- Arc::new(Queue::new(FileQueueStore {
- workspace_dir: workspace_dir.to_path_buf(),
- }))
- })
- .clone()
+ queues.retain(|_, queue| queue.strong_count() > 0);
+ if let Some(queue) = queues.get(workspace_dir).and_then(Weak::upgrade) {
+ return queue;
+ }
+ let queue = Arc::new(Queue::new(FileQueueStore {
- file: path(workspace_dir),
++ workspace_dir: workspace_dir.to_path_buf(),
+ }));
+ queues.insert(workspace_dir.to_path_buf(), Arc::downgrade(&queue));
+ queue
}
/// Queues `jobs` under `root`; a job already queued is kept once, at its
diff --cc crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
index 749431e52a,29d31f175d..dcadd7952d
--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
@@@ -1,33 -1,9 +1,35 @@@
use super::*;
- use tinymemory_tools::queue::QueueState;
+use tinymemory_tools::queue::MAX_ATTEMPTS;
++use tinymemory_tools::queue::QueueState;
use tinymemory_api::{ConsolidateRequest, ItemKind, Reach};
use crate::memory::test_fixtures::{bind_reference, config_in};
+#[test]
+fn workspace_queues_are_released_after_the_last_holder_drops() {
+ let temp = tempfile::tempdir().unwrap();
+ let workspaces = (0..32)
+ .map(|index| temp.path().join(index.to_string()))
+ .collect::<Vec<_>>();
+ let queues = workspaces
+ .iter()
+ .map(|workspace| queue_of(workspace))
+ .collect::<Vec<_>>();
+
+ drop(queues);
+
+ let sentinel = temp.path().join("sentinel");
+ drop(queue_of(&sentinel));
+
+ let queues = QUEUES.lock().unwrap();
- assert!(workspaces
- .iter()
- .all(|workspace| !queues.contains_key(workspace)));
++ assert!(
++ workspaces
++ .iter()
++ .all(|workspace| !queues.contains_key(workspace))
++ );
+}
+
fn build(agent: &str) -> BackgroundJob {
BackgroundJob::BuildBeliefs {
request: ConsolidateRequest::new(Reach::exact(Namespace::agent(agent)))
@@@ -35,25 -11,6 +37,27 @@@
}
}
+#[test]
+fn corrupt_job_queue_file_is_set_aside() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = path(tmp.path());
+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();
+ std::fs::write(&file, b"{\"pending\":[").unwrap();
- let store = FileQueueStore { file: file.clone() };
++ let store = FileQueueStore {
++ workspace_dir: tmp.path().to_path_buf(),
++ };
+
+ assert_eq!(store.load(), QueueState::default());
+ assert!(
+ !file.exists(),
+ "corrupt queue must not be silently replaced"
+ );
+ assert_eq!(
+ std::fs::read(file.with_extension("json.corrupt")).unwrap(),
+ b"{\"pending\":["
+ );
+}
+
#[tokio::test]
async fn duplicates_merge_and_the_queue_survives_a_reload() {
let tmp = tempfile::tempdir().unwrap();
@@@ -134,17 -95,21 +142,21 @@@ async fn a_run_needs_an_engine()
}
#[tokio::test]
--async fn the_build_delay_comes_from_the_recall_config_and_the_file_store_is_the_workspaces() {
++async fn the_build_delay_comes_from_recall_config_and_the_queue_uses_the_state_store() {
let tmp = tempfile::tempdir().unwrap();
let mut config = config_in(&tmp);
bind_reference(&config);
config.memory.recall.build_delay_secs = 3600;
enqueue(&config, &Namespace::ROOT, vec![build("a")]).await;
assert!(has_pending(&config.workspace_dir));
- let on_disk: QueueState =
- serde_json::from_str(&std::fs::read_to_string(path(&config.workspace_dir)).unwrap())
- .unwrap();
- assert_eq!(on_disk.pending.len(), 1, "persisted in memory/jobs.json");
- let stored: JobQueue = crate::memory::state_store::load(&config.workspace_dir, "jobs")
++ let stored: QueueState = crate::memory::state_store::load(&config.workspace_dir, "jobs")
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ stored.pending.len(),
+ 1,
- "persisted in the memory state store"
++ "persisted through the state KV port"
+ );
assert!(run(&config, Selection::Due).await.unwrap().is_empty());
}
diff --cc crates/openhuman-core/src/memory/lifecycle/mod.rs
index ea89630045,5dc8ea5e2c..09d996729f
--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs
@@@ -27,12 -29,12 +27,12 @@@ use std::sync::Arc
use tinymemory_api::MemoryEngine;
use tinymemory_tools::{AgentMemory, RecallPolicy};
- use crate::config::schema::RecallSettings;
-use crate::config::schema::MemoryRecallConfig;
use crate::config::Config;
++use crate::config::schema::RecallSettings;
use super::engine;
-use super::error::{MemoryError, MemoryResult};
-use super::scope::ResolvedIdentity;
+use tinymemory_api::{Error, Result};
+use tinymemory_tools::layout::identity::ResolvedIdentity;
/// TinyMemory's recall policy from `[memory.recall]`.
#[must_use]
diff --cc crates/openhuman-core/src/memory/lifecycle/prefetch.rs
index bf30cf4f08,c56e32a717..0b8ee7546d
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
@@@ -8,18 -8,17 +8,18 @@@ use std::sync::{Arc, LazyLock}
use std::time::Duration;
use futures::future::BoxFuture;
-use tinymemory_tools::prefetch::{Limits, PrefetchRuntime, Prefetcher, WorkerPool};
+use tinymemory_tools::prefetch::{
+ Limits, PrefetchRuntime, TurnCache, TurnCacheRegistry, WorkerPool,
+};
use crate::config::Config;
--use crate::core::runtime::{slot_for, DispatchCtx};
-use crate::memory::scope::ResolvedIdentity;
++use crate::core::runtime::{DispatchCtx, slot_for};
+use tinymemory_tools::layout::identity::ResolvedIdentity;
-use super::hooks::{self, PreTurnInput, TurnPack};
+use super::hooks::{self, TurnPack};
-const MAX_PACK_BYTES: usize = 64 * 1024;
static WORKERS: LazyLock<WorkerPool> = LazyLock::new(|| WorkerPool::new(8));
-static CACHES: LazyLock<Mutex<Vec<Weak<Cache>>>> = LazyLock::new(Mutex::default);
+static CACHES: LazyLock<TurnCacheRegistry<Key>> = LazyLock::new(TurnCacheRegistry::default);
type Work = BoxFuture<'static, Option<TurnPack>>;
diff --cc crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
index a79d9e0da3,bcc229201d..ec56f462be
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
@@@ -111,76 -89,6 +111,78 @@@ async fn identity_config_thread_workspa
assert!(completed(&Cache::default(), &key).is_none());
}
+#[tokio::test]
+async fn pre_turn_logs_channel_metadata_without_writing_legacy_thread_map() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = Arc::new(config_in(&tmp));
+ let engine = bind_reference(&config);
+ let identity = tinymemory_tools::layout::identity::Identity::agent("channel-agent")
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let thread_id = "telegram-thread";
+ let key = Key::new(&config, &identity, thread_id, false);
+ let cache = cache(&crate::core::runtime::DispatchCtx::ambient());
+
- assert!(pre_turn(
- &crate::core::runtime::DispatchCtx::ambient(),
- config.clone(),
- identity,
- thread_id.into(),
- 0,
- "hello from telegram".into(),
- 0,
- chrono::Utc::now(),
- false,
- None,
- Some("telegram".into()),
- )
- .is_none());
++ assert!(
++ pre_turn(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ config.clone(),
++ identity,
++ thread_id.into(),
++ 0,
++ "hello from telegram".into(),
++ 0,
++ chrono::Utc::now(),
++ false,
++ None,
++ Some("telegram".into()),
++ )
++ .is_none()
++ );
+ drain(&cache, &key).await;
+
+ let turns = stored(
+ &engine,
+ tinymemory_api::MetaFilter::kinds([tinymemory_api::ItemKind::Conversation]),
+ )
+ .await;
+ assert_eq!(turns.len(), 1);
+ assert_eq!(turns[0].meta.channel.as_deref(), Some("telegram"));
+ assert!(
+ !config
+ .workspace_dir
+ .join("memory")
+ .join("channel_threads.json")
+ .exists(),
+ "new turns must not write the legacy channel/thread map"
+ );
+}
+
+#[test]
+fn prefetch_key_tracks_memory_config_without_hashing_unrelated_config() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = tinymemory_tools::layout::identity::Identity::agent("a")
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let key = Key::new(&config, &identity, "t", false);
+
+ let mut memory_changed = config.clone();
+ memory_changed.memory.recall.brain_limit += 1;
+ assert!(key != Key::new(&memory_changed, &identity, "t", false));
+
+ let mut engine_changed = config.clone();
+ engine_changed.api_url = Some("https://memory.example.test".into());
+ assert!(key != Key::new(&engine_changed, &identity, "t", false));
+
+ let mut inference_changed = config.clone();
+ inference_changed.inference_url = Some("https://inference.example.test".into());
+ assert!(key != Key::new(&inference_changed, &identity, "t", false));
+
+ let mut unrelated_changed = config;
+ unrelated_changed.context.enabled = false;
+ assert!(key == Key::new(&unrelated_changed, &identity, "t", false));
+}
+
#[tokio::test]
async fn invalidation_rejects_late_results_and_preserves_bounded_pending_logs() {
let _guard = TEST_LOCK.lock().await;
diff --cc crates/openhuman-core/src/memory/lifecycle/sender.rs
index 9fdeabd286,d68dd87875..60d64bde3d
--- a/crates/openhuman-core/src/memory/lifecycle/sender.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/sender.rs
@@@ -3,10 -22,15 +3,10 @@@
use tinymemory_api::ObservedActor;
- use crate::agent::turn_origin::AgentTurnOrigin;
+ use crate::security::turn_origin::AgentTurnOrigin;
-/// Channels whose senders are phone numbers (or, for iMessage, email
-/// addresses).
-const PHONE_CHANNELS: &[&str] = &["whatsapp", "signal", "imessage", "linq", "sms"];
-
-/// The actor a channel turn is observed from, or `None` for any other
-/// origin, a channel turn without a sender, or a cron run (which replays its
-/// creator's channel origin around the job's own prompt, `cron/origin.rs`).
+/// The sender observed in an external-channel user turn, or `None` for any
+/// other origin, a missing sender, or a cron replay.
#[must_use]
pub fn channel_actor(origin: &AgentTurnOrigin) -> Option<ObservedActor> {
let AgentTurnOrigin::ExternalChannel {
diff --cc crates/openhuman-core/src/memory/lifecycle/views_tests.rs
index 4a065cb193,5563d2b2c3..e788f4e227
--- a/crates/openhuman-core/src/memory/lifecycle/views_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/views_tests.rs
@@@ -251,18 -129,18 +251,22 @@@ async fn jobs_run_needs_an_engine_and_n
let config = config_in(&tmp);
assert!(jobs_run(&config, JobsRunParams::default()).await.is_err());
bind_reference(&config);
-- assert!(jobs_run(&config, JobsRunParams::default())
++ assert!(
++ jobs_run(&config, JobsRunParams::default())
++ .await
++ .unwrap()
++ .runs
++ .is_empty()
++ );
++ assert!(
++ jobs_run(
++ &config,
++ JobsRunParams {
++ id: Some("x".into())
++ }
++ )
.await
-- .unwrap()
-- .runs
-- .is_empty());
-- assert!(jobs_run(
-- &config,
-- JobsRunParams {
-- id: Some("x".into())
-- }
-- )
-- .await
-- .is_err());
++ .is_err()
++ );
assert!(jobs_list(&config).await.pending.is_empty());
}
diff --cc crates/openhuman-core/src/memory/local_root.rs
index fa192c5493,77c41758db..082ec88b27
--- a/crates/openhuman-core/src/memory/local_root.rs
+++ b/crates/openhuman-core/src/memory/local_root.rs
@@@ -137,17 -141,11 +141,11 @@@ pub fn legacy_root(user_id: &str) -> St
/// layout migration (which copies into the user root) has started or
/// finished.
fn has_memory_under_legacy_root(config: &Config) -> bool {
- super::scope::layout_is_v3(config)
+ config.memory.layout == crate::config::MemoryLayoutMode::V3
- || super::layout_migration::state::path(&config.workspace_dir).exists()
+ || super::layout_migration::state::exists(&config.workspace_dir)
}
- fn read(file: &Path) -> std::io::Result<Option<LocalRoot>> {
- let text = match std::fs::read_to_string(file) {
- Ok(text) => text,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(error),
- };
- let record: LocalRoot = serde_json::from_str(&text).map_err(std::io::Error::other)?;
+ fn valid(record: &LocalRoot) -> std::io::Result<()> {
let id = record.root.strip_prefix(LOCAL_ROOT_PREFIX).unwrap_or("");
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_alphanumeric()) {
return Err(std::io::Error::other(
diff --cc crates/openhuman-core/src/memory/mod.rs
index d387b25db7,8603b6a0d9..fc8e1fbfe3
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@@ -22,14 -23,15 +22,14 @@@ pub mod backfill
pub mod billing;
pub mod brain;
pub mod bus;
-pub mod channels;
-pub mod confine;
-pub(crate) mod convert;
pub mod deletion;
pub mod engine;
+ pub mod engine_registry;
pub mod error;
pub mod explore;
- pub(crate) mod files;
-pub mod guard;
+#[cfg(test)]
+#[path = "guard_tests.rs"]
+mod guard;
pub mod import;
pub mod layout_migration;
pub mod lifecycle;
@@@ -39,7 -40,9 +39,8 @@@ pub(crate) mod run_slots
pub mod schemas;
pub mod scope;
pub mod sources;
+ pub(crate) mod state_store;
pub mod status;
-mod tool_budget;
pub(crate) mod tool_writes;
pub mod tools;
pub mod types;
@@@ -57,4 -58,7 +58,4 @@@ pub use schemas::
all_controller_schemas as all_memory_controller_schemas,
all_registered_controllers as all_memory_registered_controllers,
};
--pub use tools::{MemoryTool, MEMORY_TOOL_NAME};
-
-/// Host-specific connector prefix configuration for memory provenance.
-pub mod provenance;
++pub use tools::{MEMORY_TOOL_NAME, MemoryTool};
diff --cc crates/openhuman-core/src/memory/ops.rs
index 1843f68628,872cd1f678..04d36391ae
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@@ -165,15 -130,11 +165,15 @@@ pub fn apply_engine_set(config: &mut Co
}
CORTEXDB_ENGINE => engine::store_cortexdb_key(config, key)?,
TINYHUMANS_ENGINE => {
- return Err(MemoryError::invalid(
- "the tinyhumans engine uses your sign-in, not an API key",
- ))
+ return Err(Error::InvalidRequest(
+ ("the tinyhumans engine uses your sign-in, not an API key").into(),
- ))
++ ));
+ }
+ _ => {
+ return Err(Error::InvalidRequest(
+ ("this engine takes no API key").into(),
- ))
++ ));
}
- _ => return Err(MemoryError::invalid("this engine takes no API key")),
}
}
config.memory.engine = engine_id.to_string();
diff --cc crates/openhuman-core/src/memory/ops_compat_tests.rs
index 722092347f,0000000000..1245e43504
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/ops_compat_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_compat_tests.rs
@@@ -1,123 -1,0 +1,127 @@@
+use super::*;
+
+#[tokio::test]
+async fn forget_with_no_id_is_invalid_even_when_memory_is_off() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let error = forget(
+ &config,
+ ForgetParams {
+ ids: vec![" ".into()],
+ reach: None,
+ },
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.code(), "INVALID_REQUEST");
+}
+
+#[tokio::test]
+async fn single_user_reads_writes_and_forgets_ancestor_and_service_memory() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let ancestor_id = store_item(
+ &config,
+ StoreItem::learning(
+ "shared ancestor memory",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta::default(),
+ ),
+ )
+ .await
+ .unwrap()
+ .id
+ .0;
+ let service_namespace: tinymemory_api::Namespace =
+ "ws:main/service:newsletter".parse().unwrap();
+ let service_id = store_item(
+ &config,
+ StoreItem::learning(
+ "service private memory",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: service_namespace.clone(),
+ ..MemoryMeta::default()
+ },
+ ),
+ )
+ .await
+ .unwrap()
+ .id
+ .0;
+
+ let inherited = items_list(
+ &config,
+ ItemsListParams {
+ filter: Some(MetaFilter {
+ reach: Some(tinymemory_api::Reach::of(
+ "ws:main/agent:writer".parse().unwrap(),
+ )),
+ ..MetaFilter::default()
+ }),
+ ..ItemsListParams::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(inherited.items.iter().any(|item| item.id.0 == ancestor_id));
+
+ let service_reader = items_list(
+ &config,
+ ItemsListParams {
+ filter: Some(MetaFilter {
+ reach: Some(tinymemory_api::Reach::of(
+ "ws:main/service:newsletter/agent:writer".parse().unwrap(),
+ )),
+ ..MetaFilter::default()
+ }),
+ ..ItemsListParams::default()
+ },
+ )
+ .await
+ .unwrap();
- assert!(service_reader
- .items
- .iter()
- .any(|item| item.id.0 == service_id));
++ assert!(
++ service_reader
++ .items
++ .iter()
++ .any(|item| item.id.0 == service_id)
++ );
+ let service_item = stored(
+ &engine,
+ MetaFilter {
+ reach: Some(tinymemory_api::Reach::exact(service_namespace.clone())),
+ ..MetaFilter::default()
+ },
+ )
+ .await
+ .into_iter()
+ .find(|item| item.id.0 == service_id)
+ .expect("the explicit service reach reads the stored item");
+ assert_eq!(service_item.meta.namespace, service_namespace);
+
+ let forgotten = forget(
+ &config,
+ ForgetParams {
+ ids: vec![service_id.clone()],
+ reach: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(forgotten.forgotten, 1);
- assert!(stored(
- &engine,
- MetaFilter {
- reach: Some(tinymemory_api::Reach::exact(service_item.meta.namespace)),
- ..MetaFilter::default()
- },
- )
- .await
- .iter()
- .all(|item| item.id.0 != service_id));
++ assert!(
++ stored(
++ &engine,
++ MetaFilter {
++ reach: Some(tinymemory_api::Reach::exact(service_item.meta.namespace)),
++ ..MetaFilter::default()
++ },
++ )
++ .await
++ .iter()
++ .all(|item| item.id.0 != service_id)
++ );
+}
diff --cc crates/openhuman-core/src/memory/ops_saas_tests.rs
index ec938c90e8,0000000000..3a2739cc53
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/ops_saas_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_saas_tests.rs
@@@ -1,478 -1,0 +1,480 @@@
+use super::*;
+use crate::memory::test_fixtures::{bind_reference, config_in};
+use std::sync::{
- atomic::{AtomicUsize, Ordering},
+ Arc,
++ atomic::{AtomicUsize, Ordering},
+};
+use tinymemory_api::conformance::ReferenceEngine;
+use tinymemory_api::{
+ DocumentBody, EngineDescriptor, FetchRequest, ForgetReport, ForgetTarget, ItemKind,
+ ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Reach, RecallRequest, Role, SourceKind,
+ SourceRef, StoreItem, StoreReceipt, Turn,
+};
+
+fn learn_params(text: &str) -> LearnParams {
+ LearnParams {
+ text: text.to_string(),
+ kind: None,
+ confidence: None,
+ meta: None,
+ }
+}
+
+#[test]
+fn invalid_saas_root_is_refused_before_engine_operations() {
+ const CHILD: &str = "OPENHUMAN_TEST_SAAS_MEMORY_STORE_GUARD";
+ const TEST_NAME: &str =
+ "memory::ops::saas_tests::invalid_saas_root_is_refused_before_engine_operations";
+
+ if std::env::var_os(CHILD).is_none() {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", TEST_NAME, "--nocapture"])
+ .env(CHILD, "1")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success()
+ && String::from_utf8_lossy(&output.stdout)
+ .contains("SAAS_MEMORY_STORE_GUARD_CHILD_PASSED"),
+ "isolated SaaS test process failed or ran zero tests:\n{}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+
+ crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ for root in [None, Some("not a namespace!"), Some("root")] {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = root.map(str::to_string);
+ let calls = Arc::new(AtomicUsize::new(0));
+ crate::memory::engine::install_test_engine(
+ &config.workspace_dir,
+ Arc::new(CountingEngine {
+ inner: ReferenceEngine::new(),
+ calls: calls.clone(),
+ }),
+ );
+ let expected = "memory is unavailable: this agent has no valid memory root";
+ let check = |error: Error| {
+ assert!(matches!(error, Error::InvalidRequest(message) if message == expected));
+ };
+ let item = StoreItem::learning(
+ "should not be stored",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta::default(),
+ );
+ check(runtime.block_on(store_item(&config, item)).unwrap_err());
+ check(
+ runtime
+ .block_on(recall(
+ &config,
+ RecallParams {
+ refers_to: None,
+ question: "anything".into(),
+ filter: None,
+ limit: None,
+ },
+ ))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(fetch(
+ &config,
+ FetchParams {
+ refers_to: None,
+ query: "anything".into(),
+ mode: None,
+ filter: None,
+ limit: None,
+ cursor: None,
+ },
+ ))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(items_list(&config, ItemsListParams::default()))
+ .unwrap_err(),
+ );
+ check(
+ runtime
+ .block_on(forget(
+ &config,
+ ForgetParams {
+ ids: vec!["not-present".into()],
+ reach: None,
+ },
+ ))
+ .unwrap_err(),
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 0, "root: {root:?}");
+ }
+ println!("SAAS_MEMORY_STORE_GUARD_CHILD_PASSED");
+}
+
+#[test]
+fn valid_saas_identity_clamps_memory_operations_in_an_isolated_process() {
+ const CHILD: &str = "OPENHUMAN_TEST_SAAS_MEMORY_CLAMP";
+ const TEST_NAME: &str = "memory::ops::saas_tests::valid_saas_identity_clamps_memory_operations_in_an_isolated_process";
+
+ if std::env::var_os(CHILD).is_none() {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", TEST_NAME, "--nocapture"])
+ .env(CHILD, "1")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success()
+ && String::from_utf8_lossy(&output.stdout)
+ .contains("SAAS_MEMORY_CLAMP_CHILD_PASSED"),
+ "isolated SaaS clamp test process failed or ran zero tests:\n{}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+
+ crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = Some("team:acme".into());
+ let engine = bind_reference(&config);
+ let own = engine
+ .store(StoreItem::learning(
+ "acme shared note",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: "team:acme".parse().unwrap(),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap()
+ .id
+ .0;
+ let foreign = engine
+ .store(StoreItem::learning(
+ "other team's private marker",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: "team:other".parse().unwrap(),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap()
+ .id
+ .0;
+
+ for (namespace, text, repo) in [
+ ("team:acme", "explore acme item", "org/alpha"),
+ ("team:acme", "explore acme sibling", "org/beta"),
+ ("team:other", "explore foreign item", "org/foreign"),
+ ] {
+ engine
+ .store(StoreItem::learning(
+ text,
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: namespace.parse().unwrap(),
+ repo: Some(repo.into()),
+ tags: vec!["selected".into()],
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+ }
+ engine
+ .store(StoreItem::document(
+ "selected document",
+ MemoryMeta {
+ namespace: "team:acme".parse().unwrap(),
+ repo: Some("org/document".into()),
+ tags: vec!["selected".into()],
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+
+ let explore_params = |scan_limit| crate::memory::explore::ExploreParams {
+ facet: tinymemory_api::Facet::Repo,
+ path: vec![crate::memory::explore::PathStep {
+ facet: tinymemory_api::Facet::Kind,
+ value: "learning".into(),
+ }],
+ filter: Some(MetaFilter {
+ tags_any: vec!["selected".into()],
+ ..MetaFilter::default()
+ }),
+ limit: Some(5),
+ scan_limit,
+ };
+ let explored = crate::memory::explore::explore(&config, explore_params(Some(100)))
+ .await
+ .unwrap();
+ assert_eq!(explored.total, 2);
+ assert!(!explored.truncated);
+ assert_eq!(
+ explored
+ .buckets
+ .iter()
+ .map(|bucket| bucket.value.as_str())
+ .collect::<Vec<_>>(),
+ ["org/alpha", "org/beta"]
+ );
+ let limited = crate::memory::explore::explore(&config, explore_params(Some(1)))
+ .await
+ .unwrap();
+ assert_eq!(limited.total, 1);
+ assert!(limited.truncated);
+
+ let listed = items_list(&config, Default::default()).await.unwrap();
+ assert_eq!(listed.items.len(), 4);
+ assert!(listed.items.iter().any(|item| item.id.0 == own));
+ assert!(!listed.items.iter().any(|item| item.id.0 == foreign));
+
+ let fetched = fetch(
+ &config,
+ FetchParams {
+ refers_to: None,
+ query: "private marker".into(),
+ mode: None,
+ filter: None,
+ limit: None,
+ cursor: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert!(!fetched.hits.iter().any(|hit| hit.id.0 == foreign));
+
+ let recalled = recall(
+ &config,
+ RecallParams {
+ refers_to: None,
+ question: "private marker".into(),
+ filter: None,
+ limit: None,
+ },
+ )
+ .await
+ .unwrap();
- assert!(recalled
- .citations
- .iter()
- .all(|citation| citation.id.0 != foreign));
++ assert!(
++ recalled
++ .citations
++ .iter()
++ .all(|citation| citation.id.0 != foreign)
++ );
+
+ let learned = learn(
+ &config,
+ learn_params("clamped learning"),
+ Some(MemoryMeta {
+ namespace: "team:other".parse().unwrap(),
+ ..MemoryMeta::default()
+ }),
+ )
+ .await
+ .unwrap();
+ let stored = store_item(
+ &config,
+ StoreItem::learning(
+ "clamped store",
+ tinymemory_api::LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: "team:other".parse().unwrap(),
+ ..MemoryMeta::default()
+ },
+ ),
+ )
+ .await
+ .unwrap();
+ let own_items = engine
+ .list(tinymemory_api::ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::subtree("team:acme".parse().unwrap())),
+ ..MetaFilter::default()
+ },
+ limit: 20,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items;
+ for id in [learned.id, stored.id.0] {
+ let item = own_items.iter().find(|item| item.id.0 == id).unwrap();
+ assert_eq!(item.meta.namespace, "team:acme".parse().unwrap());
+ }
+
+ let forgotten = forget(
+ &config,
+ ForgetParams {
+ ids: vec![foreign.clone()],
+ reach: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(forgotten.forgotten, 0);
+ let foreign_items = engine
+ .list(tinymemory_api::ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::subtree("team:other".parse().unwrap())),
+ ..MetaFilter::default()
+ },
+ limit: 20,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items;
+ assert!(foreign_items.iter().any(|item| item.id.0 == foreign));
+
+ let service_namespace: tinymemory_api::Namespace =
+ "team:acme/service:newsletter".parse().unwrap();
+ let source_id = "src-profile-cleanup";
+ for namespace in ["team:acme", "team:other", "team:acme/service:newsletter"] {
+ engine
+ .store(StoreItem::Document {
+ title: Some("source cleanup fixture".into()),
+ body: DocumentBody::Text("source cleanup fixture".into()),
+ mime: None,
+ meta: MemoryMeta {
+ namespace: namespace.parse().unwrap(),
+ source: SourceRef {
+ kind: SourceKind::Folder,
+ id: Some(source_id.into()),
+ },
+ ..MemoryMeta::default()
+ },
+ })
+ .await
+ .unwrap();
+ }
+ assert_eq!(
+ crate::memory::sources::forget_items(&config, source_id)
+ .await
+ .unwrap(),
+ 2
+ );
+ let service_source_items = engine
+ .list(ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::exact(service_namespace.clone())),
+ source_id: Some(source_id.into()),
+ ..MetaFilter::default()
+ },
+ limit: 20,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items;
+ // No explicit reach uses the engine's ordinary root subtree,
+ // which leaves the service sandbox intact.
+ assert_eq!(service_source_items.len(), 1);
+
+ let thread_id = "thread-profile-cleanup";
+ for namespace in ["team:acme", "team:other", "team:acme/service:newsletter"] {
+ engine
+ .store(StoreItem::Conversation {
+ turns: vec![Turn::new(Role::User, "thread cleanup fixture")],
+ meta: MemoryMeta {
+ namespace: namespace.parse().unwrap(),
+ thread_id: Some(thread_id.into()),
+ ..MemoryMeta::default()
+ },
+ })
+ .await
+ .unwrap();
+ }
+ assert_eq!(
+ crate::memory::deletion::forget_thread(&config, thread_id).await,
+ 2
+ );
+ let service_thread_items = engine
+ .list(ListRequest {
+ filter: MetaFilter {
+ reach: Some(Reach::exact(service_namespace)),
+ thread_id: Some(thread_id.into()),
+ kinds: vec![ItemKind::Conversation],
+ ..MetaFilter::default()
+ },
+ limit: 20,
+ cursor: None,
+ })
+ .await
+ .unwrap()
+ .items;
+ // Thread cleanup retains the same root-subtree boundary.
+ assert_eq!(service_thread_items.len(), 1);
+ });
+ println!("SAAS_MEMORY_CLAMP_CHILD_PASSED");
+}
+
+struct CountingEngine {
+ inner: ReferenceEngine,
+ calls: Arc<AtomicUsize>,
+}
+
+#[async_trait::async_trait]
+impl MemoryEngine for CountingEngine {
+ fn descriptor(&self) -> &EngineDescriptor {
+ self.inner.descriptor()
+ }
+
+ async fn health(&self) -> tinymemory_api::EngineHealth {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.health().await
+ }
+
+ async fn recall(
+ &self,
+ request: RecallRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.recall(request).await
+ }
+
+ async fn fetch(
+ &self,
+ request: FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.fetch(request).await
+ }
+
+ async fn store(&self, item: StoreItem) -> tinymemory_api::Result<StoreReceipt> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.store(item).await
+ }
+
+ async fn forget(&self, target: ForgetTarget) -> tinymemory_api::Result<ForgetReport> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.forget(target).await
+ }
+
+ async fn list(&self, request: ListRequest) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.list(request).await
+ }
+}
diff --cc crates/openhuman-core/src/memory/ops_tests.rs
index c41743a6fe,8e54434dfc..529a0c577a
--- a/crates/openhuman-core/src/memory/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_tests.rs
@@@ -369,9 -267,9 +369,11 @@@ async fn stores_are_scrubbed_of_secrets
.unwrap();
let items = stored(&engine, MetaFilter::default()).await;
assert_eq!(items.len(), 1);
-- assert!(!items[0]
-- .text
-- .contains("abcdefghijklmnopqrstuvwxyz0123456789"));
++ assert!(
++ !items[0]
++ .text
++ .contains("abcdefghijklmnopqrstuvwxyz0123456789")
++ );
}
#[test]
diff --cc crates/openhuman-core/src/memory/schemas.rs
index 5996f1c821,e55ddac282..c2cbe7a778
--- a/crates/openhuman-core/src/memory/schemas.rs
+++ b/crates/openhuman-core/src/memory/schemas.rs
@@@ -3,55 -3,10 +3,55 @@@
mod defs;
mod handlers;
--use crate::core::all::RegisteredController;
use crate::core::ControllerSchema;
++use crate::core::all::RegisteredController;
--pub use defs::{schema, FUNCTIONS};
++pub use defs::{FUNCTIONS, schema};
+
+/// Every memory function paired with the handler it dispatches to.
+const HANDLERS: &[(&str, crate::core::all::ControllerHandler)] = &[
+ ("engines_list", handlers::engines_list),
+ ("engine_get", handlers::engine_get),
+ ("engine_set", handlers::engine_set),
+ ("policy_get", handlers::policy_get),
+ ("policy_set", handlers::policy_set),
+ ("pack_preview", handlers::pack_preview),
+ ("recall", handlers::recall),
+ ("fetch", handlers::fetch),
+ ("learn", handlers::learn),
+ ("forget", handlers::forget),
+ ("erase_all", handlers::erase_all),
+ ("items_list", handlers::items_list),
+ ("explore", handlers::explore),
+ ("items_get", handlers::items_get),
+ ("agents_list", handlers::agents_list),
+ (
+ "conversations_backfill_status",
+ handlers::conversations_backfill_status,
+ ),
+ (
+ "conversations_backfill_start",
+ handlers::conversations_backfill_start,
+ ),
+ ("brain_sources", handlers::brain_sources),
+ ("brain_search", handlers::brain_search),
+ ("brain_ingest", handlers::brain_ingest),
+ ("brain_forget", handlers::brain_forget),
+ ("sources_list", handlers::sources_list),
+ ("sources_add", handlers::sources_add),
+ ("sources_remove", handlers::sources_remove),
+ ("sources_sync", handlers::sources_sync),
+ ("jobs_list", handlers::jobs_list),
+ ("jobs_run", handlers::jobs_run),
+ ("import_scan", handlers::import_scan),
+ ("import_start", handlers::import_start),
+ ("import_status", handlers::import_status),
+ ("import_retry_failed", handlers::import_retry_failed),
+ ("migration_scan", handlers::migration_scan),
+ ("migration_start", handlers::migration_start),
+ ("migration_status", handlers::migration_status),
+ ("migration_retry", handlers::migration_retry),
+];
/// Every `memory` controller schema.
#[must_use]
diff --cc crates/openhuman-core/src/memory/schemas/handlers.rs
index 1338a725c2,aa455676d8..6fb09fdc95
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@@ -16,65 -19,14 +16,65 @@@ use crate::memory::types::
SourceRemovedView, SourcesAddParams, SourcesListView, SourcesRemoveParams, SourcesSyncParams,
SourcesSyncView,
};
-use crate::memory::{backfill, brain, confine, engine, import, layout_migration, ops, sources};
+use crate::memory::{backfill, brain, engine, import, layout_migration, ops, sources};
- use serde::de::DeserializeOwned;
+use serde::Serialize;
- use serde_json::{json, Map, Value};
++use serde::de::DeserializeOwned;
++use serde_json::{Map, Value, json};
+use tinymemory_api::{Error, Reach, Result};
+use tinymemory_tools::confine::{Confinement, Policy};
+use tinymemory_tools::layout::identity::Identity;
+
+fn rpc_confinement(config: &Config) -> Confinement {
+ let identity = Identity::root().resolve(&scope::identity_pins(config));
+ Confinement {
+ allowed: Reach::subtree(identity.root().clone()),
+ policy: Policy::Refuse,
+ }
+}
+
+/// The operation run after the common request parsing and config load.
+trait RpcOperation<P, R>: Send + 'static {
+ type Future: Future<Output = Result<R>> + Send + 'static;
+
+ fn call(self, ctx: DispatchCtx, config: Config, params: P) -> Self::Future;
+}
+
+impl<P, R, F, Fut> RpcOperation<P, R> for F
+where
+ F: FnOnce(DispatchCtx, Config, P) -> Fut + Send + 'static,
+ Fut: Future<Output = Result<R>> + Send + 'static,
+{
+ type Future = Fut;
+
+ fn call(self, ctx: DispatchCtx, config: Config, params: P) -> Self::Future {
+ self(ctx, config, params)
+ }
+}
-fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
- serde_json::from_value(Value::Object(params))
- .map_err(|error| MemoryError::invalid(format!("invalid params: {error}")).into())
+/// Runs the memory RPC's shared parse → load → call → finish sequence.
+fn rpc<P, R>(
+ ctx: DispatchCtx,
+ params: Map<String, Value>,
+ operation: impl RpcOperation<P, R>,
+) -> ControllerFuture
+where
+ P: DeserializeOwned + Send + 'static,
+ R: Serialize + Send + 'static,
+{
+ Box::pin(async move {
+ let params = parse::<P>(params)?;
+ let config = load(&ctx).await?;
+ finish(operation.call(ctx, config, params).await)
+ })
}
-fn to_json<T: Serialize>(value: T) -> Result<Value, String> {
+fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> std::result::Result<T, String> {
+ serde_json::from_value(Value::Object(params)).map_err(|error| {
+ StructuredRpcError::from(Error::InvalidRequest(format!("invalid params: {error}"))).encode()
+ })
+}
+
+fn to_json<T: Serialize>(value: T) -> std::result::Result<Value, String> {
Outcome::new(value, Vec::new()).into_cli_compatible_json()
}
diff --cc crates/openhuman-core/src/memory/schemas_tests.rs
index 3cdcf0d509,20b15511be..cd85d9d51d
--- a/crates/openhuman-core/src/memory/schemas_tests.rs
+++ b/crates/openhuman-core/src/memory/schemas_tests.rs
@@@ -1,11 -1,10 +1,11 @@@
use super::*;
use crate::config::Config;
--use crate::core::runtime::context::CoreContext;
use crate::core::runtime::DispatchCtx;
use crate::core::runtime::DomainSet;
++use crate::core::runtime::context::CoreContext;
use crate::memory::test_fixtures::{bind_reference, config_in};
--use serde_json::{json, Map, Value};
++use serde_json::{Map, Value, json};
+use tinymemory_api::MemoryEngine;
/// Every method of the spec's RPC table (`docs/specs/memory-v2.md`), exactly.
const SPEC_METHODS: [&str; 35] = [
@@@ -470,10 -315,10 +470,12 @@@ async fn lifecycle_handlers_answer_over
.unwrap();
let preview = preview.get("result").unwrap_or(&preview);
assert_eq!(preview["mode"], "turn");
-- assert!(preview["pack"]["markdown"]
-- .as_str()
-- .unwrap()
-- .contains("9:30"));
++ assert!(
++ preview["pack"]["markdown"]
++ .as_str()
++ .unwrap()
++ .contains("9:30")
++ );
let ran = call(&config, "jobs_run", json!({})).await.unwrap();
assert_eq!(
@@@ -516,114 -361,6 +518,116 @@@ async fn engine_set_persists_the_select
);
}
+#[tokio::test]
+async fn rpc_learn_invalidates_a_cached_prefetch_pack() {
+ use std::sync::Arc;
+ use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta};
+
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ engine
+ .store(tinymemory_api::StoreItem::learning(
+ "The user prefers dark roast coffee",
+ LearningKind::Preference,
+ 0.9,
+ MemoryMeta::default(),
+ ))
+ .await
+ .unwrap();
+
+ let ctx = CoreContext::for_test_with_config(DomainSet::full(), config.clone());
+ let dispatch = DispatchCtx::new(ctx.clone());
+ let identity = tinymemory_tools::layout::identity::Identity::root()
+ .resolve(&crate::memory::scope::identity_pins(&config));
+ let thread = "rpc-learn-invalidates-prefetch";
+ let input = || {
+ (
+ thread.to_string(),
+ 0,
+ "What coffee do I like?".to_string(),
+ 0,
+ chrono::Utc::now(),
+ false,
+ None,
+ )
+ };
+
+ CoreContext::scope(ctx.clone(), async {
+ let config = Arc::new(config.clone());
+ let (thread_id, turn_index, user_text, in_prompt_from, at, resumed, observed_actor) =
+ input();
- assert!(crate::memory::lifecycle::prefetch::pre_turn(
- &dispatch,
- config.clone(),
- identity.clone(),
- thread_id,
- turn_index,
- user_text,
- in_prompt_from,
- at,
- resumed,
- observed_actor,
- None,
- )
- .is_none());
++ assert!(
++ crate::memory::lifecycle::prefetch::pre_turn(
++ &dispatch,
++ config.clone(),
++ identity.clone(),
++ thread_id,
++ turn_index,
++ user_text,
++ in_prompt_from,
++ at,
++ resumed,
++ observed_actor,
++ None,
++ )
++ .is_none()
++ );
+ crate::memory::lifecycle::prefetch::settle_for_test(
+ &dispatch, &config, &identity, thread, false,
+ )
+ .await;
+ let (thread_id, turn_index, user_text, in_prompt_from, at, resumed, observed_actor) =
+ input();
+ assert!(
+ crate::memory::lifecycle::prefetch::pre_turn(
+ &dispatch,
+ config.clone(),
+ identity.clone(),
+ thread_id,
+ turn_index,
+ user_text,
+ in_prompt_from,
+ at,
+ resumed,
+ observed_actor,
+ None,
+ )
+ .is_some(),
+ "the initial turn should consume its completed pack"
+ );
+
+ call(
+ &config,
+ "learn",
+ json!({"text": "The user enjoys espresso"}),
+ )
+ .await
+ .unwrap();
+
+ let (thread_id, turn_index, user_text, in_prompt_from, at, resumed, observed_actor) =
+ input();
+ assert!(
+ crate::memory::lifecycle::prefetch::pre_turn(
+ &dispatch,
+ config,
+ identity,
+ thread_id,
+ turn_index,
+ user_text,
+ in_prompt_from,
+ at,
+ resumed,
+ observed_actor,
+ None,
+ )
+ .is_none(),
+ "a later turn must not consume a pack cached before RPC learn"
+ );
+ })
+ .await;
+}
+
#[tokio::test]
async fn source_handlers_add_remove_and_sync() {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/memory/scope_tests.rs
index 7931494e94,3dac987698..c309839735
--- a/crates/openhuman-core/src/memory/scope_tests.rs
+++ b/crates/openhuman-core/src/memory/scope_tests.rs
@@@ -1,116 -1,11 +1,117 @@@
use super::*;
use crate::config::schema::MemoryAgentConfig;
+use tinymemory_api::{MetaFilter, Namespace, Reach};
+use tinymemory_tools::confine::{Confinement, Policy};
+use tinymemory_tools::layout::identity::{
- account_root, actor_of_root, chat_node, validate_root, Identity, ResolvedIdentity,
- DEFAULT_AGENT_ID,
++ DEFAULT_AGENT_ID, Identity, ResolvedIdentity, account_root, actor_of_root, chat_node,
++ validate_root,
+};
fn ns(value: &str) -> Namespace {
value.parse().unwrap()
}
+#[test]
+fn config_identity_adapter_preserves_host_definition_recall_and_v3_pins() {
+ let mut config = Config::default();
+ config.memory.agent_id = Some("host-agent".into());
+ config.memory.root = Some("team:host".into());
+ config.memory.recall.enabled = false;
+ config.memory.layout = MemoryLayoutMode::V3;
+ config.memory.agents.insert(
+ "planner".into(),
+ MemoryAgentConfig {
+ agent_id: Some("planner-memory".into()),
+ root: Some("project:q4".into()),
+ recall: Some(true),
+ },
+ );
+
+ let pins = super::identity_pins(&config);
+ assert_eq!(pins.agent_id.as_deref(), Some("host-agent"));
+ assert_eq!(pins.root.as_deref(), Some("team:host"));
+ assert!(!pins.recall);
+ assert!(pins.v3);
+ assert_eq!(pins.agents.len(), 1);
+ assert_eq!(
+ pins.agents["planner"].agent_id.as_deref(),
+ Some("planner-memory")
+ );
+ assert_eq!(pins.agents["planner"].root.as_deref(), Some("project:q4"));
+ assert_eq!(pins.agents["planner"].recall, Some(true));
+
+ let resolved: ResolvedIdentity = Identity::team_member("other", "planner").resolve(&pins);
+ assert_eq!(resolved.agent_id, "host-agent");
+ assert_eq!(resolved.root(), &ns("team:host"));
+ assert!(resolved.recall);
+ assert_eq!(
+ resolved.layout.pooled_conversations_node(),
+ Some(&ns("team:host/ws:main"))
+ );
+}
+
+#[test]
+fn upstream_identity_and_confinement_keep_embedded_root_and_rpc_policy() {
+ let mut config = Config::default();
+ config.memory.root = Some("project:embed/team:acme".into());
+ let resolved = Identity::agent("planner").resolve(&super::identity_pins(&config));
+ assert_eq!(resolved.root(), &ns("project:embed/team:acme"));
+
+ let allowed = Reach::subtree(resolved.root().clone());
+ let rpc = Confinement {
+ allowed: allowed.clone(),
+ policy: Policy::Refuse,
+ };
+ let narrow = ns("project:embed/team:acme/agent:planner");
+ assert_eq!(
+ rpc.filter(Some(MetaFilter {
+ reach: Some(Reach::exact(narrow.clone())),
+ ..MetaFilter::default()
+ }))
+ .unwrap()
+ .reach,
+ Some(Reach::exact(narrow))
+ );
- assert!(rpc
- .filter(Some(MetaFilter {
++ assert!(
++ rpc.filter(Some(MetaFilter {
+ reach: Some(Reach::subtree(ns("project:embed/team:other"))),
+ ..MetaFilter::default()
+ }))
- .is_err());
++ .is_err()
++ );
+
+ let saas = Confinement {
+ allowed,
+ policy: Policy::Clamp,
+ };
+ let clamped = saas
+ .filter(Some(MetaFilter {
+ reach: Some(Reach::subtree(Namespace::ROOT)),
+ ..MetaFilter::default()
+ }))
+ .unwrap();
+ assert_eq!(clamped.reach, Some(Reach::subtree(resolved.root().clone())));
+}
+
+#[test]
+fn account_v3_identity_pools_at_the_absolute_layout_workspace() {
+ let mut config = Config::default();
+ config.config_path = "/srv/openhuman/users/6512ab0f6512ab0f6512ab0f/config.toml".into();
+ config.memory.layout = MemoryLayoutMode::V3;
+
+ let resolved = Identity::root().resolve(&super::identity_pins(&config));
+ assert_eq!(
+ user_root(&config).as_deref(),
+ Some("org:6512ab0f6512ab0f6512ab0f")
+ );
+ assert_eq!(resolved.root(), &Namespace::ROOT);
+ assert_eq!(
+ resolved.layout.pooled_conversations_node(),
+ Some(&ns("ws:main"))
+ );
+}
+
#[test]
fn by_default_an_agent_is_its_definition_under_the_default_root() {
let config = Config::default();
diff --cc crates/openhuman-core/src/memory/sources/mod.rs
index f55910daa0,b843d17d4e..027a04bca0
--- a/crates/openhuman-core/src/memory/sources/mod.rs
+++ b/crates/openhuman-core/src/memory/sources/mod.rs
@@@ -10,16 -10,14 +10,16 @@@
pub mod state;
mod sync;
-use tinymemory_api::{ForgetTarget, MetaFilter};
+use tinymemory_integrations::sources::SourceState;
+use tinymemory_integrations::sources::{Error as SourceError, SourceSpec};
+use tinymemory_tools::ops::MemoryOps;
--use crate::config::schema::{MemorySourceConfig, MemorySourceKind};
use crate::config::Config;
++use crate::config::schema::{MemorySourceConfig, MemorySourceKind};
use super::engine;
-use super::error::{MemoryError, MemoryResult};
use super::types::{SourceView, SourcesAddParams};
+use tinymemory_api::{Error, Result};
pub use sync::{start_sync, sync_due, sync_one};
diff --cc crates/openhuman-core/src/memory/sources/state.rs
index 29046fdacd,17331c165e..0d906b136f
--- a/crates/openhuman-core/src/memory/sources/state.rs
+++ b/crates/openhuman-core/src/memory/sources/state.rs
@@@ -14,34 -17,37 +14,43 @@@ use tinymemory_integrations::sources::{
/// Serialises state-file read-modify-writes in this process.
static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
-/// What the last sync of one source left behind.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct SourceState {
- /// When the last sync finished.
- #[serde(default)]
- pub last_sync_at: Option<DateTime<Utc>>,
- /// Current status.
- #[serde(default)]
- pub status: SourceStatus,
- /// Why the last sync failed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// Items stored by the last successful sync.
- #[serde(default)]
- pub items: u64,
-}
-
+ const STATE: &str = "sources_state";
+
+fn path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("sources_state.json")
++ crate::memory::state_store::legacy_path(workspace_dir, STATE)
+}
+
fn read_all(workspace_dir: &Path) -> BTreeMap<String, SourceState> {
- let file = path(workspace_dir);
- let Ok(text) = std::fs::read_to_string(&file) else {
- return BTreeMap::new();
- };
- serde_json::from_str(&text).unwrap_or_else(|error| {
- tracing::warn!(%error, "[memory:sources] sync state unparsable; set aside");
- if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {
- tracing::warn!(%error, "[memory:sources] could not set sync state file aside");
- crate::memory::state_store::load(workspace_dir, STATE)
- .unwrap_or_else(|error| {
- tracing::warn!(error = %error, "[memory:sources] reading sync state failed");
- None
- })
- .unwrap_or_default()
++ match crate::memory::state_store::load(workspace_dir, STATE) {
++ Ok(Some(state)) => state,
++ Ok(None) => {
++ quarantine_legacy_file(workspace_dir);
++ BTreeMap::new()
+ }
- BTreeMap::new()
- })
++ Err(error) => {
++ tracing::warn!(%error, "[memory:sources] reading sync state failed");
++ quarantine_legacy_file(workspace_dir);
++ BTreeMap::new()
++ }
++ }
}
fn write_all(workspace_dir: &Path, all: &BTreeMap<String, SourceState>) {
+ if let Err(error) = crate::memory::state_store::save(workspace_dir, STATE, all) {
- tracing::warn!(error = %error, "[memory:sources] writing sync state failed");
++ tracing::warn!(%error, "[memory:sources] writing sync state failed");
++ }
++}
++
++fn quarantine_legacy_file(workspace_dir: &Path) {
+ let file = path(workspace_dir);
- let result = serde_json::to_vec_pretty(all)
- .map_err(std::io::Error::other)
- .and_then(|json| {
- crate::security::secret_storage::file_store::write_atomic(&file, &json)
- .map_err(std::io::Error::other)
- });
- if let Err(error) = result {
- tracing::warn!(error = %error, "[memory:sources] writing sync state failed");
++ let Ok(bytes) = std::fs::read(&file) else {
++ return;
++ };
++ if serde_json::from_slice::<BTreeMap<String, SourceState>>(&bytes).is_ok() {
++ return;
++ }
++ if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {
++ tracing::warn!(%error, "[memory:sources] could not set sync state file aside");
}
}
diff --cc crates/openhuman-core/src/memory/sources/sync.rs
index 2fbbf07246,aef249c028..6951112ad3
--- a/crates/openhuman-core/src/memory/sources/sync.rs
+++ b/crates/openhuman-core/src/memory/sources/sync.rs
@@@ -11,17 -11,17 +11,17 @@@ use std::path::PathBuf
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use chrono::{DateTime, Utc};
++use tinymemory_integrations::sources::SourceKind;
++use tinymemory_integrations::sources::SourceStatus;
use tinymemory_integrations::sources::sync::{
self as module, RegisteredSource, SourceRegistry, SyncError, SyncState, SyncStatus, SyncUpdate,
Syncer,
};
--use tinymemory_integrations::sources::SourceKind;
- use tinymemory_integrations::sources::SourceStatus;
--use crate::config::schema::{MemorySourceConfig, MemorySourceKind};
use crate::config::Config;
++use crate::config::schema::{MemorySourceConfig, MemorySourceKind};
use crate::memory::engine;
-use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::types::SourceStatus;
+use tinymemory_api::{Error, Result};
use super::state;
diff --cc crates/openhuman-core/src/memory/sources/sync_tests.rs
index eed0b49518,43a918f9c9..129e75be63
--- a/crates/openhuman-core/src/memory/sources/sync_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/sync_tests.rs
@@@ -102,9 -102,9 +102,11 @@@ async fn sync_one_reports_memory_off_an
bind_reference(&config);
let missing = config.action_dir.join("does-not-exist");
-- assert!(sync_one(&config, &folder_source("s", &missing, None))
-- .await
-- .is_err());
++ assert!(
++ sync_one(&config, &folder_source("s", &missing, None))
++ .await
++ .is_err()
++ );
}
#[tokio::test]
@@@ -197,13 -197,13 +199,15 @@@ async fn a_source_already_syncing_is_no
// Hold a claim as a running sync would: a second request starts nothing.
let held = syncer_for(&config).start(Some("src-once")).unwrap();
assert_eq!(held.len(), 1);
-- assert!(start_sync(
-- &crate::core::runtime::DispatchCtx::ambient(),
-- &config,
-- Some("src-once")
-- )
-- .unwrap()
-- .is_empty());
++ assert!(
++ start_sync(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ Some("src-once")
++ )
++ .unwrap()
++ .is_empty()
++ );
drop(held);
assert_eq!(
start_sync(
@@@ -266,12 -266,12 +270,14 @@@ fn sync_due_with_memory_off_starts_noth
.memory
.sources
.push(folder_source("s", tmp.path(), Some(15)));
-- assert!(sync_due(
-- &crate::core::runtime::DispatchCtx::ambient(),
-- &config,
-- Utc::now()
-- )
-- .is_empty());
++ assert!(
++ sync_due(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ Utc::now()
++ )
++ .is_empty()
++ );
}
#[test]
@@@ -296,8 -296,8 +302,8 @@@ fn reset_interrupted_marks_syncing_sour
#[tokio::test]
async fn a_sync_queues_a_belief_build_only_for_an_engine_that_waits_for_one() {
use std::sync::Arc;
-- use tinymemory_api::conformance::ReferenceEngine;
use tinymemory_api::Consolidation;
++ use tinymemory_api::conformance::ReferenceEngine;
let note = || {
tinymemory_api::StoreItem::document(
diff --cc crates/openhuman-core/src/memory/state_store.rs
index 0000000000,87a24a8aec..c9b0d71cba
mode 000000,100644..100644
--- a/crates/openhuman-core/src/memory/state_store.rs
+++ b/crates/openhuman-core/src/memory/state_store.rs
@@@ -1,0 -1,166 +1,170 @@@
+ //! The memory domain's small runtime state values (`jobs`, `channel_threads`,
+ //! `pending_deletions`, `sources_state`, `import_state`,
+ //! `conversations_backfill`, `layout_migration`, `local_root`) on the storage
+ //! port.
+ //!
+ //! Each used to be `<workspace>/memory/<name>.json`. Each is now one
+ //! `tsd.kv` entry (owner `memory`, namespace `state`, key `<name>`) in the
+ //! acting scope; the first read in a backend imports the legacy file once
+ //! ([`StateKv::import_file`]) and leaves it in place.
+
+ use std::path::{Path, PathBuf};
+
+ use anyhow::Result;
-use serde::de::DeserializeOwned;
+ use serde::Serialize;
++use serde::de::DeserializeOwned;
+
+ use crate::storage::state_kv::StateKv;
+
+ const OWNER: &str = "memory";
+ const NS: &str = "state";
+
+ /// The legacy file of state value `name` in `workspace_dir`.
+ #[must_use]
+ pub(crate) fn legacy_path(workspace_dir: &Path, name: &str) -> PathBuf {
+ workspace_dir.join("memory").join(format!("{name}.json"))
+ }
+
+ fn open(workspace_dir: &Path, name: &str) -> Result<StateKv> {
+ let kv = StateKv::open(workspace_dir, OWNER, NS)?;
+ kv.import_file(name, &legacy_path(workspace_dir, name))?;
+ Ok(kv)
+ }
+
+ /// [`open`] for a value a damaged legacy file must not reset.
+ fn open_strict(workspace_dir: &Path, name: &str) -> Result<StateKv> {
+ let kv = StateKv::open(workspace_dir, OWNER, NS)?;
+ kv.import_file_strict(name, &legacy_path(workspace_dir, name))?;
+ Ok(kv)
+ }
+
+ /// Imports every `<workspace>/memory/*.json` state file into the `local` scope
+ /// of an explicit `scoped` handle, once each. For the layout migration
+ /// (`storage::layout`), which deletes those files afterwards; a file that is
+ /// not JSON is an error here (nothing may be deleted unimported), so it is
+ /// imported strictly. Returns the names imported.
+ ///
+ /// # Errors
+ ///
+ /// A storage error or an unparsable file.
+ pub(crate) fn import_all(
+ scoped: &crate::storage::ScopedStorage,
+ workspace_dir: &Path,
+ ) -> Result<Vec<String>> {
+ let kv = StateKv::over(scoped, OWNER, NS);
+ let mut names = Vec::new();
+ let Ok(entries) = std::fs::read_dir(workspace_dir.join("memory")) else {
+ return Ok(names);
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Some(name) = path
+ .file_name()
+ .and_then(|f| f.to_str())
+ .and_then(|f| f.strip_suffix(".json"))
+ .map(str::to_owned)
+ else {
+ continue;
+ };
+ if !path.is_file() {
+ continue;
+ }
+ kv.import_file_strict(&name, &path)?;
+ names.push(name);
+ }
+ names.sort();
+ Ok(names)
+ }
+
+ /// [`load`], failing on a damaged legacy file instead of starting over.
+ ///
+ /// # Errors
+ ///
+ /// A storage error, an unparsable legacy file, or a stored value that is not
+ /// a `T`.
+ pub(crate) fn load_strict<T: DeserializeOwned + Send + 'static>(
+ workspace_dir: &Path,
+ name: &str,
+ ) -> Result<Option<T>> {
+ open_strict(workspace_dir, name)?.get(name)
+ }
+
+ /// State value `name`, or `None` when none was stored.
+ ///
+ /// # Errors
+ ///
+ /// A storage error, or a stored value that is not a `T`.
+ pub(crate) fn load<T: DeserializeOwned + Send + 'static>(
+ workspace_dir: &Path,
+ name: &str,
+ ) -> Result<Option<T>> {
+ open(workspace_dir, name)?.get(name)
+ }
+
+ /// The names of the state values starting with `prefix`: those stored, plus
+ /// those whose legacy file is still in `<workspace>/memory/` (each is
+ /// imported first, so a name appears once).
+ ///
+ /// # Errors
+ ///
+ /// A storage error, or an unparsable legacy file.
+ pub(crate) fn names(workspace_dir: &Path, prefix: &str) -> Result<Vec<String>> {
+ if let Ok(entries) = std::fs::read_dir(workspace_dir.join("memory")) {
+ for entry in entries.flatten() {
+ let file = entry.file_name();
+ let Some(name) = file
+ .to_str()
+ .and_then(|file| file.strip_suffix(".json"))
+ .filter(|name| name.starts_with(prefix))
+ else {
+ continue;
+ };
+ open_strict(workspace_dir, name)?;
+ }
+ }
+ let kv = StateKv::open(workspace_dir, OWNER, NS)?;
+ Ok(kv
+ .list::<serde_json::Value>(prefix)?
+ .into_iter()
+ .map(|(name, _)| name)
+ .collect())
+ }
+
+ /// Stores `value` as state value `name`.
+ ///
+ /// # Errors
+ ///
+ /// A storage error.
+ pub(crate) fn save<T: Serialize>(workspace_dir: &Path, name: &str, value: &T) -> Result<()> {
+ open(workspace_dir, name)?.put(name, value)
+ }
+
+ /// Removes state value `name`.
+ ///
+ /// # Errors
+ ///
+ /// A storage error.
+ pub(crate) fn remove(workspace_dir: &Path, name: &str) -> Result<()> {
+ open(workspace_dir, name)?.delete(name).map(|_| ())
+ }
+
+ /// Stores `value` as `name` only when none exists, and returns what is stored.
+ ///
+ /// # Errors
+ ///
+ /// A storage error.
+ pub(crate) fn record_once<T>(workspace_dir: &Path, name: &str, value: &T) -> Result<T>
+ where
+ T: Serialize + DeserializeOwned + Clone + Send + 'static,
+ {
+ let kv = open_strict(workspace_dir, name)?;
+ if kv.insert_if_absent(name, value)? {
+ return Ok(value.clone());
+ }
+ kv.get(name)?
+ .ok_or_else(|| anyhow::anyhow!("the {name} record vanished"))
+ }
++
++#[cfg(test)]
++#[path = "state_store_tests.rs"]
++mod tests;
diff --cc crates/openhuman-core/src/memory/state_store_tests.rs
index 0000000000,0000000000..ac622840a2
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/memory/state_store_tests.rs
@@@ -1,0 -1,0 +1,64 @@@
++use tinymemory_api::{ConsolidateRequest, ItemKind, Namespace, Reach};
++use tinymemory_tools::BackgroundJob;
++
++use super::*;
++
++#[tokio::test]
++async fn host_memory_state_adapters_use_the_state_kv_port() {
++ let tmp = tempfile::tempdir().unwrap();
++ let config = crate::memory::test_fixtures::config_in(&tmp);
++ let workspace = &config.workspace_dir;
++
++ crate::memory::deletion::enqueue(
++ workspace,
++ crate::memory::deletion::PendingDeletion::Thread {
++ thread_id: "thread-1".into(),
++ },
++ );
++ crate::memory::sources::state::update(workspace, "src-1", |_| {});
++ crate::memory::layout_migration::state::save(workspace, &Default::default()).unwrap();
++ crate::memory::lifecycle::jobs::enqueue(
++ &config,
++ &Namespace::ROOT,
++ vec![BackgroundJob::BuildBeliefs {
++ request: ConsolidateRequest::new(Reach::exact(Namespace::agent("a")))
++ .kinds([ItemKind::Conversation]),
++ }],
++ )
++ .await;
++
++ for name in [
++ "pending_deletions",
++ "sources_state",
++ "layout_migration",
++ "jobs",
++ ] {
++ assert!(
++ super::load::<serde_json::Value>(workspace, name)
++ .unwrap()
++ .is_some(),
++ "memory state value {name} is stored through the KV port"
++ );
++ }
++}
++
++#[test]
++fn state_values_do_not_leak_between_workspaces() {
++ let first = tempfile::tempdir().unwrap();
++ let second = tempfile::tempdir().unwrap();
++ let first_config = crate::memory::test_fixtures::config_in(&first);
++ let second_config = crate::memory::test_fixtures::config_in(&second);
++
++ super::save(&first_config.workspace_dir, "isolation", &"first workspace").unwrap();
++
++ assert_eq!(
++ super::load::<String>(&first_config.workspace_dir, "isolation").unwrap(),
++ Some("first workspace".to_string())
++ );
++ assert!(
++ super::load::<String>(&second_config.workspace_dir, "isolation")
++ .unwrap()
++ .is_none(),
++ "a second workspace must not read the first workspace's state"
++ );
++}
diff --cc crates/openhuman-core/src/memory/tool_budget_tests.rs
index 626e7d36eb,790c3ba8f9..612385d1b8
--- a/crates/openhuman-core/src/memory/tool_budget_tests.rs
+++ b/crates/openhuman-core/src/memory/tool_budget_tests.rs
@@@ -146,42 -126,43 +146,46 @@@ async fn parallel_memory_reads_reserve_
#[tokio::test]
async fn completed_run_tracking_is_bounded() {
- let budget = ToolBudget::default();
+ let budget = budget();
for i in 0..200 {
- assert!(budget
- .run(Some(&format!("turn-{i}")), async { "ok" })
- .await
- .is_ok());
- budget
- .run(Some(format!("turn-{i}")), async {
- ToolResult::success("saved")
- })
- .await;
++ assert!(
++ budget
++ .run(Some(&format!("turn-{i}")), async { "ok" })
++ .await
++ .is_ok()
++ );
+ }
+ // The first idle record was evicted, so it receives a fresh call allowance.
+ for _ in 0..8 {
+ assert!(budget.run(Some("turn-0"), async { "ok" }).await.is_ok());
}
- let runs = budget.runs.lock().unwrap();
- assert_eq!(runs.states.len(), MAX_TRACKED_RUNS);
- assert_eq!(runs.order.len(), MAX_TRACKED_RUNS);
+ assert_eq!(
+ budget.run(Some("turn-0"), async { "too many" }).await,
+ Err(Refusal::Denied(DenialReason::CallLimit))
+ );
}
#[tokio::test(start_paused = true)]
async fn an_outstanding_memory_call_survives_other_runs_and_keeps_its_timeout_circuit() {
- let budget = ToolBudget::default();
- let call = budget.run(Some("active".into()), std::future::pending());
+ let budget = budget();
+ let call = budget.run(Some("active"), std::future::pending::<()>());
tokio::pin!(call);
assert!(futures::poll!(call.as_mut()).is_pending());
- for i in 0..MAX_TRACKED_RUNS {
- budget
- .run(Some(format!("other-{i}")), async {
- ToolResult::success("saved")
- })
- .await;
+ for i in 0..128 {
- assert!(budget
- .run(Some(&format!("other-{i}")), async { "ok" })
- .await
- .is_ok());
++ assert!(
++ budget
++ .run(Some(&format!("other-{i}")), async { "ok" })
++ .await
++ .is_ok()
++ );
}
- assert!(budget.runs.lock().unwrap().states.contains_key("active"));
- assert!(call.await.is_error);
- let calls = AtomicUsize::new(0);
- let result = budget
- .run(Some("active".into()), async {
- calls.fetch_add(1, Ordering::SeqCst);
- ToolResult::success("must not execute")
- })
- .await;
- assert!(result.is_error);
- assert_eq!(calls.load(Ordering::SeqCst), 0);
+ assert_eq!(call.await, Err(Refusal::TimedOut));
+ assert_eq!(
+ budget
+ .run(Some("active"), async { "must not execute" })
+ .await,
+ Err(Refusal::Denied(DenialReason::CircuitOpen))
+ );
}
#[tokio::test(start_paused = true)]
diff --cc crates/openhuman-core/src/memory/tool_writes.rs
index cef6a0011d,bd7609dddd..7faa076201
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@@ -11,27 -12,24 +12,26 @@@
//! the remote engine.
use std::collections::HashMap;
- use std::io::{Read, Write};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
use std::time::Duration;
use async_trait::async_trait;
use serde::Deserialize;
use sha2::{Digest, Sha256};
-use tinymemory_api::{Namespace, StoreItem, WriteOptions};
+use tinymemory_api::{Namespace, Reach, StoreItem, WriteOptions};
++use tinymemory_tools::ToolScope;
++use tinymemory_tools::WriteSink;
+use tinymemory_tools::confine::Policy;
use tinymemory_tools::list_store::{ListStore, StoreError};
use tinymemory_tools::pending::{
Ack, Binding, Entry, Epoch, FenceToken, Limits, PendingError, PendingWrites, WriteExecutor,
WriteGate, WriteOperation,
};
- use tinymemory_tools::ToolScope;
- use tinymemory_tools::WriteSink;
-use super::error::{MemoryError, MemoryResult};
-use super::tools::CallFacts;
-use super::types::{ForgetParams, LearnParams};
+use super::types::ForgetParams;
use crate::config::Config;
+use tinymemory_api::{Error, Result};
const MAX_PENDING: usize = 256;
const MAX_BYTES: usize = 2 * 1024 * 1024;
@@@ -221,13 -217,18 +221,12 @@@ fn enqueue_operation(config: &Config, o
));
}
let owner = owner_state(config);
- let ack = queue(&file)
+ queue(&file)
.enqueue(operation, scope_root, binding(config), &owner.gate)
- .map_err(map_pending)?;
- Ok(match ack {
- Ack::Learned { id } => serde_json::json!({"id":id, "status":QUEUED}),
- Ack::Forgotten { queued } => {
- serde_json::json!({"queued":queued, "status":"queued; not yet removed from memory"})
- }
- })
+ .map_err(map_pending)
}
- /// A [`ListStore`] over one queue file: owner-only, written through a
- /// temporary file and a rename, with the file and its directory fsynced.
+ /// A [`ListStore`] over one queue partition (one storage write per save).
struct FileStore {
file: PathBuf,
}
@@@ -338,42 -344,25 +343,31 @@@ fn owner_state(config: &Config) -> Arc<
let mut owners = OWNERS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- owners.entry(key).or_insert_with(|| {
- Box::leak(Box::new(OwnerState {
- gate: WriteGate::new(PROCESS_EPOCH.clone()),
- barrier: Arc::default(),
- }))
- })
+ owners.retain(|_, owner| owner.strong_count() > 0);
+ if let Some(owner) = owners.get(&key).and_then(Weak::upgrade) {
+ return owner;
+ }
+ let owner = Arc::new(OwnerState {
+ // A new gate starts at generation zero, so it needs a distinct epoch
+ // identity to make entries from a released gate stale after eviction.
+ gate: WriteGate::new(uuid::Uuid::new_v4().to_string()),
+ barrier: Arc::default(),
+ });
+ owners.insert(key, Arc::downgrade(&owner));
+ owner
}
-fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {
+fn partitions(config: &Config) -> Result<Vec<PathBuf>> {
let prefix = format!("{}-", owner_prefix(config));
- let entries = match std::fs::read_dir(config.workspace_dir.join("memory")) {
- Ok(entries) => entries,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
- Err(_) => return Err(unavailable()),
- };
- let mut files = Vec::new();
- for entry in entries {
- let file = entry.map_err(|_| unavailable())?.path();
- if file
- .file_name()
- .and_then(|name| name.to_str())
- .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".json"))
- {
- files.push(file);
- if files.len() > MAX_PENDING {
- return Err(unavailable());
- }
- }
+ let names =
+ super::state_store::names(&config.workspace_dir, &prefix).map_err(|_| unavailable())?;
+ if names.len() > MAX_PENDING {
+ return Err(unavailable());
}
- Ok(files)
+ Ok(names
+ .into_iter()
+ .map(|name| super::state_store::legacy_path(&config.workspace_dir, &name))
+ .collect())
}
/// Owner epoch captured when automatic turn work is admitted, before it can
diff --cc crates/openhuman-core/src/memory/tool_writes_tests.rs
index 2d94c5a51d,8a749d1cdc..35f364f735
--- a/crates/openhuman-core/src/memory/tool_writes_tests.rs
+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs
@@@ -1,122 -1,12 +1,122 @@@
use super::*;
-use crate::memory::scope::MemoryIdentity;
--use crate::memory::test_fixtures::{bind_reference, config_in, stored, RefusingEngine};
++use crate::memory::test_fixtures::{RefusingEngine, bind_reference, config_in, stored};
+use crate::memory::tools::CallFacts;
use serde_json::json;
-use tinymemory_api::Reach;
-use tinymemory_api::{MetaFilter, Namespace};
+use tinymemory_api::{MetaFilter, Namespace, Reach};
+use tinymemory_tools::{CallContext, SingleTool, ToolScope};
+
+/// Exercises the production native single-tool parser and the host write sink.
+pub(crate) fn enqueue(
+ config: &Config,
+ args: &serde_json::Value,
+ facts: &CallFacts,
+) -> tinymemory_api::Result<serde_json::Value> {
+ let config = config.clone();
+ let args = args.clone();
+ let facts = facts.clone();
+ let invoke = move || {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(async move {
+ let scope = ToolScope {
+ place: facts.namespace.clone(),
+ reach: Some(facts.reach.clone()),
+ writes: true,
+ zone: Some(config.time_zone()),
+ workspace: facts.workspace.clone(),
+ thread_id: facts.thread_id.clone(),
+ agent_id: facts.agent_id.clone(),
+ tool_call: Some(tinymemory_api::ToolCallRef {
+ name: crate::memory::tools::MEMORY_TOOL_NAME.to_string(),
+ id: facts.tool_call_id.clone(),
+ }),
+ };
+ let single = SingleTool::queued(
+ crate::memory::tools::MEMORY_TOOL_NAME,
+ scope,
+ std::sync::Arc::new(super::HostWriteSink::new(std::sync::Arc::new(config))),
+ );
+ let outcome = single
+ .call_with_details(args, CallContext::default())
+ .await?;
+ Ok(outcome.value)
+ })
+ };
+ if tokio::runtime::Handle::try_current().is_ok() {
+ std::thread::spawn(invoke)
+ .join()
+ .map_err(|_| tinymemory_api::Error::Unavailable("native test call panicked".into()))?
+ } else {
+ invoke()
+ }
+}
+
+pub(crate) fn queued_for(config: &Config, facts: &CallFacts) -> tinymemory_api::Result<Vec<Entry>> {
+ super::read_at(&super::queue_path(config, &facts.reach.at))
+}
+
+pub(crate) async fn drain_for(config: &Config, root: &Namespace) -> usize {
+ let file = super::queue_path(config, root);
+ let owner = super::owner_state(config);
+ let _owner = owner.barrier.read().await;
+ let state = super::drain_state(&file);
+ let _draining = state.barrier.lock().await;
+ let generation = owner.gate.generation();
+ super::drain_locked(config, &file, &owner, generation).await
+}
fn facts(config: &Config) -> CallFacts {
- CallFacts::of(config, &MemoryIdentity::agent("outbox-agent"))
+ CallFacts::of(
+ config,
+ &tinymemory_tools::layout::identity::Identity::agent("outbox-agent"),
+ )
+}
+
+#[test]
+fn owner_states_are_released_after_the_last_write_holder_drops() {
+ let temp = tempfile::tempdir().unwrap();
+ let mut keys = Vec::new();
+ let mut queue_files = Vec::new();
+ let states = (0..32)
+ .map(|index| {
+ let workspace = temp.path().join(index.to_string());
+ std::fs::create_dir_all(&workspace).unwrap();
+ let config = config_in(&temp);
+ let config = Config {
+ workspace_dir: workspace.clone(),
+ ..config
+ };
+ let file = workspace
+ .join("memory")
+ .join(format!("{}-writes.json", owner_prefix(&config)));
+ keys.push(workspace.join("memory").join(owner_prefix(&config)));
+ queue_files.push(file.clone());
+ drop(queue(&file));
+ owner_state(&config)
+ })
+ .collect::<Vec<_>>();
+
+ drop(states);
+ let sentinel_workspace = temp.path().join("sentinel");
+ std::fs::create_dir_all(&sentinel_workspace).unwrap();
+ let sentinel_config = Config {
+ workspace_dir: sentinel_workspace.clone(),
+ ..config_in(&temp)
+ };
+ drop(owner_state(&sentinel_config));
+ drop(queue(
+ &sentinel_workspace
+ .join("memory")
+ .join("sentinel-writes.json"),
+ ));
+
+ let owners = OWNERS.lock().unwrap();
+ assert!(keys.iter().all(|key| !owners.contains_key(key)));
+ drop(owners);
+ let queues = QUEUES.lock().unwrap();
+ assert!(queue_files.iter().all(|file| !queues.contains_key(file)));
}
#[tokio::test]
@@@ -210,32 -109,19 +214,21 @@@ fn private_outbox_is_scrubbed_before_pe
&facts(&config),
)
.unwrap();
- let file = path(&config.workspace_dir);
- let persisted = std::fs::read_to_string(&file).unwrap();
+ let persisted = serde_json::to_string(&read(&config.workspace_dir).unwrap()).unwrap();
assert!(!persisted.contains(secret));
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- assert_eq!(
- std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
- 0o600
- );
- assert_eq!(
- std::fs::metadata(file.parent().unwrap())
- .unwrap()
- .permissions()
- .mode()
- & 0o777,
- 0o700
- );
- }
+ assert!(
+ !path(&config.workspace_dir).exists(),
+ "the queue is a storage value, not a file"
+ );
let huge = "x".repeat(MAX_BYTES);
-- assert!(enqueue(
-- &config,
-- &json!({"action":"learn","text":huge}),
-- &facts(&config)
-- )
-- .is_err());
++ assert!(
++ enqueue(
++ &config,
++ &json!({"action":"learn","text":huge}),
++ &facts(&config)
++ )
++ .is_err()
++ );
assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);
}
@@@ -345,13 -235,14 +342,16 @@@ fn corrupt_existing_outbox_is_preserved
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let file = path(&config.workspace_dir);
- super::super::files::write_private(&file, b"corrupt existing state").unwrap();
- assert!(enqueue(
- &config,
- &json!({"action":"learn","text":"Prefers tea"}),
- &facts(&config)
- )
- .is_err());
+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();
+ std::fs::write(&file, b"corrupt existing state").unwrap();
- assert!(enqueue(
- &config,
- &json!({"action":"learn","text":"Prefers tea"}),
- &facts(&config)
- )
- .is_err());
++ assert!(
++ enqueue(
++ &config,
++ &json!({"action":"learn","text":"Prefers tea"}),
++ &facts(&config)
++ )
++ .is_err()
++ );
assert_eq!(std::fs::read(&file).unwrap(), b"corrupt existing state");
}
@@@ -420,12 -311,12 +420,14 @@@ fn a_full_outbox_keeps_existing_writes_
let mut entries = read(&config.workspace_dir).unwrap();
entries.resize(MAX_PENDING, entries[0].clone());
write(&config.workspace_dir, &entries).unwrap();
-- assert!(enqueue(
-- &config,
-- &json!({"action":"learn","text":"new"}),
-- &facts(&config)
-- )
-- .is_err());
++ assert!(
++ enqueue(
++ &config,
++ &json!({"action":"learn","text":"new"}),
++ &facts(&config)
++ )
++ .is_err()
++ );
assert_eq!(read(&config.workspace_dir).unwrap().len(), MAX_PENDING);
}
@@@ -654,12 -537,12 +656,16 @@@ async fn erasing_one_owner_fences_pendi
let fence = fence_and_clear(&crate::core::runtime::DispatchCtx::ambient(), &first)
.await
.unwrap();
-- assert!(read_at(&queue_path(&first, &facts(&first).reach.at))
-- .unwrap()
-- .is_empty());
-- assert!(read_at(&queue_path(&second, &facts(&second).reach.at))
-- .unwrap()
-- .is_empty());
++ assert!(
++ read_at(&queue_path(&first, &facts(&first).reach.at))
++ .unwrap()
++ .is_empty()
++ );
++ assert!(
++ read_at(&queue_path(&second, &facts(&second).reach.at))
++ .unwrap()
++ .is_empty()
++ );
drop(fence);
let engine = bind_reference(&first);
assert_eq!(drain(&first).await, 0);
diff --cc crates/openhuman-core/src/memory/tools.rs
index 4aff113ca7,e13393fcc1..f72d99e966
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@@ -1,16 -1,30 +1,16 @@@
-//! The single `memory` agent tool: `recall | fetch | learn | forget`.
-//!
-//! Registered only while memory is on (see [`crate::tools::ops`]). `learn`
-//! stamps the stored learning with what the host knows and the model does
-//! not get to choose:
-//!
-//! - `workspace` — the agent's working folder (`action_dir`, or the turn's
-//! isolated workspace when one is scoped);
-//! - `thread_id` and `agent_id` (the memory agent id the turn runs as,
-//! [`super::scope`]);
-//! - `namespace` — the layout's learnings node: the root of the acting
-//! identity's layout, which every agent under that root shares;
-//! - `tool_call` — this call's name and provider-assigned id;
-//! - `source.kind = agent`.
-//!
-//! `recall`, `fetch` and `forget` are confined to the identity's layout:
-//! everything under its root, never another root's (another tenant's or
-//! team's). A `reach` in the model's filter is overwritten.
+//! The host adapter for TinyMemory's single `memory` agent tool.
-use crate::tools::schema_cache::static_schema;
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::time::Duration;
use async_trait::async_trait;
--use serde_json::{json, Value};
-use tinymemory_api::{
- MemoryMeta, Namespace, Reach, RecallMode, SourceKind, SourceRef, ThreadWindow, ToolCallRef,
++use serde_json::{Value, json};
+use tinymemory_api::{Namespace, Reach, ThreadWindow, ToolCallRef};
+use tinymemory_tools::{
- concurrency_for, is_write_action, permission_for, CallContext, ConcurrencyClass, MemoryTools,
- PermissionClass, Refusal, RunBudget, SingleTool, ToolScope,
++ CallContext, ConcurrencyClass, MemoryTools, PermissionClass, Refusal, RunBudget, SingleTool,
++ ToolScope, concurrency_for, is_write_action, permission_for,
};
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
@@@ -134,115 -267,224 +134,117 @@@ impl tinymemory_tools::BudgetClock for
}
}
-/// About how many tokens of evidence `recall` hands the model (counted as
-/// four characters a token). The rest stays reachable through `fetch`.
-const EVIDENCE_TOKENS: usize = 2_500;
-
-/// The engine's closing note when a recall searched memory only in part.
-const PARTLY_SEARCHED: &str = "\n\n(Memory was only partly searched";
+/// The single `memory` tool exposed to the agent.
+pub struct MemoryTool {
+ config: Arc<Config>,
+ budget: RunBudget,
+}
-/// `evidence` cut to about [`EVIDENCE_TOKENS`] tokens, only ever at the end
-/// of a line: whole `---`-separated entries in rank order, then as many whole
-/// lines of the next entry as fit (marked `[…]`), then a note on what was
-/// left out. A line is never split, so a single line longer than the budget
-/// is kept whole when it is the first. The engine's closing note (memory
-/// only partly searched) is always kept.
-fn capped_evidence(evidence: &str) -> String {
- const SEPARATOR: &str = "\n\n---\n\n";
- let budget = EVIDENCE_TOKENS * 4;
- if evidence.len() <= budget {
- return evidence.to_string();
- }
- let (body, closing) = match evidence.rfind(PARTLY_SEARCHED) {
- Some(at) => (&evidence[..at], &evidence[at..]),
- None => (evidence, ""),
- };
- let entries: Vec<&str> = body.split(SEPARATOR).collect();
- let mut out = String::new();
- let mut whole = 0;
- let mut cut_short = false;
- for entry in &entries {
- let joint = if out.is_empty() { "" } else { SEPARATOR };
- if out.len() + joint.len() + entry.len() <= budget {
- out.push_str(joint);
- out.push_str(entry);
- whole += 1;
- continue;
- }
- // The entry does not fit: keep the whole lines of it that do.
- let mut lines = 0;
- for line in entry.split('\n') {
- let piece = if lines == 0 { joint.len() } else { 1 } + line.len();
- if out.len() + piece > budget && !out.is_empty() {
- break;
- }
- out.push_str(if lines == 0 { joint } else { "\n" });
- out.push_str(line);
- lines += 1;
- }
- if lines == entry.split('\n').count() {
- whole += 1;
- } else if lines > 0 {
- out.push_str("\n[…]");
- cut_short = true;
+impl MemoryTool {
+ /// A tool bound to `config`'s configured memory engine.
+ #[must_use]
+ pub fn new(config: Arc<Config>) -> Self {
+ Self {
+ config,
+ budget: RunBudget::new(Arc::new(TokioClock::default())),
}
- break;
}
- let left = entries.len() - whole - usize::from(cut_short);
- if left > 0 || cut_short {
- let shortened = if cut_short {
- ", the last one shortened,"
- } else {
- ""
- };
- out.push_str(&format!(
- "\n\n({left} more memory entries left out{shortened} to keep this under about \
- {EVIDENCE_TOKENS} tokens; search again with more specific words to see \
- others.)"
- ));
- }
- tracing::debug!(
- entries = entries.len(),
- whole,
- cut_short,
- "[memory:tool] recall evidence capped"
- );
- out.push_str(closing);
- out
-}
-/// Runs one action. Errors become a model-visible tool error, never a hard
-/// failure, so the model can adapt (memory off, unsupported mode, …).
-pub async fn run_action(
- ctx: &DispatchCtx,
- config: &Config,
- args: &Value,
- facts: &CallFacts,
-) -> ToolResult {
- let action = arg_str(args, "action").unwrap_or_default();
- tracing::debug!(action = %action, "[memory:tool] dispatch");
- let result: Result<Value, String> = match action.as_str() {
- // The agent answers from the evidence itself, so recall writes no
- // answer of its own; and the thread the call runs in is left out of
- // recall and fetch, since its user turn is logged before the tool
- // reads and would otherwise come back as a memory.
- "recall" => match parse::<RecallParams>(args) {
- Ok(mut params) => {
- confine(&mut params.filter, facts);
- // How much recall reads is the host's call, not the model's.
- params.limit = None;
- let question = params.question.clone();
- ops::recall_with(config, params, RecallMode::Evidence, calling_thread(facts))
- .await
- .map(|view| {
- if let Some(thread_id) = facts.thread_id.as_deref() {
- record_turn_citations(ctx, thread_id, &view.citations);
- }
- BUS.publish(DomainEvent::MemoryRecalled {
- query: question,
- hit_count: view.citations.len(),
- thread_id: facts.chat.as_ref().map(|chat| chat.thread_id.clone()),
- client_id: facts.chat.as_ref().map(|chat| chat.client_id.clone()),
- });
- evidence_json(&view)
- })
- .map_err(render_error)
- }
- Err(error) => Err(error),
- },
- "fetch" => match parse::<FetchParams>(args) {
- Ok(mut params) => {
- confine(&mut params.filter, facts);
- // Five at a time, always; more come through `cursor`.
- params.limit = Some(FETCH_TOP);
- ops::fetch_with(config, params, calling_thread(facts))
- .await
- .map(|view| {
- let mut out =
- json!({ "matches": fetch_page(&view), "items": view.hits.len() });
- if let Some(cursor) = view.next_cursor {
- out["next_cursor"] = json!(cursor);
- }
- out
- })
- .map_err(render_error)
- }
- Err(error) => Err(error),
- },
- "learn" => match parse::<LearnParams>(args) {
- Ok(mut params) => {
- params.meta = None;
- let kind = params.kind.unwrap_or(tinymemory_api::LearningKind::Fact);
- // Accepted, not visible: indexing can take minutes on a
- // hosted engine and the turn must not wait for it.
- ops::learn_with(
- config,
- params,
- Some(facts.learn_meta()),
- tinymemory_api::WriteOptions::accepted(),
+ async fn call_with_facts(
+ &self,
+ args: Value,
+ dispatch: DispatchCtx,
+ facts: CallFacts,
+ run_id: Option<&str>,
+ ) -> ToolResult {
+ let call = async {
+ let mut scope = facts.native_scope(&self.config);
+ let write_sink = Arc::new(super::tool_writes::HostWriteSink::new(self.config.clone()));
+ let single = if is_write_action(&args) {
+ SingleTool::queued(MEMORY_TOOL_NAME, scope, write_sink)
+ } else {
+ if let Err(error) = super::ops::saas_confinement(
+ &self.config,
+ tinymemory_tools::confine::Policy::Clamp,
)
- .await
- .map(|view| {
- BUS.publish(DomainEvent::MemoryStored {
- key: view.id.clone(),
- category: kind.as_str().to_string(),
- namespace: "learnings".to_string(),
- thread_id: facts.chat.as_ref().map(|chat| chat.thread_id.clone()),
- client_id: facts.chat.as_ref().map(|chat| chat.client_id.clone()),
- });
- json!({"id": view.id, "status": LEARN_STATUS})
+ .and_then(|confinement| {
+ confinement
+ .map(|confinement| confinement.reach(scope.reach.clone()))
+ .transpose()
})
- .map_err(render_error)
- }
- Err(error) => Err(error),
- },
- "forget" => match parse::<ForgetParams>(args) {
- Ok(mut params) => {
- params.reach = Some(facts.reach.clone());
- ops::forget(config, params)
+ .map(|reach| {
+ if let Some(reach) = reach {
+ scope.reach = Some(reach);
+ }
+ }) {
+ return ToolResult::error(render_error(error));
+ }
+ let engine = match super::engine::resolve(&self.config).engine() {
+ Ok(bound) => bound.engine,
+ Err(error) => return ToolResult::error(render_error(error)),
+ };
+ SingleTool::new(MEMORY_TOOL_NAME, MemoryTools::with_scope(engine, scope))
+ .with_write_sink(write_sink)
+ };
+ let call_args = args.clone();
+ let thread_window = facts.in_prompt.clone();
+ let call = async move {
+ single
+ .call_with_details(call_args, CallContext { thread_window })
+ .await
+ };
+ let outcome = if is_write_action(&args) {
+ let runtime = tokio::runtime::Handle::current();
+ match dispatch
+ .spawn_blocking(move || runtime.block_on(call))
.await
- .map(|view| json!(view))
- .map_err(render_error)
+ {
+ Ok(result) => result,
+ Err(_) => {
- return ToolResult::error(render_error(tinymemory_api::Error::Unavailable(
- "memory write queue unavailable".into(),
- )))
++ return ToolResult::error(render_error(
++ tinymemory_api::Error::Unavailable(
++ "memory write queue unavailable".into(),
++ ),
++ ));
+ }
+ }
+ } else {
+ call.await
+ };
+ let outcome = match outcome {
+ Ok(outcome) => outcome,
+ Err(error) => return ToolResult::error(render_error(error)),
+ };
+ if let Some(recall) = outcome.recall {
+ if let Some(thread_id) = facts.thread_id.as_deref() {
+ crate::web_chat::citations::record_recall_citations(
+ &dispatch,
+ thread_id,
+ &recall.citations,
+ );
+ }
+ BUS.publish(DomainEvent::MemoryRecalled {
+ query: recall.question,
+ hit_count: recall.citations.len(),
+ thread_id: facts.chat.as_ref().map(|chat| chat.thread_id.clone()),
+ client_id: facts.chat.as_ref().map(|chat| chat.client_id.clone()),
+ });
}
- Err(error) => Err(error),
- },
- other => Err(format!(
- "unknown action `{other}`; use one of recall, fetch, learn, forget"
- )),
- };
- match result {
- Ok(value) => ToolResult::success(value.to_string()),
- Err(message) => ToolResult::error(message),
- }
-}
+ if is_write_action(&args) {
+ super::tool_writes::schedule(&dispatch, self.config.clone(), &facts.reach.at);
+ }
+ ToolResult::success(outcome.value.to_string())
+ };
-/// What `fetch` shows the model: its top matches as dated lines, best first,
-/// each with the id `forget` takes. The engine's `next_cursor`, when there
-/// is one, rides beside this text; the tool description says how to use it.
-fn fetch_page(view: &super::types::FetchView) -> String {
- let mut out = match view.hits.len() {
- 0 => "Nothing in memory matches.".to_string(),
- 1 => "1 match.".to_string(),
- n => format!("Top {n} matches, best first."),
- };
- for hit in &view.hits {
- out.push_str("\n\n");
- if let Some(at) = hit.meta.observed_at {
- out.push_str(&format!("[{}] ", at.format("%Y-%m-%d %H:%M UTC")));
- }
- match hit.kind {
- tinymemory_api::ItemKind::Learning => out.push_str("learning: "),
- tinymemory_api::ItemKind::Document => out.push_str("document: "),
- tinymemory_api::ItemKind::Conversation => {}
+ if is_write_action(&args) {
+ call.await
+ } else {
+ match self.budget.run(run_id, call).await {
+ Ok(result) => result,
+ Err(refusal) => budget_refusal(refusal),
+ }
}
- out.push_str(hit.text.trim());
- out.push_str(&format!("\n(id {})", hit.id));
}
- tracing::debug!(
- hits = view.hits.len(),
- "[memory:tool] fetch matches rendered"
- );
- out
-}
-
-/// Confines a model-supplied filter to the calling agent's reach.
-fn confine(filter: &mut Option<tinymemory_api::MetaFilter>, facts: &CallFacts) {
- filter.get_or_insert_with(Default::default).reach = Some(facts.reach.clone());
-}
-
-fn render_error(error: MemoryError) -> String {
- format!("{} ({})", error, error.code())
}
#[async_trait]
@@@ -297,39 -588,10 +299,38 @@@ impl Tool for MemoryTool
}
}
-#[cfg(test)]
-#[path = "tools_tests.rs"]
-mod tests;
+fn render_error(error: tinymemory_api::Error) -> String {
+ format!("{} ({})", error, error.code())
+}
+
+fn budget_refusal(refusal: Refusal) -> ToolResult {
+ match refusal {
+ Refusal::Denied(reason) => {
+ let message = match reason {
+ tinymemory_tools::DenialReason::TrackingFull => {
+ format!("Memory is busy with other runs. {CONTINUE_WITHOUT_MEMORY}")
+ }
+ _ => format!("Memory budget exhausted for this run. {CONTINUE_WITHOUT_MEMORY}"),
+ };
- ToolResult::error(message)
- .with_metadata(json!({ REFUSAL_METADATA_KEY: "refused" }))
++ ToolResult::error(message).with_metadata(json!({ REFUSAL_METADATA_KEY: "refused" }))
+ }
+ Refusal::TimedOut => ToolResult::error(format!(
+ "Memory did not finish within its latency budget and is unavailable for this run. {CONTINUE_WITHOUT_MEMORY}"
+ )),
+ }
+}
+
+/// Whether a call was refused before TinyMemory started its action.
+pub fn is_budget_refusal(result: &ToolResult) -> bool {
+ result
+ .metadata
+ .as_ref()
+ .is_some_and(|metadata| metadata.get(REFUSAL_METADATA_KEY).is_some())
+}
+#[cfg(test)]
+#[path = "tools_activity_tests.rs"]
+mod activity_tests;
#[cfg(test)]
#[path = "tools_agent_tests.rs"]
mod agent_tests;
diff --cc crates/openhuman-core/src/memory/tools_offline_tests.rs
index 85d2a98125,0000000000..f9c6e89283
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/tools_offline_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_offline_tests.rs
@@@ -1,63 -1,0 +1,65 @@@
+use super::*;
+use crate::memory::test_fixtures::config_in;
+
+fn text(result: &ToolResult) -> String {
+ result.text()
+}
+
+#[tokio::test]
+async fn queued_writes_work_without_an_available_engine_but_not_when_explicitly_disabled() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ assert!(!crate::memory::engine::switched_off(&config));
+ assert!(
+ !crate::memory::engine::is_on(&config),
+ "the fixture has no credential or installed engine"
+ );
+ let facts = CallFacts::gather(&config, None);
+ let tool = MemoryTool::new(Arc::new(config.clone()));
+ let learned = tool
+ .execute(json!({"action":"learn","text":"queued while offline"}))
+ .await
+ .unwrap();
+ let forgotten = tool
+ .execute(json!({"action":"forget","ids":["offline-item"]}))
+ .await
+ .unwrap();
+ assert!(!learned.is_error, "learn: {}", text(&learned));
+ assert!(!forgotten.is_error, "forget: {}", text(&forgotten));
+ let pending = crate::memory::tool_writes::tests::queued_for(&config, &facts).unwrap();
+ assert_eq!(
+ pending.len(),
+ 2,
+ "both operations must be durable in the outbox"
+ );
+ assert!(matches!(
+ &pending[0].operation,
+ tinymemory_tools::pending::WriteOperation::Learn { .. }
+ ));
+ assert!(matches!(
+ &pending[1].operation,
+ tinymemory_tools::pending::WriteOperation::Forget { .. }
+ ));
- assert!(pending
- .iter()
- .all(|entry| entry.scope_root == facts.reach.at));
++ assert!(
++ pending
++ .iter()
++ .all(|entry| entry.scope_root == facts.reach.at)
++ );
+
+ let mut disabled = config.clone();
+ disabled.components.memory = false;
+ let disabled_tool = MemoryTool::new(Arc::new(disabled.clone()));
+ for args in [
+ json!({"action":"learn","text":"must not queue"}),
+ json!({"action":"forget","ids":["offline-item"]}),
+ ] {
+ let result = disabled_tool.execute(args).await.unwrap();
+ assert!(result.is_error, "explicit disable must reject the write");
+ }
+ let after_disabled = crate::memory::tool_writes::tests::queued_for(
+ &disabled,
+ &CallFacts::gather(&disabled, None),
+ )
+ .unwrap();
+ assert_eq!(after_disabled, pending, "disabled memory must not append");
+}
diff --cc crates/openhuman-core/src/memory/tools_saas_tests.rs
index 1a4e76739e,0000000000..39c1f5e382
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/tools_saas_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_saas_tests.rs
@@@ -1,258 -1,0 +1,266 @@@
+use super::*;
+use crate::config::schema::MemoryAgentConfig;
+use crate::memory::test_fixtures::config_in;
+use std::sync::{
- atomic::{AtomicUsize, Ordering},
+ Arc,
++ atomic::{AtomicUsize, Ordering},
+};
+use tinymemory_api::conformance::ReferenceEngine;
+use tinymemory_api::{
+ EngineDescriptor, FetchPage, FetchRequest, ForgetReport, ForgetTarget, LearningKind, ListPage,
+ ListRequest, MemoryEngine, MemoryMeta, Namespace, RecallAnswer, RecallRequest, StoreItem,
+ StoreReceipt,
+};
+
+struct CountingReadEngine {
+ inner: ReferenceEngine,
+ reads: Arc<AtomicUsize>,
+}
+
+#[async_trait::async_trait]
+impl MemoryEngine for CountingReadEngine {
+ fn descriptor(&self) -> &EngineDescriptor {
+ self.inner.descriptor()
+ }
+
+ async fn health(&self) -> tinymemory_api::EngineHealth {
+ self.inner.health().await
+ }
+
+ async fn recall(&self, request: RecallRequest) -> tinymemory_api::Result<RecallAnswer> {
+ self.reads.fetch_add(1, Ordering::SeqCst);
+ self.inner.recall(request).await
+ }
+
+ async fn fetch(&self, request: FetchRequest) -> tinymemory_api::Result<FetchPage> {
+ self.reads.fetch_add(1, Ordering::SeqCst);
+ self.inner.fetch(request).await
+ }
+
+ async fn store(&self, item: StoreItem) -> tinymemory_api::Result<StoreReceipt> {
+ self.inner.store(item).await
+ }
+
+ async fn forget(&self, target: ForgetTarget) -> tinymemory_api::Result<ForgetReport> {
+ self.inner.forget(target).await
+ }
+
+ async fn list(&self, request: ListRequest) -> tinymemory_api::Result<ListPage> {
+ self.inner.list(request).await
+ }
+}
+
+fn tool_context_for(agent_id: &str) -> tinyagents_harness::tool::ToolExecutionContext {
+ let mut host = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ host.memory_identity = Some(tinymemory_tools::layout::identity::Identity::agent(
+ agent_id,
+ ));
+ let run = host.into_tinyagents(tinyagents_harness::context::RunConfig::new("saas-memory"));
+ tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &run,
+ tinyagents_harness::ids::CallId::new("saas-memory-call"),
+ )
+}
+
+fn isolate(test_name: &str, marker: &str) -> Option<std::process::Output> {
+ if std::env::var_os(marker).is_some() {
+ None
+ } else {
+ Some(
+ std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", test_name, "--nocapture"])
+ .env(marker, "1")
+ .output()
+ .unwrap(),
+ )
+ }
+}
+
+#[test]
+fn invalid_saas_roots_and_agent_overrides_reject_memory_tool_reads() {
+ const MARKER: &str = "OPENHUMAN_TEST_SAAS_MEMORY_TOOL_INVALID_ROOT";
+ const TEST_NAME: &str = "memory::tools::saas_tests::invalid_saas_roots_and_agent_overrides_reject_memory_tool_reads";
+ if let Some(output) = isolate(TEST_NAME, MARKER) {
+ assert!(
+ output.status.success()
+ && String::from_utf8_lossy(&output.stdout)
+ .contains("SAAS_MEMORY_TOOL_INVALID_ROOT_CHILD_PASSED"),
+ "isolated SaaS tool root test failed or ran zero tests:\n{}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+
+ crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async {
+ for root in [None, Some("not a namespace!"), Some("root")] {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = root.map(str::to_string);
+ config.memory.agents.insert(
+ "scout".into(),
+ MemoryAgentConfig {
+ root: Some("team:foreign".into()),
+ ..MemoryAgentConfig::default()
+ },
+ );
+ let inner = ReferenceEngine::new();
+ inner
+ .store(StoreItem::learning(
+ "foreign marker that must stay unread",
+ LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: "team:foreign".parse().unwrap(),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+ let reads = Arc::new(AtomicUsize::new(0));
+ crate::memory::engine::install_test_engine(
+ &config.workspace_dir,
+ Arc::new(CountingReadEngine {
+ inner,
+ reads: reads.clone(),
+ }),
+ );
+ let tool = MemoryTool::new(Arc::new(config.clone()));
+ let context = tool_context_for("scout");
+ for args in [
+ json!({"action":"recall","question":"foreign marker"}),
+ json!({"action":"fetch","query":"foreign marker"}),
+ ] {
+ let result = tool
+ .execute_with_context(args, ToolCallOptions::default(), Some(&context))
+ .await
+ .unwrap();
+ assert!(result.is_error, "root {root:?}: {}", result.text());
+ assert!(
+ result
+ .text()
+ .contains("memory is unavailable: this agent has no valid memory root"),
+ "root {root:?}: {}",
+ result.text()
+ );
+ }
+ assert_eq!(reads.load(Ordering::SeqCst), 0, "root {root:?}");
+ }
+ });
+ println!("SAAS_MEMORY_TOOL_INVALID_ROOT_CHILD_PASSED");
+}
+
+#[test]
+fn valid_saas_root_keeps_tool_reads_inside_the_authenticated_namespace() {
+ const MARKER: &str = "OPENHUMAN_TEST_SAAS_MEMORY_TOOL_VALID_ROOT";
+ const TEST_NAME: &str = "memory::tools::saas_tests::valid_saas_root_keeps_tool_reads_inside_the_authenticated_namespace";
+ if let Some(output) = isolate(TEST_NAME, MARKER) {
+ assert!(
+ output.status.success()
+ && String::from_utf8_lossy(&output.stdout)
+ .contains("SAAS_MEMORY_TOOL_VALID_ROOT_CHILD_PASSED"),
+ "isolated SaaS tool clamp test failed or ran zero tests:\n{}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+
+ crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.root = Some("team:acme".into());
+ config.memory.agents.insert(
+ "scout".into(),
+ MemoryAgentConfig {
+ root: Some("team:foreign".into()),
+ ..MemoryAgentConfig::default()
+ },
+ );
+ let inner = ReferenceEngine::new();
+ for (namespace, text) in [
+ ("team:acme", "acme boundary marker"),
+ ("team:foreign", "foreign boundary marker"),
+ ] {
+ inner
+ .store(StoreItem::learning(
+ text,
+ LearningKind::Fact,
+ 0.9,
+ MemoryMeta {
+ namespace: namespace.parse::<Namespace>().unwrap(),
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+ }
+ let reads = Arc::new(AtomicUsize::new(0));
+ crate::memory::engine::install_test_engine(
+ &config.workspace_dir,
+ Arc::new(CountingReadEngine {
+ inner,
+ reads: reads.clone(),
+ }),
+ );
+ let tool = MemoryTool::new(Arc::new(config));
+ let context = tool_context_for("scout");
+ let recall = tool
+ .execute_with_context(
+ json!({"action":"recall","question":"acme boundary marker"}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ assert!(!recall.is_error, "{}", recall.text());
+ let evidence: Value = serde_json::from_str(&recall.text()).unwrap();
- assert!(evidence["evidence"]
- .as_str()
- .unwrap()
- .contains("acme boundary marker"));
- assert!(!evidence["evidence"]
- .as_str()
- .unwrap()
- .contains("foreign boundary marker"));
++ assert!(
++ evidence["evidence"]
++ .as_str()
++ .unwrap()
++ .contains("acme boundary marker")
++ );
++ assert!(
++ !evidence["evidence"]
++ .as_str()
++ .unwrap()
++ .contains("foreign boundary marker")
++ );
+
+ let fetch = tool
+ .execute_with_context(
+ json!({"action":"fetch","query":"boundary marker"}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ assert!(!fetch.is_error, "{}", fetch.text());
+ let page: Value = serde_json::from_str(&fetch.text()).unwrap();
- assert!(page["matches"]
- .as_str()
- .unwrap()
- .contains("acme boundary marker"));
- assert!(!page["matches"]
- .as_str()
- .unwrap()
- .contains("foreign boundary marker"));
++ assert!(
++ page["matches"]
++ .as_str()
++ .unwrap()
++ .contains("acme boundary marker")
++ );
++ assert!(
++ !page["matches"]
++ .as_str()
++ .unwrap()
++ .contains("foreign boundary marker")
++ );
+ assert_eq!(reads.load(Ordering::SeqCst), 2);
+ });
+ println!("SAAS_MEMORY_TOOL_VALID_ROOT_CHILD_PASSED");
+}
diff --cc crates/openhuman-core/src/memory/tools_test_support.rs
index 1ca289bf2a,0000000000..63b0a93362
mode 100644,000000..100644
--- a/crates/openhuman-core/src/memory/tools_test_support.rs
+++ b/crates/openhuman-core/src/memory/tools_test_support.rs
@@@ -1,23 -1,0 +1,23 @@@
+//! Shared test adapters for the memory tool's native facade.
+
- use super::{is_write_action, CallFacts, MemoryTool};
++use super::{CallFacts, MemoryTool, is_write_action};
+use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
+use serde_json::Value;
+use std::sync::Arc;
+use tinytools::ToolResult;
+
+pub(super) async fn run_action(
+ ctx: &DispatchCtx,
+ config: &Config,
+ args: &Value,
+ facts: &CallFacts,
+) -> ToolResult {
+ let result = MemoryTool::new(Arc::new(config.clone()))
+ .call_with_facts(args.clone(), ctx.clone(), facts.clone(), None)
+ .await;
+ if is_write_action(args) && !result.is_error {
+ crate::memory::tool_writes::tests::drain_for(config, &facts.reach.at).await;
+ }
+ result
+}
diff --cc crates/openhuman-core/src/memory/tools_tests.rs
index 4006bfce81,c090a94638..568dc97f0b
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@@ -444,21 -403,15 +444,23 @@@ async fn learnings_are_shared_under_a_r
&member(),
)
.await;
+ assert!(!forgot.is_error, "{}", forgot.text());
+ let ack: Value = serde_json::from_str(&forgot.text()).unwrap();
+ assert_eq!(ack["queued"], 1);
+ assert_eq!(ack["status"], "queued; not yet removed from memory");
+ let after_forget = stored(&engine, MetaFilter::default()).await;
+ assert_eq!(
+ after_forget.len(),
+ 3,
+ "all identity-scoped learnings remain"
+ );
+ assert!(after_forget.iter().any(|hit| hit.id == main_item.id));
+ assert!(after_forget.iter().any(|hit| hit.text.contains("arxiv")));
- assert!(after_forget
- .iter()
- .any(|hit| hit.text.contains("british english")));
+ assert!(
- forgot.text().contains("\"forgotten\":0"),
- "{}",
- forgot.text()
++ after_forget
++ .iter()
++ .any(|hit| hit.text.contains("british english"))
+ );
- assert!(stored(&engine, MetaFilter::default())
- .await
- .iter()
- .all(|hit| hit.meta.namespace != Namespace::agent("nobody")));
}
/// The reference engine, recording how far each single store waited.
diff --cc crates/openhuman-embed/src/host_internals.rs
index fd46c62768,7a38f2d59d..6651bc12c7
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@@ -20,16 -20,16 +20,16 @@@ pub use openhuman_core::run_core_from_a
/// Shared by tinyhumans (hosted controllers) and rpc (`http_host`, `/health`).
pub mod core {
pub use openhuman_core::core::{
-- unwrap_rpc, ControllerSchema, FieldSchema, Outcome, StructuredRpcError, TypeSchema,
++ ControllerSchema, FieldSchema, Outcome, StructuredRpcError, TypeSchema, unwrap_rpc,
};
pub mod all {
// tinyhumans: hosted controller extension; rpc: http_host + `/health`.
pub use openhuman_core::core::all::{
++ ControllerExtension, ControllerFuture, DomainGroup, RegisteredController,
all_controller_schemas, all_http_method_schemas, cli_handler_for_namespace,
namespace_description, register_controller_extension, rpc_method_from_parts,
-- schema_for_rpc_method, ControllerExtension, ControllerFuture, DomainGroup,
-- RegisteredController,
++ schema_for_rpc_method,
};
}
@@@ -37,30 -37,31 +37,31 @@@
/// RPC handler and classifier (rpc).
pub mod observability {
pub use openhuman_core::core::observability::{
++ API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, ExpectedErrorKind,
++ REPORT_ERROR_TRACING_TARGET, USAGE_PROBE_BACKOFF_PREFIX,
contains_transient_transport_phrase, expected_error_kind, is_api_key_rejected_message,
is_session_expired_message, is_suppressed_usage_probe_backoff,
- is_transient_http_status_code, is_transient_message_failure, report_error_or_expected,
- report_warning_message, ExpectedErrorKind, API_KEY_REJECTED_PREFIX,
- BACKEND_UNAVAILABLE_PREFIX, REPORT_ERROR_TRACING_TARGET,
+ is_transient_http_status_code, is_transient_message_failure, report_error,
- report_error_or_expected, report_warning_message, ExpectedErrorKind,
- API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, REPORT_ERROR_TRACING_TARGET,
- USAGE_PROBE_BACKOFF_PREFIX,
++ report_error_or_expected, report_warning_message,
};
}
// rpc server only, below.
pub mod auth {
pub use openhuman_core::core::auth::{
-- bearer_matches, get_rpc_token, init_rpc_token, init_rpc_token_with_value,
-- verify_bearer_token, CORE_TOKEN_ENV_VAR,
++ CORE_TOKEN_ENV_VAR, bearer_matches, get_rpc_token, init_rpc_token,
++ init_rpc_token_with_value, verify_bearer_token,
};
}
pub mod bus {
-- pub use openhuman_core::core::bus::{init, BUS};
++ pub use openhuman_core::core::bus::{BUS, init};
}
pub mod cli {
pub use openhuman_core::core::cli::load_dotenv_for_cli;
}
pub mod dispatch {
pub use openhuman_core::core::dispatch::{
-- is_known_probe_method, unknown_method_name, UNKNOWN_METHOD_PREFIX,
++ UNKNOWN_METHOD_PREFIX, is_known_probe_method, unknown_method_name,
};
}
pub mod event_bind_tokens {
@@@ -80,14 -81,14 +81,14 @@@
}
pub mod runtime {
pub use openhuman_core::core::runtime::{
-- current_tenant, is_saas, CoreContext, CoreRuntime, DispatchCtx, Mode, SaasConfig,
++ CoreContext, CoreRuntime, DispatchCtx, Mode, SaasConfig, current_tenant, is_saas,
};
pub mod saas {
pub use openhuman_core::core::runtime::saas::build;
}
}
pub mod server_launcher {
-- pub use openhuman_core::core::server_launcher::{install_server_launcher, ServeRequest};
++ pub use openhuman_core::core::server_launcher::{ServeRequest, install_server_launcher};
}
pub mod session_expiry {
pub use openhuman_core::core::session_expiry::is_session_expired_error;
@@@ -103,28 -109,15 +109,15 @@@
/// tinyhumans (every hosted controller loads its config) and rpc (server).
pub mod config {
pub use openhuman_core::config::{
-- active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot,
- load_config_with_timeout, workspace_handle, Config,
++ Config, MODEL_MANAGED_DEFAULT, PrivacyMode, active_workspace_dir,
++ active_workspace_dir_cached, active_workspace_snapshot,
+ build_runtime_proxy_client_with_timeouts, load_config_with_timeout, workspace_handle,
- Config, PrivacyMode, MODEL_MANAGED_DEFAULT,
};
pub mod app_env {
// tinyhumans: backend URL selection.
pub use openhuman_core::config::app_env::{
-- app_env_from_env, is_staging_app_env, APP_ENV_VAR, VITE_APP_ENV_VAR,
++ APP_ENV_VAR, VITE_APP_ENV_VAR, app_env_from_env, is_staging_app_env,
};
}
pub mod ops {
@@@ -166,9 -169,9 +169,9 @@@ pub mod agent
}
}
pub mod session_store {
- pub use openhuman_core::agent::session_store::{
- context_workspace_dir, install, installed, restore, ReboundSessionStores,
- WorkspaceSessionStores,
+ pub use openhuman_core::storage::sessions::{
- context_workspace_dir, install, installed, restore, ReboundSessionStores,
- WorkspaceSessionStores,
++ ReboundSessionStores, WorkspaceSessionStores, context_workspace_dir, install,
++ installed, restore,
};
}
}
@@@ -185,8 -188,8 +188,8 @@@ pub mod channels
pub mod inference {
pub mod embedding_host {
pub use openhuman_core::inference::embedding_host::{
-- default_embedding_provider_for_chat, default_embedding_provider_with_config,
-- SharedEmbeddingModel,
++ SharedEmbeddingModel, default_embedding_provider_for_chat,
++ default_embedding_provider_with_config,
};
}
pub mod provider {
@@@ -195,9 -198,9 +198,9 @@@
}
}
pub mod http {
++ pub use openhuman_core::inference::http::EXTERNAL_OPENAI_COMPAT_PROVIDER;
#[cfg(feature = "http-server")]
pub use openhuman_core::inference::http::router;
-- pub use openhuman_core::inference::http::EXTERNAL_OPENAI_COMPAT_PROVIDER;
}
}
@@@ -219,16 -210,16 +222,16 @@@ pub mod security
/// Host-supplied secret storage and encryption-key sources.
pub mod secret_storage {
pub use openhuman_core::security::secret_storage::{
++ EncryptedFileBackend, MasterKeySource, SecretBackend, SecretStorageError,
clear_master_key_source, clear_secret_backend, init_workspace,
install_master_key_source, install_secret_backend, installed_master_key_source,
installed_secret_backend, is_available, store::workspace_dir_for_file_backend,
-- EncryptedFileBackend, MasterKeySource, SecretBackend, SecretStorageError,
};
}
pub mod credentials {
pub use openhuman_core::security::credentials::{
-- channel_credential_provider, AuthService, APP_SESSION_PROVIDER,
-- DEFAULT_AUTH_PROFILE_NAME,
++ APP_SESSION_PROVIDER, AuthService, DEFAULT_AUTH_PROFILE_NAME,
++ channel_credential_provider,
};
pub mod ops {
pub use openhuman_core::security::credentials::ops::{
@@@ -237,8 -228,16 +240,16 @@@
}
pub mod session_support {
pub use openhuman_core::security::credentials::session_support::{
- build_session_state, current_session_is_local, resolve_backend_credential,
- build_session_state, classify_session_token, current_session_is_local,
- get_session_token, is_local_session_token, load_app_session_profile,
- publish_local_session_expiry, resolve_backend_credential, BackendCredential,
- SessionTokenCheck, LOCAL_SESSION_BACKEND_UNAVAILABLE,
+ BackendCredential, LOCAL_SESSION_BACKEND_UNAVAILABLE,
+ LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE, SESSION_EXPIRES_AT_META,
++ SessionTokenCheck, build_session_state, classify_session_token,
++ current_session_is_local, get_session_token, is_local_session_token,
++ load_app_session_profile, publish_local_session_expiry, resolve_backend_credential,
+ };
+ }
+ pub mod api_key {
+ pub use openhuman_core::security::credentials::api_key::{
+ get_api_key_in, store_api_key, store_api_key_in,
};
}
}
@@@ -267,6 -274,142 +286,142 @@@ pub mod util
}
}
+ // ---------------------------------------------------------------------------
+ // Extension points (tinyhumans). Generic, id-keyed registries the hosted layer
+ // fills at install time; the core knows nothing about what it is handed. Each
+ // `register_*` has an `_in` variant that binds to a `CoreBuilder::extensions`
+ // set instead of the process.
+ // ---------------------------------------------------------------------------
+
+ /// Tool sources: tools an outside crate appends to the agent catalogue.
+ pub mod tool_sources {
+ pub use openhuman_core::tools::sources::{
- register_tool_source, register_tool_source_at, register_tool_source_in,
- registered_tool_source_placements, unregister_tool_source, ToolSourceCtx,
- ToolSourceFactory, ToolSourcePlacement, ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH,
++ ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH, ToolSourceCtx, ToolSourceFactory,
++ ToolSourcePlacement, register_tool_source, register_tool_source_at,
++ register_tool_source_in, registered_tool_source_placements, unregister_tool_source,
+ };
+ }
+
+ /// The artifact publisher slot: the service that shares an artifact version.
+ pub mod artifact_publisher {
+ pub use openhuman_core::artifacts::{
- register_artifact_publisher, register_artifact_publisher_in, unregister_artifact_publisher,
- ArtifactPublisherFactory,
++ ArtifactPublisherFactory, register_artifact_publisher, register_artifact_publisher_in,
++ unregister_artifact_publisher,
+ };
+ // tinyhumans file-storage publisher: the protected-path guard it re-checks
+ // before upload, and the store its tests save artifacts into.
+ pub use openhuman_core::artifacts::tiny_store::{
+ refused_path, version_files_dir, versioned_store,
+ };
+ }
+
+ /// Egress disclosure, for hosted calls that leave the machine.
+ pub mod egress {
+ pub use openhuman_core::security::egress::{
- emit_external_transfer, emit_external_transfer_in, enforce_egress, local_only_blocks,
+ DataKind, EgressDescriptor, EgressLedger, EgressReason, IdentificationRisk,
++ emit_external_transfer, emit_external_transfer_in, enforce_egress, local_only_blocks,
+ };
+ }
+
+ /// Config enrichers and the resolved fields they fill.
+ pub mod config_enrichers {
+ pub use openhuman_core::config::schema::resolved_endpoints::ResolvedEndpoints;
+ pub use openhuman_core::config::{
- register_enricher, register_enricher_in, run_enrichers, unregister_enricher, ConfigEnricher,
++ ConfigEnricher, register_enricher, register_enricher_in, run_enrichers, unregister_enricher,
+ };
+ }
+
+ /// Composio route builders (`composio.mode` -> route).
+ pub mod composio {
+ pub use openhuman_core::integrations::composio::client::{
- register_composio_route_builder, unregister_composio_route_builder, ComposioRoute,
- ComposioRouteBuilder,
++ ComposioRoute, ComposioRouteBuilder, register_composio_route_builder,
++ unregister_composio_route_builder,
+ };
+ // The proxy route's target (origin + bearer) for `composio.mode = backend`.
+ #[cfg(feature = "modules")]
+ pub use openhuman_core::modules::connectors::{
- register_proxy_target, unregister_proxy_target, ProxyTarget, ProxyTargetResolver,
++ ProxyTarget, ProxyTargetResolver, register_proxy_target, unregister_proxy_target,
+ };
+ }
+
+ /// Media-generation tool building over host-supplied generators (tinyhumans).
+ #[cfg(feature = "media")]
+ pub mod media {
+ pub mod generation {
+ pub use openhuman_core::media::generation::{
- media_tools_for_config, GeneratorRouter, MediaGenerators, MediaReferenceAllowlist,
++ GeneratorRouter, MediaGenerators, MediaReferenceAllowlist, media_tools_for_config,
+ };
+ }
+ }
+
+ /// The wallet module's authenticated backend hook (tinyhumans web3).
+ #[cfg(feature = "web3")]
+ pub mod wallet_backend {
+ pub use openhuman_core::modules::wallet_backend::{
- register_wallet_backend, register_wallet_backend_in, unregister_wallet_backend,
- WalletBackendCall, WalletBackendFuture, WalletBackendHandler,
++ WalletBackendCall, WalletBackendFuture, WalletBackendHandler, register_wallet_backend,
++ register_wallet_backend_in, unregister_wallet_backend,
+ };
+ }
+
+ /// Model-provider registries: chat models, embeddings, catalogs.
+ pub mod inference_registry {
+ pub use openhuman_core::inference::provider::factory::PROVIDER_OPENHUMAN;
+ pub use openhuman_core::inference::provider::openhuman_backend_model::REASONING_OFF_METADATA_KEY;
+ pub use openhuman_core::inference::registry::{
++ BoxFuture, CatalogEntry, CatalogLimits, CatalogListing, CatalogRequest, ChatModelEntry,
++ ChatModelFactory, ChatModelRequest, EmbeddingFactory, EmbeddingRequest, ReadinessProbe,
+ register_catalog, register_catalog_in, register_chat_model, register_chat_model_in,
+ register_embedding, register_embedding_in, unregister_catalog, unregister_chat_model,
- unregister_embedding, BoxFuture, CatalogEntry, CatalogLimits, CatalogListing,
- CatalogRequest, ChatModelEntry, ChatModelFactory, ChatModelRequest, EmbeddingFactory,
- EmbeddingRequest, ReadinessProbe,
++ unregister_embedding,
+ };
+ }
+
+ /// Memory engines by id, and the free-background-work predicate.
+ pub mod memory_engines {
+ pub use openhuman_core::memory::engine::{
- build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings,
- TINYHUMANS_ENGINE,
++ BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings, TINYHUMANS_ENGINE,
++ build_cached, rooted,
+ };
+ pub use openhuman_core::memory::engine_registry::{
- bound_engine, register_memory_engine, register_memory_engine_in, unregister_memory_engine,
- EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground,
++ EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground, bound_engine,
++ register_memory_engine, register_memory_engine_in, unregister_memory_engine,
+ };
+ }
+
+ /// The channel callback slot.
+ #[cfg(feature = "channels")]
+ pub mod channel_callback {
+ pub use openhuman_core::channels::callback_slot::{
- register_channel_callback, register_channel_callback_in, unregister_channel_callback,
- CallbackFuture, ChannelCallback, ChannelCallbackCtx,
++ CallbackFuture, ChannelCallback, ChannelCallbackCtx, register_channel_callback,
++ register_channel_callback_in, unregister_channel_callback,
+ };
+ }
+
+ /// Voice provider registries: STT, TTS and live sessions by slug.
+ #[cfg(feature = "voice")]
+ pub mod voice_registry {
+ pub use openhuman_core::config::schema::voice_live::{
+ LIVE_PROVIDER_ELEVENLABS_HOSTED, LIVE_PROVIDER_GEMINI_HOSTED,
+ };
+ pub use openhuman_core::voice::factory::registry::{
- register_stt_provider, register_stt_provider_in, register_tts_provider,
- register_tts_provider_in, unregister_stt_provider, unregister_tts_provider,
- SttProviderFactory, TtsProviderFactory,
++ SttProviderFactory, TtsProviderFactory, register_stt_provider, register_stt_provider_in,
++ register_tts_provider, register_tts_provider_in, unregister_stt_provider,
++ unregister_tts_provider,
+ };
+ pub use openhuman_core::voice::factory::{
- create_stt_provider, create_tts_provider, SttProvider, SttResult, TtsProvider,
++ SttProvider, SttResult, TtsProvider, create_stt_provider, create_tts_provider,
+ };
+ pub use openhuman_core::voice::live::ops::live_providers;
+ pub use openhuman_core::voice::live::registry::{
- register_live_provider, register_live_provider_in, unregister_live_provider, ConfigureFn,
- ConfiguredFn, LiveFuture, LiveProviderEntry, LiveProviderPlacement, PrepareFn,
++ ConfigureFn, ConfiguredFn, LiveFuture, LiveProviderEntry, LiveProviderPlacement, PrepareFn,
++ register_live_provider, register_live_provider_in, unregister_live_provider,
+ };
+ pub use openhuman_core::voice::live::types::{LiveProviderInfo, LiveProviderKind};
+ pub use openhuman_core::voice::live::{
- LiveVoiceError, PreparedProvider, GEMINI_LANGUAGES, GEMINI_VOICES,
++ GEMINI_LANGUAGES, GEMINI_VOICES, LiveVoiceError, PreparedProvider,
+ };
+ }
+
// The rest is the rpc server alone.
pub mod desktop {
@@@ -290,7 -435,7 +447,7 @@@ pub mod platform
pub mod connectivity {
pub mod rpc {
pub use openhuman_core::platform::connectivity::rpc::{
-- pick_listen_port_for_host_with, OccupiedByCore,
++ OccupiedByCore, pick_listen_port_for_host_with,
};
}
}
@@@ -301,16 -446,22 +458,22 @@@
pub mod storage {
pub use openhuman_core::storage::{
-- block_on, block_on_anyhow, clear, configured_url, driver_is_shared, install,
-- install_for_url, installed, open, url_from, StorageBackend, STORAGE_URL_VAR,
++ STORAGE_URL_VAR, StorageBackend, block_on, block_on_anyhow, clear, configured_url,
++ driver_is_shared, install, install_for_url, installed, open, url_from,
};
+
+ /// The layout v1 -> v2 migration the host runs at boot when
+ /// `[storage] auto_migrate_layout` is set.
+ pub mod layout {
+ pub use openhuman_core::storage::layout::auto_migrate;
+ }
}
pub mod profiles {
pub mod gateway {
pub use openhuman_core::profiles::gateway::{
-- resolve_scope, sign, verify, GatewayRefusal, GatewayScope, HeldBy, PROFILE_HELD,
-- PROFILE_OWNER_HEADER, USER_HEADER, USER_SIG_HEADER,
++ GatewayRefusal, GatewayScope, HeldBy, PROFILE_HELD, PROFILE_OWNER_HEADER, USER_HEADER,
++ USER_SIG_HEADER, resolve_scope, sign, verify,
};
}
pub mod host {
@@@ -352,9 -490,9 +502,9 @@@ pub mod web3
pub mod web_chat {
pub use openhuman_core::web_chat::{
++ ChatRequestMetadata, GuardrailPayload, StartChatError, WebChannelEvent,
approval_request_event, cancel_chat_scoped, plan_review_request_event,
publish_web_channel_event, start_chat, subscribe_web_channel_events, unix_epoch_ms,
-- ChatRequestMetadata, GuardrailPayload, StartChatError, WebChannelEvent,
};
}
diff --cc crates/openhuman-tinyhumans/src/transport/mod.rs
index cd9806816e,aca857087b..751e63e31f
--- a/crates/openhuman-tinyhumans/src/transport/mod.rs
+++ b/crates/openhuman-tinyhumans/src/transport/mod.rs
@@@ -19,12 -12,13 +19,17 @@@ use serde_json::Value
use tinyhumans_sdk::TinyHumansClient;
mod error;
+ mod port;
+#[cfg(test)]
+#[path = "memory_bearer_tests.rs"]
+mod memory_bearer_tests;
+
pub use error::map_sdk_error;
+ pub use port::{
+ BackendRequest, BackendTransport, BackendTransportError, BaseUrlPurpose, QueryParam,
+ TransportProfile,
+ };
/// One `reqwest::Client` per [`TransportProfile`], each built from
/// [`backend_client_builder`](crate::backend::headers::backend_client_builder)
diff --cc crates/openhuman-tinyhumans/src/transport/port.rs
index d356658c44,b857492c16..95f7cdde2c
--- a/crates/openhuman-tinyhumans/src/transport/port.rs
+++ b/crates/openhuman-tinyhumans/src/transport/port.rs
@@@ -1,39 -1,13 +1,15 @@@
- //! The backend port: how the core reaches the hosted TinyHumans backend
- //! without depending on the SDK that speaks to it.
- //!
- //! The core owns the *routes* (`/payments/summary`,
- //! `/agent-integrations/...`, `channels/{c}/messages`, ...) and the error
- //! *classification* ([`crate::backend::client`], `integrations/client/errors.rs`).
- //! What it does not own is the HTTP primitive that carries a request with the
- //! right credential header shape and route policy. That is a
- //! [`BackendTransport`], and the only production implementation lives in the
- //! `openhuman-tinyhumans` crate on top of the vendored `tinyhumans-sdk`. A core
- //! built without that crate has no transport and every backend-touching call
- //! degrades to [`BackendTransportError::Unavailable`] — the core keeps running
- //! agents, memory, tools and RPC without any TinyHumans connection.
- //!
- //! See [`install`] for how a transport reaches the core at runtime.
+ //! The hosted-backend HTTP port: the request shape, the [`BackendTransport`]
+ //! trait and its typed error. Owned by this crate; the core has no backend
+ //! port. [`SdkBackendTransport`](crate::SdkBackendTransport) implements it.
use async_trait::async_trait;
- use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
+ use openhuman_embed::__host::security::credentials::session_support::BackendCredential;
+ use reqwest::header::HeaderMap;
use reqwest::Method;
use serde_json::Value;
+use std::sync::Arc;
+use tinymemory_integrations::BearerSource;
- use crate::security::credentials::session_support::BackendCredential;
-
- pub mod error;
- pub mod install;
- #[cfg(test)]
- pub mod plain;
-
- pub use error::BackendTransportError;
- pub use install::{
- clear_backend_transport, install_backend_transport, installed_backend_transport, is_installed,
- resolve_backend_transport,
- };
-
/// One `(name, value)` query pair; a `None` value omits the pair.
pub type QueryParam = (&'static str, Option<String>);
diff --cc docs/TEST-COVERAGE-MATRIX.md
index f337ff7305,ce043d844a..36a1f4d82a
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@@ -356,7 -356,7 +356,7 @@@ Spec: `docs/specs/memory-v2.md` (host)
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | -------------------------------- | ----- | ------------ | ------ | ----- |
--| 8.1.1 | Learn / store a learning | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tools_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `tests/memory_v2_e2e.rs` (`learn_list_fetch_recall_and_forget_round_trip`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Agent `learn` returns a durable local queued acknowledgement without awaiting the engine; explicit `openhuman.memory_learn` retains its RPC contract. Held-engine, scrub-before-persist, atomic owner-only storage, capacity, persistence failure, restart replay and invocation-ID deduplication regressions cover the outbox |
++| 8.1.1 | Learn / store a learning | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tools_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `crates/openhuman-core/src/memory/state_store_tests.rs`, `tests/memory_v2_e2e.rs` (`learn_list_fetch_recall_and_forget_round_trip`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Agent `learn` returns a durable local queued acknowledgement without awaiting the engine; explicit `openhuman.memory_learn` retains its RPC contract. Held-engine, scrub-before-persist, state-KV persistence, workspace isolation, capacity, persistence failure, restart replay and invocation-ID deduplication regressions cover the outbox |
| 8.1.2 | Recall (answer with citations) | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Ask chip; explicit agent-tool recall is bounded to 15 seconds per call, 30 seconds aggregate and 8 attempts while the bounded run record remains tracked; a timeout disables optional memory for the tracked run (idle records may be evicted under churn) |
| 8.1.3 | Fetch and list | RU+RI | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `tests/memory_v2_e2e.rs` | ✅ | Hybrid only on both launch engines; other modes answer `UNSUPPORTED`. Explicit agent-tool fetch shares the bounded recall budget |
| 8.1.4 | Forget | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | By id; agent-tool forget queues trusted-reach removal, preserves learn-before-forget order and retains failed writes for retry; a queued result does not claim removal |
@@@ -383,8 -383,8 +383,8 @@@
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | ----------------------------- | ----- | ------------ | ------ | ----- |
--| 8.3.1 | Conformance suite | RU | `vendor/tinymemory/crates/tinymemory-conformance/` (vendored `tinymemory`) | ✅ | Reference engine and both CortexDB wires through an HTTP double |
--| 8.3.2 | Sources, documents, safety, context, import crates | RU | `vendor/tinymemory/crates/tinymemory-{sources,documents,safety,context,import}/` (vendored `tinymemory`) | ✅ | SSRF guard, scrubbing, budgeted context, legacy reader |
++| 8.3.1 | Conformance suite | RU | `vendor/tinymemory/crates/tinymemory-api/src/conformance/` | ✅ | Reference engine and both CortexDB wires through an HTTP double |
++| 8.3.2 | Sources, documents, safety, context, import crates | RU | `vendor/tinymemory/crates/tinymemory-tools/src/`, `vendor/tinymemory/crates/tinymemory-integrations/src/` | ✅ | SSRF guard, scrubbing, budgeted context, legacy reader |
### 8.4 Chat Thread Store (not memory)
diff --cc scripts/__tests__/rust-coverage-status.test.mjs
index ec66603d7c,c2804277fb..6d92ad5a71
--- a/scripts/__tests__/rust-coverage-status.test.mjs
+++ b/scripts/__tests__/rust-coverage-status.test.mjs
@@@ -163,3 -164,327 +164,327 @@@ for (const [label, scriptPath, invoke]
);
});
}
+
+ for (const helper of [
+ "llvm_cov",
+ "llvm_cov_package",
+ "llvm_cov_product_facade",
+ ]) {
+ test(`${helper} selects nextest for private suites and rejects empty selections`, () => {
+ const result = withRunnerFunctions(
+ [helper],
+ [
+ "OH_COV_RUNNER=nextest",
+ "CORE_PRODUCT_FEATURES=channels",
+ 'bash() { printf "%s\\n" "$*"; }',
+ ].join("\n"),
+ `${helper} --no-report -p openhuman-embed --all-targets`,
+ );
+ assert.equal(result.status, 0, result.output);
+ assert.match(
+ result.output,
+ /cargo llvm-cov nextest --profile ci --no-tests=fail/,
+ );
+ assert.match(result.output, /--no-report -p openhuman-embed --all-targets/);
+ });
+ }
+
+ test("private core coverage runs sequentially without a second target directory", () => {
+ const source = fs.readFileSync(runner, "utf8");
+ assert.doesNotMatch(source, /UNIT_PID|cov-unit|export CARGO_TARGET_DIR/);
+ assert.match(source, /suite "openhuman lib\+bins \(nextest\)" llvm_cov/);
+ assert.match(source, /suite "openhuman-embed \(default\)" llvm_cov_package/);
+ assert.match(
+ source,
+ /suite "openhuman-tinyhumans \(default\)" llvm_cov_package/,
+ );
+ });
+
+ test("coverage finalizer retains interrupted reports and the cancellation status", () => {
+ const result = withRunnerFunctions(
+ ["preserve_coverage"],
+ [
+ "OUT=interrupted.info",
+ "COVERAGE_REPORTED=0",
+ 'log() { printf "%s\\n" "$*"; }',
+ 'llvm_cov() { printf "REPORT %s\\n" "$*"; return 9; }',
+ ].join("\n"),
+ "trap preserve_coverage EXIT; exit 143",
+ );
+ assert.equal(result.status, 143, result.output);
+ assert.match(
+ result.output,
+ /REPORT report --lcov --output-path interrupted.info/,
+ );
+ });
+
+ function runMockedCoverage(exitCode) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rust-coverage-runner-"));
+ try {
+ for (const folder of [
+ "bin",
+ "scripts/ci",
+ "crates/openhuman-cli",
+ ".config",
+ "tests",
+ ])
+ fs.mkdirSync(path.join(dir, folder), { recursive: true });
+ const write = (name, content) =>
+ fs.writeFileSync(path.join(dir, name), content, { mode: 0o755 });
+ for (const name of [
+ "scripts/ci/nextest-coverage.sh",
+ "scripts/ci/nextest-report.mjs",
+ ".config/nextest.toml",
+ ])
+ fs.copyFileSync(path.join(repoRoot, name), path.join(dir, name));
+ write("scripts/ci/product-features.sh", "#!/bin/bash\necho channels\n");
+ write("scripts/ci-cancel-aware.sh", '#!/bin/bash\nexec "$@"\n');
+ write("scripts/ci/assert-coverage-presence.sh", "#!/bin/bash\nexit 0\n");
+ write("crates/openhuman-cli/Cargo.toml", "");
+ write("tests/active.rs", "#[test] fn active() {}\n");
+ write("bin/rustup", "#!/bin/bash\nexit 1\n");
+ write(
+ "bin/cargo",
+ `#!/bin/bash
+ printf '%s\\n' "$*" >> "$MOCK_CALLS"
+ case "$*" in *"-E package(=openhuman)") [ "${exitCode}" = 0 ] || exit "${exitCode}" ;; esac
+ node - "$@" <<'JS'
+ const fs = require('node:fs');
+ const args = process.argv.slice(2);
+ if (args[0] === 'metadata') console.log(JSON.stringify({ packages: [] }));
+ if (args[0] === 'llvm-cov' && args[1] === 'show-env') console.log('export CARGO_LLVM_COV_TARGET_DIR=target');
+ if (args[0] === 'nextest' && args[1] === 'list') {
+ console.log(JSON.stringify({ 'rust-suites': { active: { 'binary-name': 'active', testcases: { active: { ignored: false, 'filter-match': { status: 'matches' } } } } } }));
+ }
+ const pos = args.indexOf('--config-file');
+ if (pos >= 0) {
+ const config = fs.readFileSync(args[pos + 1], 'utf8');
+ const report = JSON.parse(config.split('\\n').find(line => line.startsWith('path = ')).slice(7));
+ fs.writeFileSync(report, '<testsuites><testsuite name="openhuman-cli::active" tests="1"></testsuite></testsuites>');
+ }
+ JS
+ `,
+ );
+ let status = 0;
+ try {
+ execFileSync("bash", [runner], {
+ cwd: dir,
+ env: {
+ ...process.env,
+ PATH: `${dir}/bin:${process.env.PATH}`,
+ MOCK_CALLS: `${dir}/calls`,
+ OH_COV_RUNNER: "nextest",
+ OH_COV_DOCTESTS: "0",
+ },
+ stdio: "pipe",
+ });
+ } catch (error) {
+ status = error.status;
+ }
+ return {
+ status,
+ calls: fs.readFileSync(`${dir}/calls`, "utf8").trim().split("\n"),
+ };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ test("private coverage executes every package configuration once and reports after a failed suite", () => {
+ const { status, calls } = runMockedCoverage(7);
+ assert.equal(status, 1);
+ const selections = calls.filter((line) => line.includes("llvm-cov nextest"));
+ assert.equal(selections.length, 8);
+ assert.equal(new Set(selections).size, 8);
+ assert.ok(selections.every((line) => line.includes("--no-tests=fail")));
+ assert.ok(
+ selections.some((line) =>
+ line.includes("-E package(=openhuman-cli) & kind(test)"),
+ ),
+ );
+ // The product-feature suites differ only in their nextest filter, so Cargo
+ // resolves (and builds) the core and its dependencies once for all of them.
+ const unified = selections.filter((line) =>
+ line.includes(
+ "--features channels --no-report --no-fail-fast -p openhuman -p openhuman-embed -p openhuman-tinyhumans -p openhuman-cli --all-targets -E ",
+ ),
+ );
+ assert.equal(unified.length, 4);
+ assert.deepEqual(
+ unified.map((line) => line.slice(line.indexOf("-E ") + 3)).sort(),
+ [
+ "package(=openhuman)",
+ "package(=openhuman-cli) & kind(test)",
+ "package(=openhuman-embed)",
+ "package(=openhuman-tinyhumans)",
+ ],
+ );
+ assert.equal(
+ calls.filter((line) => line.includes("llvm-cov report")).length,
+ 1,
+ );
+ });
+
+ test("private coverage cancels remaining suites but still preserves a report", () => {
+ const { status, calls } = runMockedCoverage(143);
+ assert.equal(status, 143);
+ assert.equal(
+ calls.filter((line) => line.includes("llvm-cov nextest")).length,
+ 1,
+ );
+ assert.equal(
+ calls.filter((line) => line.includes("llvm-cov report")).length,
+ 1,
+ );
+ });
+
+ test("private coverage passes when all eight selected configurations report tests", () => {
+ const { status } = runMockedCoverage(0);
+ assert.equal(status, 0);
+ });
+
+ test("instrumented CLI inventory is cancellation-aware and reuses llvm-cov's environment", () => {
+ const source = fs.readFileSync(runner, "utf8");
+ assert.match(
+ source,
+ /bash scripts\/ci-cancel-aware\.sh cargo llvm-cov show-env --sh/,
+ );
+ assert.match(source, /eval "\$\{inventory_env\}"/);
+ assert.match(
+ source,
+ /bash scripts\/ci-cancel-aware\.sh cargo nextest list --message-format json/,
+ );
+ });
+
+ test("CLI inventory lists llvm-cov's own build instead of instrumenting a second copy", () => {
+ const source = fs.readFileSync(runner, "utf8");
+ const start = source.indexOf(" cli_inventory() (");
+ const end = source.indexOf("\n )", start);
+ assert.notEqual(start, -1);
+ assert.notEqual(end, -1);
+ const inventory = source.slice(start, end + "\n )".length);
+ const script = [
+ "set -euo pipefail",
+ 'CORE_PRODUCT_FEATURES="channels,modules"',
+ ...source
+ .split("\n")
+ .filter((line) => /^(UNIFIED_PRODUCT_ARGS|FILTER_CLI_TESTS)=/.test(line)),
+ "expected_inventory=/dev/null",
+ "export CARGO_BUILD_TARGET_DIR=preserved-target",
+ `bash() {
+ if [[ "$*" == *"llvm-cov show-env"* ]]; then
+ for arg in "$@"; do
+ [[ "$arg" != --features ]] || { echo 'show-env rejects --features' >&2; return 64; }
+ done
+ printf '%s\\n' 'export INVENTORY_INSTRUMENTED=1' 'export CARGO_TARGET_DIR=instrumented-target' 'export CARGO_LLVM_COV_TARGET_DIR=cov-target'
+ elif [[ "$*" == *"nextest list"* ]]; then
+ [[ "$*" == *"--features channels,modules --target-dir cov-target/llvm-cov-target -p openhuman -p openhuman-embed -p openhuman-tinyhumans -p openhuman-cli --all-targets -E package(=openhuman-cli) & kind(test)"* ]] || return 65
+ [[ "$INVENTORY_INSTRUMENTED" == 1 && "$CARGO_TARGET_DIR" == instrumented-target && "$CARGO_BUILD_TARGET_DIR" == preserved-target ]] || return 66
+ [[ "$LLVM_PROFILE_FILE" == */ci-out/nextest/cli-inventory-profraw/* ]] || return 68
+ else return 67
+ fi
+ }`,
+ inventory,
+ "cli_inventory",
+ ].join("\n");
+ execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ });
+
+ for (const platform of ["Linux", "Darwin", "MINGW64_NT-10.0", "Windows_NT"]) {
+ test(`coverage inventory applies only documented target exceptions on ${platform}`, () => {
+ const windows = platform.startsWith("MINGW") || platform === "Windows_NT";
+ const result = withRunnerFunctions(
+ ["target_expected_in_coverage"],
+ 'log() { printf "%s\\n" "$*"; }',
+ [
+ `if target_expected_in_coverage composio_list_tools_stack_overflow_regression '${platform}'; then exit 11; fi`,
+ `if target_expected_in_coverage windows_sandbox_env_e2e '${platform}'; then ${windows ? ":" : "exit 12"}; else ${windows ? "exit 13" : ":"}; fi`,
+ `target_expected_in_coverage json_rpc_e2e '${platform}'`,
+ `target_expected_in_coverage future_empty_suite '${platform}'`,
+ ].join("\n"),
+ );
+ assert.equal(result.status, 0, result.output);
+ assert.match(result.output, /cfg\(not\(coverage\)\)/);
+ });
+ }
+
+ test("coverage inventory exceptions match the source gates and remain required at selection", () => {
+ assert.match(
+ fs.readFileSync(
+ path.join(
+ repoRoot,
+ "tests/composio_list_tools_stack_overflow_regression.rs",
+ ),
+ "utf8",
+ ),
+ /#!\[cfg\(not\(coverage\)\)\]/,
+ );
+ const windows = fs.readFileSync(
+ path.join(repoRoot, "tests/windows_sandbox_env_e2e.rs"),
+ "utf8",
+ );
+ const functions = [
+ ...windows.matchAll(
+ /#\[cfg\(windows\)\]\s*#\[(?:tokio::)?test(?:\([^\n]*\))?\]/g,
+ ),
+ ];
+ assert.ok(
+ functions.length > 0,
+ "Windows-only fixture must retain gated tests",
+ );
+ assert.equal(
+ functions.length,
+ [...windows.matchAll(/#\[(?:tokio::)?test(?:\([^\n]*\))?\]/g)].length,
+ "every Windows fixture test must remain gated",
+ );
+ assert.match(
+ fs.readFileSync(runner, "utf8"),
+ /target_features_satisfied "\$\{target\}" && target_expected_in_coverage "\$\{target\}"/,
+ );
+ });
+
+ test("nextest product suites share one Cargo argument set and differ only in their filter", () => {
+ // Join line continuations so each suite call reads as one command.
+ const source = fs.readFileSync(runner, "utf8").replace(/\\\n\s*/g, "");
+ const nextestOnly = (name) => {
+ const pattern = new RegExp(
+ `suite "${name}" llvm_cov --no-report --no-fail-fast "\\$\\{UNIFIED_PRODUCT_ARGS\\[@\\]\\}" -E "\\$\\{(FILTER_[A-Z_]+)\\}"`,
+ );
+ const match = source.match(pattern);
+ assert.ok(match, `${name} must use the unified product arguments`);
+ return match[1];
+ };
+ const filters = [
+ nextestOnly("openhuman lib\\+bins \\(nextest\\)"),
+ nextestOnly("openhuman-embed"),
+ nextestOnly("openhuman-tinyhumans"),
+ nextestOnly("openhuman-cli integration tests \\(nextest\\)"),
+ ];
+ assert.equal(new Set(filters).size, 4, "every suite selects its own tests");
+ // The cli inventory is listed with the same arguments so it reuses the build.
+ assert.match(
+ source,
+ /cargo nextest list .*"\$\{UNIFIED_PRODUCT_ARGS\[@\]\}" -E "\$\{FILTER_CLI_TESTS\}"/,
+ );
+ // One package set, whose cargo resolution unifies the core's features once.
+ const args = source.match(/^UNIFIED_PRODUCT_ARGS=\((.*)\)$/m)[1];
+ assert.equal(
+ args,
+ "-p openhuman -p openhuman-embed -p openhuman-tinyhumans -p openhuman-cli --all-targets",
+ );
+ // Exact package matches: `package(openhuman)` alone would be a glob of the name.
+ for (const value of [
+ "FILTER_CORE='package(=openhuman)'",
+ "FILTER_EMBED='package(=openhuman-embed)'",
+ "FILTER_TINYHUMANS='package(=openhuman-tinyhumans)'",
+ "FILTER_CLI_TESTS='package(=openhuman-cli) & kind(test)'",
+ ])
+ assert.ok(source.includes(value), value);
+ // The old per-package nextest selections are gone; rpc, tui and the default
+ // feature suites keep their own resolutions.
+ assert.doesNotMatch(source, /-p openhuman-cli --tests/);
-
++
+ assert.match(source, /suite "openhuman-rpc" llvm_cov_package .*-p openhuman-rpc --all-targets/);
+ assert.match(source, /suite "openhuman-tui" llvm_cov_package .*-p openhuman-tui --all-targets/);
+ assert.match(source, /suite "openhuman-embed \(default\)" llvm_cov_package .*-p openhuman-embed --all-targets/);
+ });