The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(memory): bring the host's RPC models home from the engine crate
Shanu3e6f20e293e7
diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rsindex 3afef7ff6e..a2e19dd7b2 100644--- a/src/openhuman/memory/direct_engine_refs_tests.rs+++ b/src/openhuman/memory/direct_engine_refs_tests.rs@@ -99,12 +99,18 @@//! behind the bus is the only shape that keeps a supermemory/mem0/cognee//! driver implementable** — a contract with `with_connection` in it is a//! SQLite contract wearing a trait.-//! - **Host policy living in the engine crate** (~14 files) —+//! - **Host policy reached through the engine crate** (~14 files) —//! `store::safety::{sanitize_text, sanitize_json, has_likely_secret}`,-//! `util::redact::redact`, `source_scope::*`. Pure functions and a-//! task-local. These want relocation to `tinymemory-api`, not bus methods;-//! they are the cheapest item on this list and they unblock nothing else,-//! which is exactly why they are worth doing first.+//! `util::redact::redact`, `source_scope::*`. This looked like the cheapest+//! item on the list and mostly is not, which is worth stating so the next+//! person does not re-derive it: `store::safety` is a **shim over+//! `crate::engine::backend::store::safety`**, so those scrubbers live in+//! tinycortex and relocating them is engine work rather than a contract+//! move. `source_scope` is a `tokio::task_local`, so hosting it in+//! `tinymemory-api` means adding tokio to a crate whose whole point is that+//! a caller can depend on it and compile almost nothing. Only+//! `util::redact` (136 lines over `sha2`) is the clean case, and it costs+//! `sha2` in the contract crate.//! - **The re-embed queue** (~8 files) — `queue::{start, store, types,//! ensure_reembed_backfill, requeue_failed_after_provider_change,//! drain_until_idle, wake_workers, backfill_in_progress}`. No family.@@ -112,13 +118,20 @@//! `tinycortex::{memory_config_from, run_composio_connection,//! load_composio_sync_state, HostSyncAdapter, CodingSession*}`. Named after//! the engine, so no engine-neutral family can express them as they stand.-//! - **Engine-owned types** — `rpc_models::*`, `store::trees::types::TreeKind`,+//! - **Engine-owned types** — `store::trees::types::TreeKind`,//! `store::chunks::types::SourceKind`, `store::{NamespaceDocumentInput,//! NamespaceRetrievalContext, GraphRelationRecord}`. A type import links the//! crate exactly as a call does, so the shed needs these in//! `tinymemory-api`. `MemoryCategory`/`MemoryEntry`/`MemoryTaint` already//! are — `tinymemory_core::traits` re-exports them — so those call sites can//! name the contract today.+//!+//! `rpc_models` was on this list and is **done**: all forty-five types were+//! named by this host and by nothing inside `tinymemory`, so they moved to+//! `memory::rpc_models` rather than into the contract. That is the shape to+//! look for first in what remains — a type the engine crate defines but only+//! the host uses does not need a contract to live in, it needs to come home.+//! `SourceKind` is emphatically **not** such a case (see the trap below).//! - **Chat, ingest pipeline and preferences** (~12 files) —//! `chat::{ChatProvider, build_chat_provider, test_override}`,//! `ingest_pipeline::{ingest_chat, ingest_document_with_scope}`,@@ -293,7 +306,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/agent/harness/artifact_offload/policy.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (store::safety::sanitize_text); belongs in tinymemory-api rather than gaining a bus method",+ "host policy reached through the engine crate (store::safety::sanitize_text); `store::safety` is itself a shim over `crate::engine::backend::store::safety`, so the scrubbers live in tinycortex — relocating them is engine work, not a contract move",),("src/openhuman/agent/harness/session/builder/factory.rs",@@ -318,7 +331,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/agent/harness/tool_result_artifacts/mod.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (store::safety); belongs in tinymemory-api rather than gaining a bus method",+ "host policy reached through the engine crate (store::safety); `store::safety` is itself a shim over `crate::engine::backend::store::safety`, so the scrubbers live in tinycortex — relocating them is engine work, not a contract move",),("src/openhuman/agent/learning/linkedin_enrichment.rs",@@ -348,7 +361,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/agent/tools/save_preference.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (store::safety); belongs in tinymemory-api rather than gaining a bus method",+ "host policy reached through the engine crate (store::safety); `store::safety` is itself a shim over `crate::engine::backend::store::safety`, so the scrubbers live in tinycortex — relocating them is engine work, not a contract move",),("src/openhuman/channels/controllers/ops/connect.rs",@@ -398,7 +411,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/flows/tinyflows/memory_adapter.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (store::safety::has_likely_secret); belongs in tinymemory-api rather than gaining a bus method",+ "host policy reached through the engine crate (store::safety::has_likely_secret); `store::safety` is itself a shim over `crate::engine::backend::store::safety`, so the scrubbers live in tinycortex — relocating them is engine work, not a contract move",),("src/openhuman/hosted/orchestration/effect_executor.rs",@@ -433,7 +446,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/memory/guard/audit.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (util::redact::redact); belongs in tinymemory-api rather than gaining a bus method",+ "pure host-policy helper genuinely owned by the engine crate (util::redact::redact — 136 lines over `sha2` alone); relocatable to tinymemory-api, at the cost of adding `sha2` there, unlike its `store::safety` neighbours which only shim the engine's own scrubbers",),("src/openhuman/memory/guard/policy.rs",@@ -513,7 +526,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/memory/store_golden.rs",Verdict::NeedsWiderSeam,- "reaches engine storage below the contract (global::client, rpc_models::QueryNamespaceRequest, store::UnifiedMemory::new, store::chunks); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",+ "reaches engine storage below the contract (global::client, store::UnifiedMemory::new, store::chunks); MemoryChunks is read-only (list_chunks/get_chunk/chunk_detail/storage_kinds/chunk_embeddings) with no write or transaction door",),("src/openhuman/memory/sync/composio/bus.rs",@@ -573,7 +586,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[("src/openhuman/security/approval/store.rs",Verdict::NeedsWiderSeam,- "pure host-policy helper living in the engine crate (store::safety::sanitize_text); belongs in tinymemory-api rather than gaining a bus method",+ "host policy reached through the engine crate (store::safety::sanitize_text); `store::safety` is itself a shim over `crate::engine::backend::store::safety`, so the scrubbers live in tinycortex — relocating them is engine work, not a contract move",),("src/openhuman/security/credentials/ops.rs",diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rsindex ebe12bbe6a..86f06163c8 100644--- a/src/openhuman/memory/mod.rs+++ b/src/openhuman/memory/mod.rs@@ -121,7 +121,13 @@ pub use tinymemory_core::ingestion::{IngestionState, IngestionStatusSnapshot, MemoryIngestionConfig, MemoryIngestionRequest,MemoryIngestionResult, DEFAULT_MEMORY_EXTRACTION_MODEL,};-pub use tinymemory_core::rpc_models::*;+// The host's own JSON-RPC request/response shapes. They lived in+// `tinymemory_core::rpc_models` and were re-exported here by a glob; nothing+// in `tinymemory` ever named one, so the engine crate was carrying this host's+// RPC surface (#5560). Same glob, same paths, same wire bytes — the definitions+// are simply ours now. See `rpc_models`'s module docs.+pub mod rpc_models;+pub use rpc_models::*;pub use tinymemory_core::traits::{Memory, MemoryCategory, MemoryEntry, MemoryTaint, NamespaceSummary, RecallOpts,};diff --git a/src/openhuman/memory/rpc_models.rs b/src/openhuman/memory/rpc_models.rsnew file mode 100644index 0000000000..ff3e994c7d--- /dev/null+++ b/src/openhuman/memory/rpc_models.rs@@ -0,0 +1,614 @@+//! RPC data models for the OpenHuman memory system.+//!+//! This module defines the request and response structures used by the JSON-RPC+//! interface to interact with the memory system. These models ensure type-safe+//! communication between the frontend/client and the Rust backend.+//!+//! # Why these live here and not in the engine crate (#5560)+//!+//! They used to be `tinymemory_core::rpc_models`, re-exported into this module+//! by a glob. Nothing in `tinymemory` ever referenced them — not the engine,+//! not an adapter, not a test — while all forty-five types are named by this+//! host, so the engine crate was carrying one host's JSON-RPC surface and+//! every file that touched a request shape held the engine in the build for it.+//!+//! Moving them changes no bytes on the wire: the structs are verbatim, so the+//! serde shapes, field names and defaults are identical, and the re-export+//! below keeps every `memory::…` path resolving exactly as before. What it+//! changes is who owns them — a request shape this host defines, deserializes+//! and passes between its own functions (`memory_query_namespace`,+//! `thread_create_new`) was never the engine's to define.+//!+//! The mirror in `tinymemory-core` is dead on arrival and should be deleted+//! upstream; until it is, the two definitions cannot diverge in a way that+//! matters, because nothing reads the engine's copy.++use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++/// Standard error structure for API responses.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApiError {+ /// A machine-readable error code.+ pub code: String,+ /// A human-readable error message.+ pub message: String,+ /// Optional additional error details.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub details: Option<serde_json::Value>,+}++/// Pagination metadata for list-based responses.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaginationMeta {+ /// Maximum number of items requested.+ pub limit: usize,+ /// Number of items skipped.+ pub offset: usize,+ /// Total number of items available in the backend.+ pub count: usize,+}++/// General metadata included in all API envelopes.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApiMeta {+ /// Unique identifier for the request.+ pub request_id: String,+ /// Time taken to process the request in seconds.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub latency_seconds: Option<f64>,+ /// Whether the response was served from a cache.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cached: Option<bool>,+ /// Optional counts of various items (e.g., by category).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub counts: Option<BTreeMap<String, usize>>,+ /// Optional pagination information.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub pagination: Option<PaginationMeta>,+}++/// Generic envelope for all API responses.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApiEnvelope<T> {+ /// The actual payload of the response.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub data: Option<T>,+ /// Error information if the request failed.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<ApiError>,+ /// Metadata about the request and response.+ pub meta: ApiMeta,+}++/// An empty request body for methods that don't require parameters.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct EmptyRequest {}++/// Request to create a new conversation thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CreateConversationThreadRequest {+ #[serde(default)]+ pub labels: Option<Vec<String>>,+ #[serde(default)]+ pub personality_id: Option<String>,+}++/// Request payload for `openhuman.memory_init`.+///+/// `jwt_token` is accepted for backward compatibility but **not used** — memory+/// is local-only (SQLite). Remote/cloud memory sync is a future consideration.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct MemoryInitRequest {+ /// Optional token, currently ignored as memory is local-only.+ #[serde(default)]+ pub jwt_token: Option<String>,+}++/// Response payload for `openhuman.memory_init`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryInitResponse {+ /// Whether the memory system was successfully initialized.+ pub initialized: bool,+ /// The root workspace directory.+ pub workspace_dir: String,+ /// The specific directory where memory data is stored.+ pub memory_dir: String,+}++/// Summary information for a workspace-backed conversation thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ConversationThreadSummary {+ pub id: String,+ pub title: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub chat_id: Option<i64>,+ pub is_active: bool,+ pub message_count: usize,+ pub last_message_at: String,+ pub created_at: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent_thread_id: Option<String>,+ #[serde(default)]+ pub labels: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub personality_id: Option<String>,+}++/// A single persisted conversation message.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ConversationMessageRecord {+ pub id: String,+ pub content: String,+ #[serde(rename = "type")]+ pub message_type: String,+ #[serde(default)]+ pub extra_metadata: serde_json::Value,+ pub sender: String,+ pub created_at: String,+}++/// Request to create or update a thread in workspace storage.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UpsertConversationThreadRequest {+ pub id: String,+ pub title: String,+ pub created_at: String,+ #[serde(default)]+ pub parent_thread_id: Option<String>,+ #[serde(default)]+ pub labels: Option<Vec<String>>,+ #[serde(default)]+ pub personality_id: Option<String>,+}++/// Request to update labels for a conversation thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UpdateConversationThreadLabelsRequest {+ pub thread_id: String,+ pub labels: Vec<String>,+}++/// Request to set a user-specified title on a conversation thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UpdateConversationThreadTitleRequest {+ pub thread_id: String,+ pub title: String,+}++/// Response payload for thread list operations.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ConversationThreadsListResponse {+ pub threads: Vec<ConversationThreadSummary>,+ pub count: usize,+}++/// Request to fetch messages for a specific thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ConversationMessagesRequest {+ pub thread_id: String,+}++/// Response payload for message list operations.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ConversationMessagesResponse {+ pub messages: Vec<ConversationMessageRecord>,+ pub count: usize,+}++/// Request to append a message to a thread.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct AppendConversationMessageRequest {+ pub thread_id: String,+ pub message: ConversationMessageRecord,+}++/// Request to generate or refresh a thread title after the first exchange.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct GenerateConversationThreadTitleRequest {+ pub thread_id: String,+ #[serde(default)]+ pub assistant_message: Option<String>,+}++/// Request to patch a persisted message.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UpdateConversationMessageRequest {+ pub thread_id: String,+ pub message_id: String,+ #[serde(default)]+ pub extra_metadata: Option<serde_json::Value>,+}++/// Request to delete a thread and its message log.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DeleteConversationThreadRequest {+ pub thread_id: String,+ pub deleted_at: String,+}++/// Response payload for single-thread deletion.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DeleteConversationThreadResponse {+ pub deleted: bool,+}++/// Response payload for purging all workspace-backed conversations.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PurgeConversationThreadsResponse {+ pub messages_deleted: usize,+ pub agent_threads_deleted: usize,+ pub agent_messages_deleted: usize,+}++/// Request payload for `openhuman.list_documents`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ListDocumentsRequest {+ /// Optional namespace filter.+ #[serde(default)]+ pub namespace: Option<String>,+}++/// Summary information for a document in memory.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryDocumentSummary {+ /// Unique identifier for the document.+ pub document_id: String,+ /// Namespace the document belongs to.+ pub namespace: String,+ /// Lookup key for the document.+ pub key: String,+ /// Human-readable title.+ pub title: String,+ /// Type of the source (e.g., "file", "web", "note").+ pub source_type: String,+ /// Ingestion priority.+ pub priority: String,+ /// Creation timestamp (Unix epoch).+ pub created_at: f64,+ /// Last update timestamp (Unix epoch).+ pub updated_at: f64,+}++/// Response payload for `openhuman.list_documents`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ListDocumentsResponse {+ /// The namespace used for filtering.+ #[serde(default)]+ pub namespace: Option<String>,+ /// The list of document summaries.+ pub documents: Vec<MemoryDocumentSummary>,+ /// Total number of documents found.+ pub count: usize,+}++/// Response payload for `openhuman.list_namespaces`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ListNamespacesResponse {+ /// List of available namespace names.+ pub namespaces: Vec<String>,+ /// Total number of namespaces.+ pub count: usize,+}++/// Request payload for `openhuman.delete_document`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DeleteDocumentRequest {+ /// Namespace containing the document.+ pub namespace: String,+ /// ID of the document to delete.+ pub document_id: String,+}++/// Response payload for `openhuman.delete_document`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DeleteDocumentResponse {+ /// Status message of the operation.+ pub status: String,+ /// Namespace of the document.+ pub namespace: String,+ /// ID of the deleted document.+ pub document_id: String,+ /// Whether the deletion was successful.+ pub deleted: bool,+}++/// Request payload for `openhuman.query_namespace`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct QueryNamespaceRequest {+ /// Namespace to query.+ pub namespace: String,+ /// Natural language query or search term.+ pub query: String,+ /// Whether to include reference citations in the response.+ #[serde(default)]+ pub include_references: Option<bool>,+ /// Optional filter to specific document IDs.+ #[serde(default)]+ pub document_ids: Option<Vec<String>>,+ /// Maximum number of results to return.+ #[serde(default)]+ pub limit: Option<u32>,+ /// Alias for limit, specifying max number of chunks.+ #[serde(default)]+ pub max_chunks: Option<u32>,+}++impl QueryNamespaceRequest {+ /// Resolves the effective limit from `max_chunks`, `limit`, or a default value.+ pub fn resolved_limit(&self) -> u32 {+ self.max_chunks.or(self.limit).unwrap_or(10)+ }+}++/// Response payload for `openhuman.query_namespace`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct QueryNamespaceResponse {+ /// Retrieved context including entities, relations, and chunks.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub context: Option<MemoryRetrievalContext>,+ /// A formatted message suitable for inclusion in an LLM prompt.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub llm_context_message: Option<String>,+}++/// Request payload for `openhuman.recall_context`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RecallContextRequest {+ /// Namespace to recall from.+ pub namespace: String,+ /// Whether to include references.+ #[serde(default)]+ pub include_references: Option<bool>,+ /// Maximum number of results.+ #[serde(default)]+ pub limit: Option<u32>,+ /// Maximum number of chunks.+ #[serde(default)]+ pub max_chunks: Option<u32>,+}++impl RecallContextRequest {+ /// Resolves the effective limit.+ pub fn resolved_limit(&self) -> u32 {+ self.max_chunks.or(self.limit).unwrap_or(10)+ }+}++/// Response payload for `openhuman.recall_context`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecallContextResponse {+ /// Retrieved context.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub context: Option<MemoryRetrievalContext>,+ /// Formatted LLM message.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub llm_context_message: Option<String>,+}++/// Request payload for `openhuman.recall_memories`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RecallMemoriesRequest {+ /// Namespace to recall from.+ pub namespace: String,+ /// Minimum retention score (0.0 to 1.0).+ #[serde(default)]+ pub min_retention: Option<f32>,+ /// Temporal filter (Unix epoch).+ #[serde(default)]+ pub as_of: Option<f64>,+ /// Maximum results.+ #[serde(default)]+ pub limit: Option<u32>,+ /// Alias for limit.+ #[serde(default)]+ pub max_chunks: Option<u32>,+ /// Alias for limit (top K results).+ #[serde(default)]+ pub top_k: Option<u32>,+}++impl RecallMemoriesRequest {+ /// Resolves the effective limit checking `top_k`, `max_chunks`, and `limit`.+ pub fn resolved_limit(&self) -> u32 {+ self.top_k.or(self.max_chunks).or(self.limit).unwrap_or(10)+ }+}++/// Represents an entity retrieved from memory.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryRetrievalEntity {+ /// Unique identifier for the entity.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub id: Option<String>,+ /// Name of the entity.+ pub name: String,+ /// Type of the entity (e.g., "Person", "Place").+ #[serde(skip_serializing_if = "Option::is_none")]+ pub entity_type: Option<String>,+ /// Retrieval relevance score.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub score: Option<f64>,+ /// Additional arbitrary metadata.+ #[serde(default)]+ pub metadata: serde_json::Value,+}++/// Represents a relationship between two entities.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryRetrievalRelation {+ /// The subject entity.+ pub subject: String,+ /// The relationship type (predicate).+ pub predicate: String,+ /// The object entity.+ pub object: String,+ /// Relevance score.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub score: Option<f64>,+ /// Number of times this relation was evidenced.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub evidence_count: Option<u32>,+ /// Additional metadata.+ #[serde(default)]+ pub metadata: serde_json::Value,+}++/// Represents a text chunk retrieved from memory.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryRetrievalChunk {+ /// ID of the chunk.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub chunk_id: Option<String>,+ /// ID of the parent document.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub document_id: Option<String>,+ /// The text content of the chunk.+ pub content: String,+ /// Relevance score.+ pub score: f64,+ /// Additional metadata.+ #[serde(default)]+ pub metadata: serde_json::Value,+ /// Creation timestamp.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub created_at: Option<String>,+ /// Last update timestamp.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub updated_at: Option<String>,+}++/// Container for all retrieved memory components.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryRetrievalContext {+ /// List of entities found.+ pub entities: Vec<MemoryRetrievalEntity>,+ /// List of relations between entities.+ pub relations: Vec<MemoryRetrievalRelation>,+ /// List of raw text chunks.+ pub chunks: Vec<MemoryRetrievalChunk>,+}++/// A specific item recalled from memory.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemoryRecallItem {+ /// Type of memory item (e.g., "fact", "observation").+ #[serde(rename = "type")]+ pub kind: String,+ /// Unique ID of the item.+ pub id: String,+ /// Text content of the memory.+ pub content: String,+ /// Relevance score.+ pub score: f64,+ /// Retention strength (0.0 to 1.0).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub retention: Option<f64>,+ /// Timestamp of last access.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub last_accessed_at: Option<String>,+ /// Total number of times this memory was accessed.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub access_count: Option<u32>,+ /// How many days the memory has remained stable.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub stability_days: Option<f64>,+}++/// Response payload for `openhuman.recall_memories`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecallMemoriesResponse {+ /// List of recalled memory items.+ pub memories: Vec<MemoryRecallItem>,+}++/// Request payload for `openhuman.list_memory_files`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ListMemoryFilesRequest {+ /// Directory path relative to the memory root.+ #[serde(default = "default_memory_relative_dir")]+ pub relative_dir: String,+}++/// Response payload for `openhuman.list_memory_files`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ListMemoryFilesResponse {+ /// The directory listed.+ pub relative_dir: String,+ /// List of filenames.+ pub files: Vec<String>,+ /// Total count of files.+ pub count: usize,+}++/// Request payload for `openhuman.read_memory_file`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ReadMemoryFileRequest {+ /// Path to the file relative to the memory root.+ pub relative_path: String,+}++/// Response payload for `openhuman.read_memory_file`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReadMemoryFileResponse {+ /// The path of the file read.+ pub relative_path: String,+ /// Full content of the file.+ pub content: String,+}++/// Request payload for `openhuman.write_memory_file`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WriteMemoryFileRequest {+ /// Path to write to relative to the memory root.+ pub relative_path: String,+ /// Content to write.+ pub content: String,+}++/// Response payload for `openhuman.write_memory_file`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WriteMemoryFileResponse {+ /// The path of the file written.+ pub relative_path: String,+ /// Whether the write was successful.+ pub written: bool,+ /// Number of bytes written.+ pub bytes_written: usize,+}++/// Default directory for memory operations. Empty string means the memory+/// root itself (`<workspace>/memory`); the file-based memory RPCs resolve all+/// relative paths under that directory.+pub(crate) fn default_memory_relative_dir() -> String {+ String::new()+}++#[cfg(test)]+#[path = "rpc_models_tests.rs"]+mod tests;diff --git a/src/openhuman/memory/rpc_models_tests.rs b/src/openhuman/memory/rpc_models_tests.rsnew file mode 100644index 0000000000..22207e2dc2--- /dev/null+++ b/src/openhuman/memory/rpc_models_tests.rs@@ -0,0 +1,239 @@+//! Unit tests for the memory RPC request/response models, covering+//! deserialization compatibility and limit-resolution helpers.++use super::*;+use serde_json::json;++#[test]+fn recall_memories_request_accepts_compatibility_noop_params() {+ let request: RecallMemoriesRequest = serde_json::from_value(json!({+ "namespace": "team",+ "top_k": 7,+ "min_retention": 0.8,+ "as_of": 1700000000.0+ }))+ .expect("compatibility params should deserialize");++ assert_eq!(request.namespace, "team");+ assert_eq!(request.top_k, Some(7));+ assert_eq!(request.min_retention, Some(0.8));+ assert_eq!(request.as_of, Some(1_700_000_000.0));+}++#[test]+fn recall_memories_request_limit_resolution_ignores_compatibility_noop_params() {+ let request: RecallMemoriesRequest = serde_json::from_value(json!({+ "namespace": "team",+ "limit": 3,+ "min_retention": 0.5,+ "as_of": 1700000000.0+ }))+ .expect("request should deserialize");++ assert_eq!(request.resolved_limit(), 3);+}++// ── resolved_limit priorities ─────────────────────────────────++#[test]+fn recall_memories_resolved_limit_prefers_top_k_over_max_chunks_and_limit() {+ let req = RecallMemoriesRequest {+ namespace: "n".into(),+ min_retention: None,+ as_of: None,+ limit: Some(5),+ max_chunks: Some(7),+ top_k: Some(9),+ };+ assert_eq!(req.resolved_limit(), 9);+}++#[test]+fn recall_memories_resolved_limit_falls_back_to_max_chunks_then_limit_then_default() {+ let without_top_k = RecallMemoriesRequest {+ namespace: "n".into(),+ min_retention: None,+ as_of: None,+ limit: Some(5),+ max_chunks: Some(7),+ top_k: None,+ };+ assert_eq!(without_top_k.resolved_limit(), 7);++ let limit_only = RecallMemoriesRequest {+ namespace: "n".into(),+ min_retention: None,+ as_of: None,+ limit: Some(5),+ max_chunks: None,+ top_k: None,+ };+ assert_eq!(limit_only.resolved_limit(), 5);++ let none = RecallMemoriesRequest {+ namespace: "n".into(),+ min_retention: None,+ as_of: None,+ limit: None,+ max_chunks: None,+ top_k: None,+ };+ assert_eq!(none.resolved_limit(), 10);+}++#[test]+fn query_namespace_resolved_limit_prefers_max_chunks_then_limit_then_default() {+ let req = QueryNamespaceRequest {+ namespace: "n".into(),+ query: "q".into(),+ include_references: None,+ document_ids: None,+ limit: Some(3),+ max_chunks: Some(9),+ };+ assert_eq!(req.resolved_limit(), 9);++ let req_limit_only = QueryNamespaceRequest {+ namespace: "n".into(),+ query: "q".into(),+ include_references: None,+ document_ids: None,+ limit: Some(3),+ max_chunks: None,+ };+ assert_eq!(req_limit_only.resolved_limit(), 3);++ let req_none = QueryNamespaceRequest {+ namespace: "n".into(),+ query: "q".into(),+ include_references: None,+ document_ids: None,+ limit: None,+ max_chunks: None,+ };+ assert_eq!(req_none.resolved_limit(), 10);+}++#[test]+fn recall_context_resolved_limit_prefers_max_chunks_then_limit_then_default() {+ let req = RecallContextRequest {+ namespace: "n".into(),+ include_references: None,+ limit: Some(3),+ max_chunks: Some(9),+ };+ assert_eq!(req.resolved_limit(), 9);++ let req_limit_only = RecallContextRequest {+ namespace: "n".into(),+ include_references: None,+ limit: Some(3),+ max_chunks: None,+ };+ assert_eq!(req_limit_only.resolved_limit(), 3);++ let req_none = RecallContextRequest {+ namespace: "n".into(),+ include_references: None,+ limit: None,+ max_chunks: None,+ };+ assert_eq!(req_none.resolved_limit(), 10);+}++// ── deny_unknown_fields enforcement ───────────────────────────++#[test]+fn query_namespace_request_rejects_unknown_fields() {+ let err = serde_json::from_value::<QueryNamespaceRequest>(json!({+ "namespace": "n",+ "query": "q",+ "bogus": 1+ }))+ .unwrap_err();+ assert!(err.to_string().contains("bogus"));+}++#[test]+fn recall_context_request_rejects_unknown_fields() {+ let err = serde_json::from_value::<RecallContextRequest>(json!({+ "namespace": "n",+ "bogus": true+ }))+ .unwrap_err();+ assert!(err.to_string().contains("bogus"));+}++#[test]+fn empty_request_rejects_any_field() {+ let err = serde_json::from_value::<EmptyRequest>(json!({"x": 1})).unwrap_err();+ assert!(err.to_string().contains("x"));+ serde_json::from_value::<EmptyRequest>(json!({})).unwrap();+}++// ── MemoryInitRequest tolerates backwards-compatible jwt_token ────++#[test]+fn memory_init_request_jwt_token_is_optional_and_ignored() {+ let without: MemoryInitRequest = serde_json::from_value(json!({})).unwrap();+ assert_eq!(without.jwt_token, None);+ let with: MemoryInitRequest = serde_json::from_value(json!({"jwt_token": "abc"})).unwrap();+ assert_eq!(with.jwt_token.as_deref(), Some("abc"));+}++// ── ApiError / ApiMeta / ApiEnvelope round-trip ──────────────++#[test]+fn api_error_round_trips_with_optional_details() {+ let err = ApiError {+ code: "E".into(),+ message: "boom".into(),+ details: Some(json!({"why": "reason"})),+ };+ let s = serde_json::to_string(&err).unwrap();+ let back: ApiError = serde_json::from_str(&s).unwrap();+ assert_eq!(back.code, "E");+ assert_eq!(back.message, "boom");+ assert!(back.details.is_some());+}++#[test]+fn api_error_without_details_omits_field_when_serialized() {+ let err = ApiError {+ code: "E".into(),+ message: "boom".into(),+ details: None,+ };+ let s = serde_json::to_string(&err).unwrap();+ assert!(!s.contains("details"), "got: {s}");+}++#[test]+fn api_envelope_round_trip_preserves_data_and_meta() {+ let env = ApiEnvelope::<u32> {+ data: Some(42),+ error: None,+ meta: ApiMeta {+ request_id: "r1".into(),+ latency_seconds: Some(0.5),+ cached: Some(false),+ counts: None,+ pagination: Some(PaginationMeta {+ limit: 10,+ offset: 0,+ count: 1,+ }),+ },+ };+ let s = serde_json::to_string(&env).unwrap();+ let back: ApiEnvelope<u32> = serde_json::from_str(&s).unwrap();+ assert_eq!(back.data, Some(42));+ assert!(back.error.is_none());+ assert_eq!(back.meta.pagination.unwrap().count, 1);+}++#[test]+fn default_memory_relative_dir_is_memory() {+ // Empty string == the memory root itself (`<workspace>/memory`).+ assert_eq!(super::default_memory_relative_dir(), "");+}diff --git a/src/openhuman/memory/store_golden.rs b/src/openhuman/memory/store_golden.rsindex f3f1a9c226..47e1d82788 100644--- a/src/openhuman/memory/store_golden.rs+++ b/src/openhuman/memory/store_golden.rs@@ -48,7 +48,7 @@ use crate::openhuman::memory::ops::{doc_list, doc_put, graph_query, graph_upsert, kv_get, memory_query_namespace, GraphQueryParams,GraphUpsertParams, KvGetDeleteParams, KvSetParams, NamespaceOnlyParams, PutDocParams,};-use tinymemory_core::rpc_models::QueryNamespaceRequest;+use crate::openhuman::memory::rpc_models::QueryNamespaceRequest;use tinymemory_core::store::chunks;use tinymemory_core::store::chunks::types::{Chunk, Metadata, SourceKind, SourceRef};use tinymemory_core::store::namespace_store::{events, fts5, profile, segments};