Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): memory (#2127)

Eric Hayes3d9f87f585c9
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.ts
index 1f7e0ba93b..fd4f65b087 100644
--- a/js/app/packages/service-clients/service-cognition/generated/client.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts
@@ -17,6 +17,8 @@ import type {
GetChatsForAttachmentResponse,
GetModelsResponse,
HttpSendChatMessageRequest,
+ MemoryErrorBody,
+ MemoryResponse,
PatchChatRequest,
SendChatMessageResponse,
StringIDResponse,
@@ -745,6 +747,63 @@ export const healthHandler = async (
} as healthHandlerResponse;
};
+/**
+ * Returns the current memory if one exists. If the memory is stale or missing,
+a background generation is triggered and the endpoint returns the stale
+memory (200) or 404 if none exists yet.
+ * @summary Get the authenticated user's latest memory.
+ */
+export type getMemoryHandlerResponse200 = {
+ data: MemoryResponse;
+ status: 200;
+};
+
+export type getMemoryHandlerResponse404 = {
+ data: void;
+ status: 404;
+};
+
+export type getMemoryHandlerResponse500 = {
+ data: MemoryErrorBody;
+ status: 500;
+};
+
+export type getMemoryHandlerResponseSuccess = getMemoryHandlerResponse200 & {
+ headers: Headers;
+};
+export type getMemoryHandlerResponseError = (
+ | getMemoryHandlerResponse404
+ | getMemoryHandlerResponse500
+) & {
+ headers: Headers;
+};
+
+export type getMemoryHandlerResponse =
+ | getMemoryHandlerResponseSuccess
+ | getMemoryHandlerResponseError;
+
+export const getGetMemoryHandlerUrl = () => {
+ return `/memory`;
+};
+
+export const getMemoryHandler = async (
+ options?: RequestInit
+): Promise<getMemoryHandlerResponse> => {
+ const res = await fetch(getGetMemoryHandlerUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getMemoryHandlerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getMemoryHandlerResponse;
+};
+
/**
* @summary Gets all available models
*/
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
index 93e97bde6a..03f166145d 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
@@ -137,6 +137,8 @@ export * from './httpSendChatMessageRequestAdditionalInstructions';
export * from './httpSendChatMessageRequestAttachments';
export * from './httpSendChatMessageRequestChatId';
export * from './jwtPayload';
+export * from './memoryErrorBody';
+export * from './memoryResponse';
export * from './messageWithAttachments';
export * from './model';
export * from './modelMetadata';
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/memoryErrorBody.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/memoryErrorBody.ts
new file mode 100644
index 0000000000..db7c25a777
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/memoryErrorBody.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export interface MemoryErrorBody {
+ /** Error description. */
+ error: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/memoryResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/memoryResponse.ts
new file mode 100644
index 0000000000..4bb9743534
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/memoryResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * The user's latest memory.
+ */
+export interface MemoryResponse {
+ /** The generated memory text. */
+ memory: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 76f8c43d56..0ee3739a17 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -646,6 +646,39 @@
}
}
},
+ "/memory": {
+ "get": {
+ "tags": ["memory"],
+ "summary": "Get the authenticated user's latest memory.",
+ "description": "Returns the current memory if one exists. If the memory is stale or missing,\na background generation is triggered and the endpoint returns the stale\nmemory (200) or 404 if none exists yet.",
+ "operationId": "get_memory_handler",
+ "responses": {
+ "200": {
+ "description": "Latest memory for the user",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MemoryResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No memory exists for this user yet (generation triggered)"
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MemoryErrorBody"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/models": {
"get": {
"tags": ["get_models"],
@@ -2346,6 +2379,27 @@
}
}
},
+ "MemoryErrorBody": {
+ "type": "object",
+ "required": ["error"],
+ "properties": {
+ "error": {
+ "type": "string",
+ "description": "Error description."
+ }
+ }
+ },
+ "MemoryResponse": {
+ "type": "object",
+ "description": "The user's latest memory.",
+ "required": ["memory"],
+ "properties": {
+ "memory": {
+ "type": "string",
+ "description": "The generated memory text."
+ }
+ }
+ },
"MessageWithAttachments": {
"type": "object",
"required": ["content", "date", "attachmentIds"],
@@ -2383,6 +2437,7 @@
"claude-3-7-sonnet",
"claude-sonnet-4",
"claude-sonnet-4-5",
+ "claude-sonnet-4-6",
"claude-haiku-4-5",
"claude-opus-4-5",
"claude-opus-4-6"
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 91e73b3acc..5ff58e7159 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2914,6 +2914,7 @@ dependencies = [
"macro_share_permissions",
"macro_user_id",
"macro_uuid",
+ "memory",
"model",
"model-entity",
"model_notifications",
@@ -6075,6 +6076,47 @@ version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+[[package]]
+name = "memory"
+version = "0.1.0"
+dependencies = [
+ "ai",
+ "ai_tools",
+ "ai_toolset",
+ "anyhow",
+ "axum",
+ "chrono",
+ "comms",
+ "comms_service_client",
+ "document_cognition_service_client",
+ "document_storage_service_client",
+ "documents",
+ "email",
+ "email_service_client",
+ "entity_access",
+ "frecency",
+ "futures",
+ "lexical_client",
+ "macro_aws_config",
+ "macro_db_migrator",
+ "macro_entrypoint",
+ "macro_user_id",
+ "macro_uuid",
+ "model_user",
+ "scribe",
+ "search_service_client",
+ "serde",
+ "serde_json",
+ "soup",
+ "sqlx",
+ "static_file_service_client",
+ "sync_service_client",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "utoipa",
+]
+
[[package]]
name = "mention_utils"
version = "0.1.0"
@@ -9706,6 +9748,7 @@ dependencies = [
"chrono",
"email",
"futures",
+ "macro_user_id",
"model",
"models_email",
"models_opensearch",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index af1cd844d8..e7796d65da 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -128,7 +128,7 @@ members = [
"upload_extractor_lambda_trigger",
"user_link_cleanup_handler",
"user_quota",
- "worker_trigger",
+ "worker_trigger", "memory",
]
[workspace.dependencies]
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
index 5ae9e432cd..8f47a5b849 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
@@ -20,14 +20,13 @@ impl<T> ToolLoop<AnthropicClient, T>
where
T: Clone + Send + Sync,
{
- pub fn new(toolset: AsyncToolSet<T>, context: T) -> Self {
+ pub fn new(toolset: Arc<AsyncToolSet<T>>, context: T) -> Self {
let extensions = AnthropicRequestExtensions(vec![
AnthropicRequestExtension::WebSearchTool,
AnthropicRequestExtension::FetchTool,
AnthropicRequestExtension::CodeExecutionTool,
]);
let client = AnthropicClient::new(extensions);
- let toolset = Arc::new(toolset);
Self {
client,
context,
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
index 32ca6a9982..cabb66b05d 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
@@ -78,9 +78,7 @@ impl Default for Cli<(), fn() -> RequestContext> {
model: Model::Claude45Opus,
#[allow(deprecated)]
request_context_fn: || RequestContext {
- user_id: Arc::new(
- MacroUserIdStr::try_from_email("cli@localhost").expect("valid email"),
- ),
+ user_id: MacroUserIdStr::try_from_email("cli@localhost").expect("valid email"),
jwt: Arc::new(String::new()),
},
}
@@ -145,7 +143,7 @@ where
}
println!("---");
- let tool_loop = ToolLoop::new(self.toolset, self.service_context);
+ let tool_loop = ToolLoop::new(Arc::new(self.toolset), self.service_context);
let stdin = io::stdin();
let mut stdout = io::stdout();
diff --git a/rust/cloud-storage/ai/src/types/model/metadata.rs b/rust/cloud-storage/ai/src/types/model/metadata.rs
index 577f6d64bb..82a4cff4d6 100644
--- a/rust/cloud-storage/ai/src/types/model/metadata.rs
+++ b/rust/cloud-storage/ai/src/types/model/metadata.rs
@@ -67,6 +67,11 @@ impl ModelWithMetadataAndProvider for Model {
Model::Claude37Sonnet => ModelMetadata {
context_window: 200_000,
},
+
+ Model::Claude46Sonnet => ModelMetadata {
+ context_window: 1_000_000,
+ },
+
Model::Claude45Sonnet => ModelMetadata {
context_window: 200_000,
},
@@ -114,6 +119,7 @@ impl ModelWithMetadataAndProvider for Model {
Model::Claude45Haiku => Provider::Anthropic,
Model::Claude45Opus => Provider::Anthropic,
Model::Claude46Opus => Provider::Anthropic,
+ Model::Claude46Sonnet => Provider::Anthropic,
// XAI models //
}
}
diff --git a/rust/cloud-storage/ai/src/types/model/mod.rs b/rust/cloud-storage/ai/src/types/model/mod.rs
index b4797ac0f4..2b42015ae2 100644
--- a/rust/cloud-storage/ai/src/types/model/mod.rs
+++ b/rust/cloud-storage/ai/src/types/model/mod.rs
@@ -82,6 +82,10 @@ pub enum Model {
#[strum(serialize = "claude-sonnet-4-5")]
Claude45Sonnet,
+ #[serde(rename = "claude-sonnet-4-6")]
+ #[strum(serialize = "claude-sonnet-4-6")]
+ Claude46Sonnet,
+
#[serde(rename = "claude-haiku-4-5")]
#[strum(serialize = "claude-haiku-4-5")]
#[default]
@@ -115,6 +119,7 @@ pub mod constants {
pub const CLAUDE_37_SONNET: &str = "claude-3.7-sonnet";
pub const CLAUDE_4_SONNET: &str = "claude-sonnet-4";
pub const CLAUDE_45_SONNET: &str = "claude-4.5-sonnet";
+ pub const CLAUDE_46_SONNET: &str = "claude-4.6-sonnet";
pub const CLAUDE_45_HAIKU: &str = "claude-4.5-haiku";
pub const CLAUDE_45_OPUS: &str = "claude-4.5-opus";
pub const CLAUDE_46_OPUS: &str = "claude-4.6-opus";
@@ -148,6 +153,7 @@ impl Model {
Model::Claude37Sonnet => (ANTHROPIC, CLAUDE_37_SONNET),
Model::Claude4Sonnet => (ANTHROPIC, CLAUDE_4_SONNET),
Model::Claude45Sonnet => (ANTHROPIC, CLAUDE_45_SONNET),
+ Model::Claude46Sonnet => (ANTHROPIC, CLAUDE_46_SONNET),
Model::Claude45Haiku => (ANTHROPIC, CLAUDE_45_HAIKU),
Model::Claude45Opus => (ANTHROPIC, CLAUDE_45_OPUS),
Model::Claude46Opus => (ANTHROPIC, CLAUDE_46_OPUS),
diff --git a/rust/cloud-storage/ai/src/types/providers/openai/request.rs b/rust/cloud-storage/ai/src/types/providers/openai/request.rs
index 1671c95573..fe70d81ddc 100644
--- a/rust/cloud-storage/ai/src/types/providers/openai/request.rs
+++ b/rust/cloud-storage/ai/src/types/providers/openai/request.rs
@@ -61,7 +61,11 @@ impl ChatCompletionRequest {
CreateChatCompletionRequestArgs::default()
.stream(stream)
- .model(self.model.to_string())
+ .model(format!(
+ "{}/{}",
+ self.model.to_provider_model_string().0,
+ self.model
+ ))
.messages(self.openai_messages())
.response_format(response_format)
.build()
diff --git a/rust/cloud-storage/ai/src/types/request_builder.rs b/rust/cloud-storage/ai/src/types/request_builder.rs
index 76187cce23..6e3f5cb056 100644
--- a/rust/cloud-storage/ai/src/types/request_builder.rs
+++ b/rust/cloud-storage/ai/src/types/request_builder.rs
@@ -1,6 +1,9 @@
use crate::{
traits::TextAttachment,
- types::{ChatCompletionRequest, ChatMessage, ImageData, Model, Role, SystemPrompt},
+ types::{
+ ChatCompletionRequest, ChatMessage, ChatMessageContent, ImageData, Model, Role,
+ SystemPrompt,
+ },
};
#[derive(Default)]
@@ -187,6 +190,17 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {
self
}
+ pub fn user_message(
+ self,
+ message: impl Into<String>,
+ ) -> RequestBuilder<ChatModel, Vec<ChatMessage>, Prompt> {
+ self.messages(vec![ChatMessage {
+ content: ChatMessageContent::Text(message.into()),
+ image_urls: None,
+ role: Role::User,
+ }])
+ }
+
// set messages
pub fn messages(
self,
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 6af62c5714..ea5fc73bd8 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -26,7 +26,7 @@ pub use tool_context::*;
pub type AiToolSet = AsyncToolSet<ToolServiceContext>;
pub struct ToolSetWithPrompt {
- pub toolset: AiToolSet,
+ pub toolset: Arc<AiToolSet>,
pub prompt: &'static str,
}
@@ -50,6 +50,7 @@ pub fn all_tools() -> ToolSetWithPrompt {
.add_subtoolset::<ToolDocumentToolContext>(document_toolset())
.expect("failed to add document toolset");
let prompt = prompts::TOOLS_PROMPT;
+ let toolset = Arc::new(toolset);
ToolSetWithPrompt { toolset, prompt }
}
@@ -67,6 +68,6 @@ pub fn all_tool_schemas() -> ToolSchemas {
pub fn no_tools() -> ToolSetWithPrompt {
ToolSetWithPrompt {
prompt: prompts::BASE_PROMPT,
- toolset: AsyncToolSet::new(),
+ toolset: Arc::new(AsyncToolSet::new()),
}
}
diff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rs
index 1f1adbcfb7..a67cf82785 100644
--- a/rust/cloud-storage/ai_toolset/src/context.rs
+++ b/rust/cloud-storage/ai_toolset/src/context.rs
@@ -27,7 +27,7 @@ impl<S> DerefMut for ServiceContext<S> {
#[derive(Clone)]
pub struct RequestContext {
/// The ID of the user making the request.
- pub user_id: Arc<MacroUserIdStr<'static>>,
+ pub user_id: MacroUserIdStr<'static>,
/// The JWT token for the request.
#[deprecated(note = "Do not add new dependencies on this field")]
pub jwt: Arc<String>,
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index d008913bb9..7c5749c824 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -74,6 +74,7 @@ log = { workspace = true }
macro_auth = { path = "../macro_auth" }
model-entity = { path = "../model-entity" }
macro_cors = { path = "../macro_cors" }
+memory = { path = "../memory" }
macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs
index ea75f973cd..c775ecd62a 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs
@@ -166,7 +166,7 @@ pub async fn handler(
#[expect(deprecated)]
let request_context = RequestContext {
- user_id: Arc::new(user.macro_user_id),
+ user_id: user.macro_user_id,
jwt: Arc::new(String::new()),
};
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index 8d4c6c1d79..941645a608 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -27,6 +27,9 @@ pub type DcsScribe =
pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
+pub type DcsMemoryService =
+ memory::domain::service::MemoryServiceImpl<memory::outbound::pg_memory_repo::PgMemoryRepo>;
+
#[derive(Clone, FromRef)]
pub struct ApiContext {
pub db: PgPool,
@@ -44,6 +47,7 @@ pub struct ApiContext {
pub soup_service: Arc<ToolSoupService>,
pub stream_repo: Arc<dyn StreamRepo>,
pub document_tool_context: ToolDocumentToolContext,
+ pub memory_service: Arc<DcsMemoryService>,
}
pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index cb991c622b..2315e22f63 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -249,13 +249,31 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
test_lexical_client,
);
+ let search_service_client = Arc::new(search_service_client);
+ let scribe = Arc::new(content_client);
+
+ let memory_tool_context = ai_tools::ToolServiceContext {
+ search_service_client: search_service_client.clone(),
+ email_service_client: email_service_client_external.clone(),
+ scribe: scribe.clone(),
+ soup_service: soup_service.clone(),
+ document_tool_context: document_tool_context.clone(),
+ };
+ let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
+ let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(
+ pool.clone(),
+ memory_repo,
+ memory_tool_context,
+ ai_tools::all_tools(),
+ ));
+
let api_context = ApiContext {
db: pool.clone(),
sqs_client: Arc::new(sqs_client),
document_storage_client,
comms_service_client,
- search_service_client: Arc::new(search_service_client),
- scribe: Arc::new(content_client),
+ search_service_client,
+ scribe,
email_service_client_external,
jwt_args: JwtValidationArgs::new_testing(),
config: Arc::new(Config::new_empty_for_test()),
@@ -265,6 +283,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
soup_service,
stream_repo: MockStreamRepo::new(),
document_tool_context,
+ memory_service,
};
Arc::new(api_context)
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
index da7e1e911d..ed64b76f9c 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
@@ -70,6 +70,8 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {
}
fn api_router(api_context: ApiContext) -> Router {
+ let memory_service = api_context.memory_service.clone();
+
let internal_router = Router::new()
.nest("/chats", chats::router(api_context.clone()))
.nest("/stream", stream::router(api_context.clone()))
@@ -77,6 +79,7 @@ fn api_router(api_context: ApiContext) -> Router {
.nest("/citations", citations::router())
.nest("/preview", preview::router())
.nest("/id_mapping", id_mapping::router())
+ .merge(memory::inbound::axum_router::memory_router(memory_service))
.with_state(api_context.clone())
.route(
"/chat/completions",
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
index a3e220d246..e153e551d9 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
@@ -23,6 +23,7 @@ use axum::response::IntoResponse;
use futures::StreamExt;
use macro_db_client::dcs::create_chat;
use macro_user_id::user_id::MacroUserIdStr;
+use memory::domain::MemoryService;
use model::chat::ChatAttachmentWithName;
use model::user::UserContext;
use model_entity::EntityType;
@@ -227,18 +228,33 @@ pub async fn send_chat_message(
}
})?;
+ // Fetch user memory (triggers background generation if stale/missing)
+ let user_memory = ctx
+ .memory_service
+ .get_or_generate_memory((*user_id).clone())
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "failed to fetch user memory"))
+ .ok()
+ .flatten();
+
// Build the completion request
let toolset = choose_toolset(&payload);
- let ai_request =
- build_chat_completion_request(ctx.clone(), &chat, &payload, toolset.prompt, &jwt_token)
- .await
- .map_err(|err| {
- tracing::error!(error=?err, "failed to build chat completion request");
- ChatMessageError {
- error: "Failed to build request".to_string(),
- stream_id: Some(stream_id.clone()),
- }
- })?;
+ let ai_request = build_chat_completion_request(
+ ctx.clone(),
+ &chat,
+ &payload,
+ toolset.prompt,
+ &jwt_token,
+ user_memory.as_deref(),
+ )
+ .await
+ .map_err(|err| {
+ tracing::error!(error=?err, "failed to build chat completion request");
+ ChatMessageError {
+ error: "Failed to build request".to_string(),
+ stream_id: Some(stream_id.clone()),
+ }
+ })?;
// Log time to send request
log::log_timing(log::LatencyMetric::TimeToSendRequest, model, now.elapsed());
@@ -255,7 +271,7 @@ pub async fn send_chat_message(
ctx.clone(),
ai_request,
toolset.toolset,
- user_id.clone(),
+ (*user_id).clone(),
jwt_token,
actual_chat_id.clone(),
message_id.clone(),
@@ -326,8 +342,8 @@ async fn create_new_chat(
fn stream_and_save_message(
ctx: Arc<ApiContext>,
request: ai::types::ChatCompletionRequest,
- toolset: AiToolSet,
- user_id: Arc<MacroUserIdStr<'static>>,
+ toolset: Arc<AiToolSet>,
+ user_id: MacroUserIdStr<'static>,
jwt_token: String,
chat_id: String,
message_id: String,
@@ -525,7 +541,7 @@ fn stream_and_save_message(
chat_id.clone(),
message_id.clone(),
text,
- user_id.as_ref().clone(),
+ user_id.clone(),
);
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs
index 5536cb46d0..9fd4a9243e 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs
@@ -17,6 +17,7 @@ pub async fn build_chat_completion_request(
incoming_message: &SendChatMessagePayload,
static_system_prompt: &str,
jwt: &str,
+ user_memory: Option<&str>,
) -> Result<ChatCompletionRequest> {
let attachments = fetch::fetchium(
ctx.scribe.clone(),
@@ -48,7 +49,13 @@ pub async fn build_chat_completion_request(
.as_deref()
.unwrap_or_default();
- let system_prompt = format!("{}\n{}", static_system_prompt, additional_instructions);
+ let mut system_prompt = format!("{}\n{}", static_system_prompt, additional_instructions);
+
+ if let Some(memory) = user_memory {
+ system_prompt.push_str("\n\n<user_memory>\n");
+ system_prompt.push_str(memory);
+ system_prompt.push_str("\n</user_memory>");
+ }
Ok(RequestBuilder::new()
.attachments(attachments)
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index 7878e63f27..f88d7d2741 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -14,6 +14,7 @@ use crate::model::{
},
stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},
};
+use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryResponse};
use crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};
@@ -64,7 +65,8 @@ use utoipa::OpenApi;
get_batch_preview::handler,
chat_history::get_chat_history_handler,
chat_history_batch_messages::get_chat_history_batch_messages_handler,
- chat_message::send_chat_message
+ chat_message::send_chat_message,
+ memory_api::get_memory_handler
),
components(
schemas(
@@ -133,6 +135,10 @@ use utoipa::OpenApi;
StreamError,
ToolSet,
+ // Memory
+ MemoryResponse,
+ MemoryErrorBody,
+
// Tools
ai::tool::schema::ToolSchema,
ai::tool::schema::ToolSchemas,
diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rs
index ea163c2e6c..bbe541e90f 100644
--- a/rust/cloud-storage/document_cognition_service/src/config.rs
+++ b/rust/cloud-storage/document_cognition_service/src/config.rs
@@ -1,6 +1,5 @@
-use anyhow::Context;
pub use macro_env::Environment;
-use macro_env_var::env_var;
+use macro_env_var::{env_var, maybe_env_var};
use crate::core::constants::DEFAULT_DOCUMENT_BATCH_LIMIT;
/// The configuration parameters for the application.
@@ -56,112 +55,100 @@ pub struct Config {
env_var!(
pub struct EnvVars {
+ pub DatabaseUrl,
+ pub DocumentStorageBucket,
+ pub DocumentTextExtractorQueue,
+ pub ChatDeleteQueue,
+ pub NotificationQueue,
+ pub DocumentStorageServiceUrl,
+ pub SearchEventQueue,
+ pub SyncServiceUrl,
+ pub SyncServiceAuthKey,
+ pub LexicalServiceUrl,
+ pub EmailServiceUrl,
+ pub StaticFileServiceUrl,
+ pub AuthenticationServiceUrl,
+ pub AuthenticationServiceSecretKey,
pub RedisHost,
+ pub DocxDocumentUploadBucket,
+ pub DocumentStorageServiceCloudfrontDistributionUrl,
+ pub DocumentStorageServiceCloudfrontSignerPublicKeyId,
+ pub DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
+ }
+);
+
+maybe_env_var!(
+ pub struct MaybeEnvVars {
+ pub Port,
+ pub DocumentBatchLimit,
}
);
impl Config {
#[tracing::instrument(err, skip_all)]
pub fn from_env(env_vars: EnvVars) -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
- let port: usize = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .unwrap();
- let environment = Environment::new_or_prod();
-
- let document_batch_limit = match std::env::var("DOCUMENT_BATCH_LIMIT") {
- Ok(val) => val.parse::<i64>().unwrap_or(DEFAULT_DOCUMENT_BATCH_LIMIT),
- Err(_) => DEFAULT_DOCUMENT_BATCH_LIMIT,
- };
-
- let document_storage_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")
- .context("DOCUMENT_STORAGE_BUCKET environment variable not set")?;
-
- let document_text_extractor_queue = std::env::var("DOCUMENT_TEXT_EXTRACTOR_QUEUE")
- .context("DOCUMENT_TEXT_EXTRACTOR_QUEUE environment variable not set")?;
-
- let chat_delete_queue = std::env::var("CHAT_DELETE_QUEUE")
- .context("CHAT_DELETE_QUEUE environment variable not set")?;
-
- let notification_queue =
- std::env::var("NOTIFICATION_QUEUE").context("NOTIFICATION_QUEUE must be provided")?;
-
- let document_storage_service_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")
- .context("DOCUMENT_STORAGE_SERVICE_URL must be provided")?;
+ let maybe = MaybeEnvVars::new();
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
-
- let sync_service_url =
- std::env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be provided")?;
-
- let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY")
- .context("SYNC_SERVICE_AUTH_KEY must be provided")?;
-
- let lexical_service_url =
- std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be provided")?;
+ let port: usize = maybe.port.as_deref().unwrap_or("8080").parse().unwrap();
+ let environment = Environment::new_or_prod();
- let email_service_url =
- std::env::var("EMAIL_SERVICE_URL").context("EMAIL_SERVICE_URL must be provided")?;
+ let document_batch_limit = maybe
+ .document_batch_limit
+ .as_deref()
+ .and_then(|v| v.parse::<i64>().ok())
+ .unwrap_or(DEFAULT_DOCUMENT_BATCH_LIMIT);
let document_cognition_service_url = format!("http://127.0.0.1:{}", port);
- let static_file_service_url = std::env::var("STATIC_FILE_SERVICE_URL")
- .context("STATIC_FILE_SERVICE_URL must be provided")?;
-
- let authentication_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")
- .context("AUTHENTICATION_SERVICE_URL must be provided")?;
-
- let authentication_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
- .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;
-
- let docx_document_upload_bucket = std::env::var("DOCX_DOCUMENT_UPLOAD_BUCKET")
- .context("DOCX_DOCUMENT_UPLOAD_BUCKET must be provided")?;
-
- let cloudfront_distribution_url =
- std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")
- .context("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be provided")?;
-
- let cloudfront_signer_public_key_id = std::env::var(
- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID",
- )
- .context("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be provided")?;
-
- let cloudfront_signer_private_key = std::env::var(
- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME",
- )
- .context(
- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME must be provided",
- )?;
-
- let EnvVars { redis_host } = env_vars;
-
- Ok(Config {
+ let EnvVars {
database_url,
- port,
- environment,
- document_batch_limit,
document_storage_bucket,
- document_storage_service_url,
document_text_extractor_queue,
chat_delete_queue,
notification_queue,
+ document_storage_service_url,
search_event_queue,
- sync_service_auth_key,
sync_service_url,
+ sync_service_auth_key,
lexical_service_url,
email_service_url,
- document_cognition_service_url,
static_file_service_url,
authentication_service_url,
authentication_service_secret_key,
redis_host,
docx_document_upload_bucket,
- cloudfront_distribution_url,
- cloudfront_signer_public_key_id,
- cloudfront_signer_private_key,
+ document_storage_service_cloudfront_distribution_url,
+ document_storage_service_cloudfront_signer_public_key_id,
+ document_storage_service_cloudfront_signer_private_key_secret_name,
+ } = env_vars;
+
+ Ok(Config {
+ database_url: database_url.to_string(),
+ port,
+ environment,
+ document_batch_limit,
+ document_storage_bucket: document_storage_bucket.to_string(),
+ document_storage_service_url: document_storage_service_url.to_string(),
+ document_text_extractor_queue: document_text_extractor_queue.to_string(),
+ chat_delete_queue: chat_delete_queue.to_string(),
+ notification_queue: notification_queue.to_string(),
+ search_event_queue: search_event_queue.to_string(),
+ sync_service_auth_key: sync_service_auth_key.to_string(),
+ sync_service_url: sync_service_url.to_string(),
+ lexical_service_url: lexical_service_url.to_string(),
+ email_service_url: email_service_url.to_string(),
+ document_cognition_service_url,
+ static_file_service_url: static_file_service_url.to_string(),
+ authentication_service_url: authentication_service_url.to_string(),
+ authentication_service_secret_key: authentication_service_secret_key.to_string(),
+ redis_host,
+ docx_document_upload_bucket: docx_document_upload_bucket.to_string(),
+ cloudfront_distribution_url: document_storage_service_cloudfront_distribution_url
+ .to_string(),
+ cloudfront_signer_public_key_id:
+ document_storage_service_cloudfront_signer_public_key_id.to_string(),
+ cloudfront_signer_private_key:
+ document_storage_service_cloudfront_signer_private_key_secret_name.to_string(),
})
}
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 07b13f616a..79b4d11fe3 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -248,30 +248,53 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized document tool context");
+ let email_service_client_external = Arc::new(EmailServiceClientExternal::new(
+ email_service_client.url().to_owned(),
+ ));
+
+ let scribe = Arc::new(
+ ScribeClient::new()
+ .with_document_client(
+ DocumentClient::builder()
+ .with_dss_client(document_storage_client.clone())
+ .with_lexical_client(lexical_client)
+ .with_sync_service_client(sync_service_client.clone())
+ .with_macro_db(db.clone())
+ .build(),
+ )
+ .with_channel_client_and_db(comms_service_client.clone(), db.clone())
+ .with_dcs_client(document_cognition_service_client)
+ .with_email_client(email_service_client)
+ .with_static_file_client(static_file_service_client.clone()),
+ );
+ let search_service_client = Arc::new(search_service_client);
+
+ // Build memory service
+ let memory_tool_context = ai_tools::ToolServiceContext {
+ search_service_client: search_service_client.clone(),
+ email_service_client: email_service_client_external.clone(),
+ scribe: scribe.clone(),
+ soup_service: soup_service.clone(),
+ document_tool_context: document_tool_context.clone(),
+ };
+ let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(db.clone());
+ let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(
+ db.clone(),
+ memory_repo,
+ memory_tool_context,
+ ai_tools::all_tools(),
+ ));
+
+ tracing::info!("initialized memory service");
+
api::setup_and_serve(ApiContext {
db: db.clone(),
- email_service_client_external: Arc::new(EmailServiceClientExternal::new(
- email_service_client.url().to_owned(),
- )),
- scribe: Arc::new(
- ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(document_storage_client.clone())
- .with_lexical_client(lexical_client)
- .with_sync_service_client(sync_service_client.clone())
- .with_macro_db(db.clone())
- .build(),
- )
- .with_channel_client_and_db(comms_service_client.clone(), db.clone())
- .with_dcs_client(document_cognition_service_client)
- .with_email_client(email_service_client)
- .with_static_file_client(static_file_service_client.clone()),
- ),
+ email_service_client_external,
+ scribe,
sqs_client: Arc::new(sqs_client),
document_storage_client: Arc::new(document_storage_client),
comms_service_client: Arc::new(comms_service_client),
- search_service_client: Arc::new(search_service_client),
+ search_service_client,
jwt_args,
config: Arc::new(config),
internal_auth_key,
@@ -280,6 +303,7 @@ async fn main() -> anyhow::Result<()> {
soup_service,
stream_repo,
document_tool_context,
+ memory_service,
})
.await
.context("failed to setup and serve api")?;
diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs
index f3f2737807..a35fef8d56 100644
--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs
+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs
@@ -13,13 +13,13 @@ use super::middleware::McpUserIdentity;
/// MCP server handler that extracts authenticated user identity from HTTP
/// request parts injected by rmcp's `StreamableHttpService`.
pub struct AuthenticatedToolService<Context> {
- toolset: AsyncToolSet<Context>,
+ toolset: Arc<AsyncToolSet<Context>>,
context: Context,
}
impl<Context> AuthenticatedToolService<Context> {
/// Create a new authenticated tool service.
- pub fn new(toolset: AsyncToolSet<Context>, context: Context) -> Self {
+ pub fn new(toolset: Arc<AsyncToolSet<Context>>, context: Context) -> Self {
Self { toolset, context }
}
}
@@ -93,7 +93,7 @@ where
#[allow(deprecated)]
let request_context = RequestContext {
jwt: Arc::new(identity.jwt.clone()),
- user_id: Arc::new(user_id),
+ user_id,
};
let arguments = request
diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rs
index 2c5a7e74db..4ade7fb042 100644
--- a/rust/cloud-storage/documents/examples/documents_toolset.rs
+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs
@@ -146,7 +146,7 @@ async fn main() {
let toolset = document_toolset();
let context = RequestContext {
- user_id: Arc::new(user_id),
+ user_id,
// Remove this later
#[allow(deprecated)]
jwt: Arc::new(String::new()),
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
index b74b1c9683..3523ad5fec 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
@@ -66,7 +66,7 @@ where
})?;
let content_type = parsed_file_type.mime_type();
- let user_id: MacroUserIdStr<'static> = (*request_context.user_id).clone();
+ let user_id: MacroUserIdStr<'static> = request_context.user_id.clone();
let file_bytes = self.file_content.as_bytes();
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
index 92d9ad7efe..2db9866348 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
@@ -80,7 +80,7 @@ where
let entity_access_receipt = service_context
.entity_access_service
.generate_entity_access_receipt(
- request_context.user_id.as_ref(),
+ &request_context.user_id,
None,
&self.document_id.to_string(),
EntityType::Document,
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
index d1b379ff55..df3a8cc839 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
@@ -51,7 +51,7 @@ where
let entity_access_receipt = service_context
.entity_access_service
.generate_entity_access_receipt(
- request_context.user_id.as_ref(),
+ &request_context.user_id,
None,
&self.document_id.to_string(),
EntityType::Document,
diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rs
index df40e0d179..adcf599e7b 100644
--- a/rust/cloud-storage/email/examples/ai_tools_cli.rs
+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs
@@ -98,7 +98,7 @@ async fn main() {
#[expect(deprecated)]
let context = RequestContext {
- user_id: Arc::new(user_id),
+ user_id,
jwt: Arc::new(String::new()),
};
diff --git a/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs b/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
index 683696cfc6..9721ad213c 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
@@ -7,6 +7,7 @@ use crate::domain::{
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::user_id::MacroUserIdStr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -94,7 +95,7 @@ where
tracing::info!("Create draft");
let link = service_context
- .resolve_link((*request_context.user_id).clone())
+ .resolve_link(MacroUserIdStr((*request_context.user_id).clone()))
.await?;
let input = CreateDraftInput {
diff --git a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
index 92c9216683..f6eca1250e 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
@@ -7,6 +7,7 @@ use crate::domain::{
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::user_id::MacroUserIdStr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -76,7 +77,7 @@ where
tracing::info!("List labels");
let link = service_context
- .resolve_link((*request_context.user_id).clone())
+ .resolve_link(MacroUserIdStr((*request_context.user_id).clone()))
.await?;
let labels = service_context
diff --git a/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs
index 748e5b2f46..c0d7b59c15 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs
@@ -4,6 +4,7 @@ use crate::domain::ports::{EmailService, GmailTokenProvider};
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::user_id::MacroUserIdStr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -60,7 +61,7 @@ where
tracing::info!("Update thread labels");
let link = service_context
- .resolve_link((*request_context.user_id).clone())
+ .resolve_link(MacroUserIdStr((*request_context.user_id).clone()))
.await?;
let access_token = service_context.resolve_access_token(&link).await?;
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 31cc921df8..888cb7a271 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -87,6 +87,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./github/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./referral/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./chat/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./memory/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
new file mode 100644
index 0000000000..d2b084cf10
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
new file mode 100644
index 0000000000..6d97183829
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json b/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json
new file mode 100644
index 0000000000..505a2bd912
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = $2\n WHERE entity_id = $1\n AND property_definition_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Jsonb",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
new file mode 100644
index 0000000000..9d717fa5f9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "values",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
new file mode 100644
index 0000000000..182e0858ba
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260323000000_create_memory_table.sql b/rust/cloud-storage/macro_db_client/migrations/20260323000000_create_memory_table.sql
new file mode 100644
index 0000000000..37ec72c711
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260323000000_create_memory_table.sql
@@ -0,0 +1,10 @@
+CREATE TABLE memory (
+ id UUID PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ memory TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX memory_user_id_idx ON memory (user_id);
+CREATE INDEX memory_user_id_created_at_idx ON memory (user_id, created_at DESC);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260323170000_memory_unique_user_id.sql b/rust/cloud-storage/macro_db_client/migrations/20260323170000_memory_unique_user_id.sql
new file mode 100644
index 0000000000..1ff2877c33
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260323170000_memory_unique_user_id.sql
@@ -0,0 +1,4 @@
+-- One memory per user; upsert overwrites on new generation.
+DROP INDEX memory_user_id_idx;
+DROP INDEX memory_user_id_created_at_idx;
+ALTER TABLE memory ADD CONSTRAINT memory_user_id_unique UNIQUE (user_id);
diff --git a/rust/cloud-storage/macro_uuid/src/lib.rs b/rust/cloud-storage/macro_uuid/src/lib.rs
index 717c317b88..c9ae41bdc1 100644
--- a/rust/cloud-storage/macro_uuid/src/lib.rs
+++ b/rust/cloud-storage/macro_uuid/src/lib.rs
@@ -1,5 +1,6 @@
use anyhow::{Result, anyhow};
-use uuid::{NoContext, Timestamp, Uuid};
+pub use uuid::Uuid;
+use uuid::{NoContext, Timestamp};
pub fn generate_uuid_v7() -> Uuid {
Uuid::new_v7(Timestamp::now(NoContext))
diff --git a/rust/cloud-storage/memory/.sqlx/query-343e4f6931752a30ceb2e078834aacd0a8486948494a4dc14b62e943590e97f6.json b/rust/cloud-storage/memory/.sqlx/query-343e4f6931752a30ceb2e078834aacd0a8486948494a4dc14b62e943590e97f6.json
new file mode 100644
index 0000000000..3d96b51e53
--- /dev/null
+++ b/rust/cloud-storage/memory/.sqlx/query-343e4f6931752a30ceb2e078834aacd0a8486948494a4dc14b62e943590e97f6.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT memory, created_at as \"created_at!\"\n FROM memory\n WHERE user_id = $1\n ORDER BY created_at DESC\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "memory",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "343e4f6931752a30ceb2e078834aacd0a8486948494a4dc14b62e943590e97f6"
+}
diff --git a/rust/cloud-storage/memory/.sqlx/query-b101ce64403b1af489e1cafdd07cbfc71039effb4d2869606534765bce7b17fc.json b/rust/cloud-storage/memory/.sqlx/query-b101ce64403b1af489e1cafdd07cbfc71039effb4d2869606534765bce7b17fc.json
new file mode 100644
index 0000000000..3cf399f742
--- /dev/null
+++ b/rust/cloud-storage/memory/.sqlx/query-b101ce64403b1af489e1cafdd07cbfc71039effb4d2869606534765bce7b17fc.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO memory (id, user_id, memory)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id) DO UPDATE\n SET memory = EXCLUDED.memory,\n updated_at = NOW()\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b101ce64403b1af489e1cafdd07cbfc71039effb4d2869606534765bce7b17fc"
+}
diff --git a/rust/cloud-storage/memory/.sqlx/query-da59b393b3c5c2cc664c6ac89fb05dec57b4fb5d0b4ea2def2c8c4978c1d9c36.json b/rust/cloud-storage/memory/.sqlx/query-da59b393b3c5c2cc664c6ac89fb05dec57b4fb5d0b4ea2def2c8c4978c1d9c36.json
new file mode 100644
index 0000000000..648acdb6cb
--- /dev/null
+++ b/rust/cloud-storage/memory/.sqlx/query-da59b393b3c5c2cc664c6ac89fb05dec57b4fb5d0b4ea2def2c8c4978c1d9c36.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT memory\n FROM memory\n WHERE id = $1 AND user_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "memory",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "da59b393b3c5c2cc664c6ac89fb05dec57b4fb5d0b4ea2def2c8c4978c1d9c36"
+}
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
new file mode 100644
index 0000000000..ddc2ca24cf
--- /dev/null
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -0,0 +1,47 @@
+[package]
+name = "memory"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+
+[dependencies]
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+thiserror = { workspace = true }
+ai_tools = { path = "../ai_tools" }
+ai_toolset = { path = "../ai_toolset" }
+ai = { path = "../ai" }
+futures = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+chrono = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+anyhow = { workspace = true }
+axum = { workspace = true }
+model_user = { path = "../model_user", features = ["axum"] }
+tracing = { workspace = true }
+utoipa = { workspace = true }
+macro_entrypoint = { path = "../macro_entrypoint" }
+
+# For building ToolServiceContext
+comms = { path = "../comms" }
+documents = { path = "../documents" }
+email = { path = "../email" }
+entity_access = { path = "../entity_access" }
+frecency = { path = "../frecency" }
+lexical_client = { path = "../lexical_client" }
+scribe = { path = "../scribe" }
+search_service_client = { path = "../search_service_client" }
+email_service_client = { path = "../email_service_client" }
+document_storage_service_client = { path = "../document_storage_service_client" }
+comms_service_client = { path = "../comms_service_client" }
+document_cognition_service_client = { path = "../document_cognition_service_client" }
+static_file_service_client = { path = "../static_file_service_client" }
+sync_service_client = { path = "../sync_service_client" }
+soup = { path = "../soup", features = ["all"] }
+macro_aws_config = { path = "../macro_aws_config" }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
new file mode 100644
index 0000000000..85d7e90e31
--- /dev/null
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -0,0 +1,153 @@
+use ai_tools::{NoOpConnectionService, NoOpTaskProperties, ToolServiceContext};
+use comms::domain::service::ChannelServiceImpl;
+use comms::outbound::postgres::comms_repo::PgCommsRepo;
+use comms::outbound::postgres::user_repo::PgUserRepo;
+use document_cognition_service_client::DocumentCognitionServiceClient;
+use document_storage_service_client::DocumentStorageServiceClient;
+use documents::domain::models::CloudFrontConfig;
+use documents::inbound::toolset::DocumentToolContext;
+use documents::outbound::pg_document_repo::PgDocumentRepo;
+use documents::outbound::s3_upload_url::S3UploadUrlAdapter;
+use email::domain::service::EmailServiceImpl;
+use email::outbound::EmailPgRepo;
+use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
+use entity_access::domain::service::EntityAccessServiceImpl;
+use entity_access::outbound::PgAccessRepository;
+use frecency::domain::services::FrecencyQueryServiceImpl;
+use frecency::outbound::postgres::FrecencyPgStorage;
+use lexical_client::LexicalClient;
+use scribe::ScribeClient;
+use scribe::document::DocumentClient;
+use search_service_client::SearchServiceClient;
+use soup::domain::service::SoupImpl;
+use soup::outbound::pg_soup_repo::PgSoupRepo;
+use static_file_service_client::StaticFileServiceClient;
+use std::sync::Arc;
+use sync_service_client::SyncServiceClient;
+
+/// Builds a [`ToolServiceContext`] from environment variables and a database pool.
+///
+/// Required env vars: `INTERNAL_API_SECRET_KEY`, `DOCUMENT_STORAGE_SERVICE_URL`,
+/// `SEARCH_SERVICE_URL`, `EMAIL_SERVICE_URL`, `SYNC_SERVICE_URL`,
+/// `DOCUMENT_COGNITION_SERVICE_URL`, `STATIC_FILE_SERVICE_URL`,
+/// `DOCUMENT_STORAGE_BUCKET`, `DOCX_DOCUMENT_UPLOAD_BUCKET`,
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`,
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`
+#[tracing::instrument(skip(pool), err)]
+pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<ToolServiceContext> {
+ let internal_auth_key =
+ std::env::var("INTERNAL_API_SECRET_KEY").unwrap_or_else(|_| "local".into());
+ let dss_url = std::env::var("DOCUMENT_STORAGE_SERVICE_URL")?;
+ let search_url = std::env::var("SEARCH_SERVICE_URL")?;
+ let email_url = std::env::var("EMAIL_SERVICE_URL")?;
+ let sync_url = std::env::var("SYNC_SERVICE_URL")?;
+ let dcs_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")?;
+ let sfs_url = std::env::var("STATIC_FILE_SERVICE_URL")?;
+ let comms_url =
+ std::env::var("COMMS_SERVICE_URL").unwrap_or_else(|_| "http://localhost:8080".into());
+ let lexical_url =
+ std::env::var("LEXICAL_SERVICE_URL").unwrap_or_else(|_| "http://localhost:8096".into());
+ let doc_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")?;
+ let docx_bucket = std::env::var("DOCX_DOCUMENT_UPLOAD_BUCKET")?;
+ let cf_dist_url = std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")?;
+ let cf_key_id = std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID")?;
+ let cf_private_key =
+ std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME")?;
+
+ // Service clients
+ let dss_client = Arc::new(DocumentStorageServiceClient::new(
+ internal_auth_key.clone(),
+ dss_url,
+ ));
+ let comms_client = Arc::new(comms_service_client::CommsServiceClient::new(comms_url));
+ let search_client = Arc::new(SearchServiceClient::new(
+ internal_auth_key.clone(),
+ search_url,
+ ));
+ let sync_client = Arc::new(SyncServiceClient::new(internal_auth_key.clone(), sync_url));
+ let email_client = Arc::new(EmailServiceClient::new(
+ internal_auth_key.clone(),
+ email_url.clone(),
+ ));
+ let dcs_client = Arc::new(DocumentCognitionServiceClient::new(
+ internal_auth_key.clone(),
+ dcs_url,
+ ));
+ let sfs_client = Arc::new(StaticFileServiceClient::new(
+ internal_auth_key.clone(),
+ sfs_url,
+ ));
+ let email_ext_client = Arc::new(EmailServiceClientExternal::new(email_url));
+ let lexical_client = LexicalClient::new(internal_auth_key, lexical_url);
+
+ // Scribe
+ let scribe = Arc::new(
+ ScribeClient::new()
+ .with_document_client(
+ DocumentClient::builder()
+ .with_dss_client(dss_client.clone())
+ .with_lexical_client(Arc::new(lexical_client.clone()))
+ .with_sync_service_client(sync_client.clone())
+ .with_macro_db(pool.clone())
+ .build(),
+ )
+ .with_channel_client_and_db(comms_client, pool.clone())
+ .with_dcs_client(dcs_client)
+ .with_email_client(email_client)
+ .with_static_file_client(sfs_client),
+ );
+
+ // Soup service
+ let frecency_storage = FrecencyPgStorage::new(pool.clone());
+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
+ let email_service = EmailServiceImpl::new(
+ EmailPgRepo::new(pool.clone()),
+ frecency_service.clone(),
+ email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
+ 0,
+ );
+ let channels_service = ChannelServiceImpl::new(
+ PgCommsRepo { pool: pool.clone() },
+ PgUserRepo::new(pool.clone()),
+ frecency_storage,
+ );
+ let soup_service = Arc::new(SoupImpl::new(
+ PgSoupRepo::new(pool.clone()),
+ frecency_service,
+ email_service,
+ channels_service,
+ ));
+
+ // Document tool context
+ let s3_client = macro_aws_config::s3_client().await;
+ let s3_upload_adapter = S3UploadUrlAdapter::new(s3_client, &doc_bucket, &docx_bucket);
+ let document_repo = PgDocumentRepo::new(pool.clone());
+ let cloudfront_config = CloudFrontConfig {
+ distribution_url: cf_dist_url,
+ signer_public_key_id: cf_key_id,
+ signer_private_key: cf_private_key,
+ presigned_url_expiry_seconds: 3600,
+ browser_cache_expiry_seconds: 86400,
+ };
+ let document_service = documents::domain::service::DocumentServiceImpl::new(
+ document_repo,
+ cloudfront_config,
+ sync_client.as_ref().clone(),
+ s3_upload_adapter,
+ NoOpTaskProperties,
+ NoOpConnectionService,
+ );
+ let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone()));
+ let document_tool_context =
+ DocumentToolContext::new(document_service, entity_access_service, lexical_client);
+
+ Ok(ToolServiceContext {
+ search_service_client: search_client,
+ email_service_client: email_ext_client,
+ scribe,
+ soup_service,
+ document_tool_context,
+ })
+}
diff --git a/rust/cloud-storage/memory/src/domain/mod.rs b/rust/cloud-storage/memory/src/domain/mod.rs
new file mode 100644
index 0000000000..444f148b01
--- /dev/null
+++ b/rust/cloud-storage/memory/src/domain/mod.rs
@@ -0,0 +1,4 @@
+pub mod ports;
+pub mod service;
+
+pub use ports::*;
diff --git a/rust/cloud-storage/memory/src/domain/ports.rs b/rust/cloud-storage/memory/src/domain/ports.rs
new file mode 100644
index 0000000000..bf70e5fbfc
--- /dev/null
+++ b/rust/cloud-storage/memory/src/domain/ports.rs
@@ -0,0 +1,55 @@
+use ai::types::AiError;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum MemoryError {
+ #[error(transparent)]
+ AiError(#[from] AiError),
+ #[error("Nothing was generated")]
+ NoGeneration,
+ #[error("memory rejected by judge: {0}")]
+ Rejected(String),
+ #[error(transparent)]
+ Db(#[from] sqlx::Error),
+ #[error(transparent)]
+ Other(#[from] anyhow::Error),
+}
+
+pub type Result<T> = std::result::Result<T, MemoryError>;
+
+pub type Memory = String;
+
+/// A memory record with its creation timestamp.
+pub struct MemoryRecord {
+ /// The memory text.
+ pub memory: Memory,
+ /// When this memory was generated.
+ pub created_at: DateTime<Utc>,
+}
+
+pub trait MemoryRepo: Send + Sync + 'static {
+ fn save_memory(
+ &self,
+ memory: &Memory,
+ user: MacroUserIdStr,
+ ) -> impl Future<Output = Result<Uuid>> + Send;
+ fn get_latest_memory(
+ &self,
+ user: MacroUserIdStr,
+ ) -> impl Future<Output = Result<Option<MemoryRecord>>> + Send;
+ fn get_memory_by_id(
+ &self,
+ user: MacroUserIdStr,
+ id: Uuid,
+ ) -> impl Future<Output = Result<Memory>> + Send;
+}
+
+pub trait MemoryService: Send + Sync + 'static {
+ fn get_or_generate_memory(
+ &self,
+ user: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Option<Memory>>> + Send;
+}
diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rs
new file mode 100644
index 0000000000..6f1258bbb9
--- /dev/null
+++ b/rust/cloud-storage/memory/src/domain/service.rs
@@ -0,0 +1,217 @@
+use super::ports::*;
+use ai::chat_completion::get_chat_completion;
+use ai::tool::tool_loop::ai_client::ToolLoop;
+use ai::types::*;
+use ai_tools::{ToolServiceContext, ToolSetWithPrompt};
+use ai_toolset::RequestContext;
+use chrono::Utc;
+use futures::stream::StreamExt;
+use serde::Deserialize;
+use std::sync::Arc;
+
+static GENERATION_MODEL: Model = Model::Claude46Opus;
+static JUDGE_MODEL: Model = Model::Claude46Sonnet;
+
+static GENERATE_MEMORY_PROMPT: &str = "\
+Use tool calls to research who I am, what I care about, what I'm working on, \
+and anything else that would be useful as permanent knowledge. Look at my \
+documents, projects, emails, channels, and search for content I've created.
+
+Then generate a ~1000-3000 word memory about me that will be prepended to \
+future prompts to provide personalized answers. Focus on:
+- My role, team, and responsibilities
+- Technologies, tools, and languages I use
+- Current projects and priorities
+- Domain knowledge and expertise
+- Communication style and preferences
+
+Don't include things that would make sense to find via tool search at runtime. \
+Focus on context that is useful as permanent background knowledge.
+
+CRITICAL: Your response must contain ONLY the memory text. \
+No preamble, no postscript, no commentary, no \"Let me...\", no \"Here is...\". \
+Do not narrate your research process. Do not address the user. \
+Just output the raw memory text starting with the first substantive line.";
+
+static JUDGE_PROMPT: &str = "\
+You are a strict quality judge for AI-generated user memory profiles.
+
+A \"memory\" is a ~1000-3000 word summary of a user prepended to future AI prompts \
+for personalization. A good memory is built from rich data: documents the user wrote, \
+projects they manage, emails they sent, channels they participate in, and search results \
+showing their work.
+
+REJECT if ANY of the following are true:
+- The memory is based on insufficient data (e.g. only a handful of chat titles, \
+ no documents, no projects, no emails). A memory built from nearly empty workspace \
+ data is useless speculation.
+- It is mostly guesswork or hedged inferences (\"likely\", \"suggests\", \"may\") \
+ rather than concrete facts derived from actual content.
+- It is under ~500 words of substantive content.
+- It lacks specific details about the user's actual work, codebase, projects, or role.
+- It reads like a personality quiz rather than a professional profile grounded in \
+ real workspace activity.
+- It contains narration about the research process (\"I found...\", \"The workspace has...\").
+
+ACCEPT only if the memory contains concrete, specific, actionable context derived \
+from substantial workspace data (documents, code, projects, emails, messages) that \
+would meaningfully improve future AI interactions.";
+
+#[derive(Debug, Deserialize)]
+struct MemoryJudgement {
+ accepted: bool,
+ reason: String,
+}
+
+pub struct MemoryServiceImpl<Rpo> {
+ db: sqlx::PgPool,
+ memory_repo: Rpo,
+ tool_context: ToolServiceContext,
+ tools: ToolSetWithPrompt,
+}
+
+impl<Rpo> MemoryServiceImpl<Rpo> {
+ pub fn new(
+ db: sqlx::PgPool,
+ memory_repo: Rpo,
+ tool_context: ToolServiceContext,
+ tools: ToolSetWithPrompt,
+ ) -> Self {
+ Self {
+ db,
+ memory_repo,
+ tool_context,
+ tools,
+ }
+ }
+}
+
+/// Default max age for memory freshness (7 days).
+const MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
+
+impl<Rpo> MemoryService for MemoryServiceImpl<Rpo>
+where
+ Rpo: MemoryRepo,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn get_or_generate_memory(
+ &self,
+ user: macro_user_id::user_id::MacroUserIdStr<'static>,
+ ) -> super::Result<Option<Memory>> {
+ let record = self.memory_repo.get_latest_memory(user.clone()).await?;
+
+ let needs_generation = match &record {
+ Some(r) => {
+ let age = Utc::now() - r.created_at;
+ age > chrono::Duration::from_std(MAX_AGE).unwrap_or(chrono::TimeDelta::MAX)
+ }
+ None => true,
+ };
+
+ if needs_generation {
+ let pool = self.db.clone();
+ let tool_context = self.tool_context.clone();
+ let toolset = self.tools.toolset.clone();
+ let prompt = self.tools.prompt;
+ tokio::spawn(async move {
+ let repo = crate::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
+ let tools = ToolSetWithPrompt { toolset, prompt };
+ let svc = MemoryServiceImpl::new(pool, repo, tool_context, tools);
+ match svc.generate_memory(user.clone()).await {
+ Ok(_) => tracing::info!(%user, "memory generated"),
+ Err(MemoryError::Rejected(reason)) => {
+ tracing::warn!(%user, %reason, "memory rejected by judge")
+ }
+ Err(e) => tracing::error!(%user, error = ?e, "memory generation failed"),
+ }
+ });
+ }
+
+ Ok(record.map(|r| r.memory))
+ }
+}
+
+impl<Rpo> MemoryServiceImpl<Rpo>
+where
+ Rpo: MemoryRepo,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn generate_memory(
+ &self,
+ user: macro_user_id::user_id::MacroUserIdStr<'static>,
+ ) -> super::Result<Memory> {
+ let request = RequestBuilder::new()
+ .model(GENERATION_MODEL)
+ .system_prompt(self.tools.prompt)
+ .user_message(GENERATE_MEMORY_PROMPT)
+ .build();
+
+ let mut agent = ToolLoop::new(self.tools.toolset.clone(), self.tool_context.clone()).chat();
+
+ let request_context = RequestContext {
+ user_id: user.clone(),
+ #[allow(deprecated)]
+ jwt: Arc::new("fake_jwt".into()),
+ };
+
+ {
+ let mut stream = agent
+ .send_message(request, request_context, user.clone().into())
+ .await?;
+
+ while let Some(next) = stream.next().await {
+ next?;
+ }
+ }
+
+ let messages = agent.get_new_conversation_messages();
+
+ let Some(memory) = messages.last().and_then(|message| {
+ let text = message.content.message_text();
+ if text.trim().is_empty() {
+ None
+ } else {
+ Some(text)
+ }
+ }) else {
+ return Err(MemoryError::NoGeneration);
+ };
+
+ // 2nd pass: judge the memory quality
+ judge_memory(&memory).await?;
+
+ self.memory_repo.save_memory(&memory, user).await?;
+ Ok(memory)
+ }
+}
+
+#[tracing::instrument(skip(memory), err)]
+async fn judge_memory(memory: &str) -> super::Result<()> {
+ let user_message = format!(
+ "Evaluate this memory and respond with ONLY a JSON object \
+ (no markdown, no code fences):\n\
+ {{\"accepted\": true/false, \"reason\": \"one sentence explanation\"}}\n\n\
+ ---\n\n{memory}"
+ );
+
+ let request = RequestBuilder::new()
+ .model(JUDGE_MODEL)
+ .system_prompt(JUDGE_PROMPT)
+ .user_message(&user_message)
+ .build();
+
+ let response = get_chat_completion(request)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+
+ let judgement: MemoryJudgement = serde_json::from_str(response.trim())
+ .map_err(|e| anyhow::anyhow!("failed to parse judge response: {e}\nraw: {response}"))?;
+
+ tracing::info!(accepted = judgement.accepted, reason = %judgement.reason, "Memory judgement");
+
+ if !judgement.accepted {
+ return Err(MemoryError::Rejected(judgement.reason));
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/memory/src/inbound/axum_router.rs b/rust/cloud-storage/memory/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..50398e9d26
--- /dev/null
+++ b/rust/cloud-storage/memory/src/inbound/axum_router.rs
@@ -0,0 +1,71 @@
+use crate::domain::MemoryService;
+use axum::{
+ Json, Router,
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::get,
+};
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::Serialize;
+use std::sync::Arc;
+use utoipa::ToSchema;
+
+/// The user's latest memory.
+#[derive(Serialize, ToSchema)]
+pub struct MemoryResponse {
+ /// The generated memory text.
+ pub memory: String,
+}
+
+#[derive(Serialize, ToSchema)]
+pub struct MemoryErrorBody {
+ /// Error description.
+ pub error: String,
+}
+
+pub fn memory_router<T, S>(service: Arc<T>) -> Router<S>
+where
+ T: MemoryService + Send + Sync + 'static,
+ S: Send + Sync + Clone + 'static,
+{
+ Router::new()
+ .route("/memory", get(get_memory_handler::<T>))
+ .with_state(service)
+}
+
+/// Get the authenticated user's latest memory.
+///
+/// Returns the current memory if one exists. If the memory is stale or missing,
+/// a background generation is triggered and the endpoint returns the stale
+/// memory (200) or 404 if none exists yet.
+#[utoipa::path(
+ get,
+ path = "/memory",
+ responses(
+ (status = 200, description = "Latest memory for the user", body = MemoryResponse),
+ (status = 404, description = "No memory exists for this user yet (generation triggered)"),
+ (status = 500, description = "Internal server error", body = MemoryErrorBody),
+ ),
+ tag = "memory"
+)]
+#[tracing::instrument(skip(service, user), fields(user_id = %user.macro_user_id))]
+pub async fn get_memory_handler<T: MemoryService>(
+ State(service): State<Arc<T>>,
+ user: MacroUserExtractor,
+) -> Response {
+ match service.get_or_generate_memory(user.macro_user_id).await {
+ Ok(Some(memory)) => Json(MemoryResponse { memory }).into_response(),
+ Ok(None) => StatusCode::NOT_FOUND.into_response(),
+ Err(e) => {
+ tracing::error!(error = ?e, "failed to get memory");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(MemoryErrorBody {
+ error: "failed to get memory".to_string(),
+ }),
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/rust/cloud-storage/memory/src/inbound/mod.rs b/rust/cloud-storage/memory/src/inbound/mod.rs
new file mode 100644
index 0000000000..2021071c60
--- /dev/null
+++ b/rust/cloud-storage/memory/src/inbound/mod.rs
@@ -0,0 +1 @@
+pub mod axum_router;
diff --git a/rust/cloud-storage/memory/src/lib.rs b/rust/cloud-storage/memory/src/lib.rs
new file mode 100644
index 0000000000..75ced455b8
--- /dev/null
+++ b/rust/cloud-storage/memory/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod context;
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
diff --git a/rust/cloud-storage/memory/src/main.rs b/rust/cloud-storage/memory/src/main.rs
new file mode 100644
index 0000000000..1791da482e
--- /dev/null
+++ b/rust/cloud-storage/memory/src/main.rs
@@ -0,0 +1,35 @@
+use ai_tools::all_tools;
+use macro_user_id::user_id::MacroUserIdStr;
+use memory::context::build_tool_service_context;
+use memory::domain::{MemoryService, service::MemoryServiceImpl};
+use memory::outbound::pg_memory_repo::PgMemoryRepo;
+use sqlx::postgres::PgPoolOptions;
+
+#[tokio::main]
+#[tracing::instrument(err)]
+async fn main() -> anyhow::Result<()> {
+ macro_entrypoint::MacroEntrypoint::default().init();
+
+ let database_url = std::env::var("DATABASE_URL")?;
+
+ let pool = PgPoolOptions::new()
+ .max_connections(5)
+ .connect(&database_url)
+ .await?;
+
+ let tool_context = build_tool_service_context(pool.clone()).await?;
+ let tools = all_tools();
+ let memory_repo = PgMemoryRepo::new(pool.clone());
+ let memory_service = MemoryServiceImpl::new(pool, memory_repo, tool_context, tools);
+
+ let user = MacroUserIdStr::try_from(std::env::var("USER_ID").expect("USER_ID"))
+ .expect("parse user id");
+
+ tracing::info!("Generating memory for {user}...");
+ match memory_service.get_or_generate_memory(user).await? {
+ Some(memory) => println!("{memory}"),
+ None => println!("No memory yet, generation triggered in background"),
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/memory/src/outbound.rs b/rust/cloud-storage/memory/src/outbound.rs
new file mode 100644
index 0000000000..599b0bd1fd
--- /dev/null
+++ b/rust/cloud-storage/memory/src/outbound.rs
@@ -0,0 +1 @@
+pub mod pg_memory_repo;
diff --git a/rust/cloud-storage/memory/src/outbound/pg_memory_repo.rs b/rust/cloud-storage/memory/src/outbound/pg_memory_repo.rs
new file mode 100644
index 0000000000..5afa9c08af
--- /dev/null
+++ b/rust/cloud-storage/memory/src/outbound/pg_memory_repo.rs
@@ -0,0 +1,77 @@
+#[cfg(test)]
+mod test;
+
+use crate::domain::{Memory, MemoryRepo, Result, ports::MemoryRecord};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+
+pub struct PgMemoryRepo {
+ inner: PgPool,
+}
+
+impl PgMemoryRepo {
+ pub fn new(inner: PgPool) -> Self {
+ PgMemoryRepo { inner }
+ }
+}
+
+impl MemoryRepo for PgMemoryRepo {
+ async fn save_memory(&self, memory: &Memory, user: MacroUserIdStr<'_>) -> Result<Uuid> {
+ let id = macro_uuid::generate_uuid_v7();
+ let row = sqlx::query!(
+ r#"
+ INSERT INTO memory (id, user_id, memory)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id) DO UPDATE
+ SET memory = EXCLUDED.memory,
+ updated_at = NOW()
+ RETURNING id
+ "#,
+ id,
+ user.as_ref(),
+ memory,
+ )
+ .fetch_one(&self.inner)
+ .await?;
+
+ Ok(row.id)
+ }
+
+ async fn get_latest_memory(&self, user: MacroUserIdStr<'_>) -> Result<Option<MemoryRecord>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT memory, created_at as "created_at!"
+ FROM memory
+ WHERE user_id = $1
+ ORDER BY created_at DESC
+ LIMIT 1
+ "#,
+ user.as_ref(),
+ )
+ .fetch_optional(&self.inner)
+ .await?;
+
+ Ok(row.map(|r| MemoryRecord {
+ memory: r.memory,
+ created_at: r.created_at,
+ }))
+ }
+
+ async fn get_memory_by_id(&self, user: MacroUserIdStr<'_>, id: Uuid) -> Result<Memory> {
+ let row = sqlx::query!(
+ r#"
+ SELECT memory
+ FROM memory
+ WHERE id = $1 AND user_id = $2
+ "#,
+ id,
+ user.as_ref(),
+ )
+ .fetch_optional(&self.inner)
+ .await?
+ .ok_or(crate::domain::MemoryError::NoGeneration)?;
+
+ Ok(row.memory)
+ }
+}
diff --git a/rust/cloud-storage/memory/src/outbound/pg_memory_repo/test.rs b/rust/cloud-storage/memory/src/outbound/pg_memory_repo/test.rs
new file mode 100644
index 0000000000..41f3310903
--- /dev/null
+++ b/rust/cloud-storage/memory/src/outbound/pg_memory_repo/test.rs
@@ -0,0 +1,100 @@
+use super::PgMemoryRepo;
+use crate::domain::{MemoryError, MemoryRepo};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn save_and_get_by_id(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let memory_text = "User is a senior engineer working on cloud infra".to_string();
+
+ let id = repo.save_memory(&memory_text, user.clone()).await.unwrap();
+ let fetched = repo.get_memory_by_id(user, id).await.unwrap();
+
+ assert_eq!(fetched, memory_text);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_latest_returns_most_recent(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ repo.save_memory(&"first memory".to_string(), user.clone())
+ .await
+ .unwrap();
+ repo.save_memory(&"second memory".to_string(), user.clone())
+ .await
+ .unwrap();
+
+ let record = repo.get_latest_memory(user).await.unwrap().unwrap();
+ assert_eq!(record.memory, "second memory");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_latest_no_memories_returns_none(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let result = repo.get_latest_memory(user).await.unwrap();
+ assert!(result.is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_by_id_wrong_user_returns_error(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user_a = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user_b = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let id = repo
+ .save_memory(&"private memory".to_string(), user_a)
+ .await
+ .unwrap();
+
+ let result = repo.get_memory_by_id(user_b, id).await;
+ assert!(matches!(result, Err(MemoryError::NoGeneration)));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_by_id_nonexistent_returns_error(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let fake_id = macro_uuid::generate_uuid_v7();
+
+ let result = repo.get_memory_by_id(user, fake_id).await;
+ assert!(matches!(result, Err(MemoryError::NoGeneration)));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn memories_are_scoped_to_user(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user_a = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user_b = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ repo.save_memory(&"user a memory".to_string(), user_a.clone())
+ .await
+ .unwrap();
+ repo.save_memory(&"user b memory".to_string(), user_b.clone())
+ .await
+ .unwrap();
+
+ let latest_a = repo.get_latest_memory(user_a).await.unwrap().unwrap();
+ let latest_b = repo.get_latest_memory(user_b).await.unwrap().unwrap();
+
+ assert_eq!(latest_a.memory, "user a memory");
+ assert_eq!(latest_b.memory, "user b memory");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_latest_includes_created_at(pool: Pool<Postgres>) {
+ let repo = PgMemoryRepo::new(pool);
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ repo.save_memory(&"a memory".to_string(), user.clone())
+ .await
+ .unwrap();
+
+ let record = repo.get_latest_memory(user).await.unwrap().unwrap();
+ assert!(record.created_at <= chrono::Utc::now());
+}
diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
index 7228e8fd4c..9b2fc6370d 100644
--- a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
@@ -15,6 +15,7 @@ use ai::tool::{
};
use async_trait::async_trait;
use cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::CreatedAt;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
@@ -142,7 +143,7 @@ where
let paginated = service_context
.service
.get_user_notifications::<serde_json::Value>(
- (*request_context.user_id).copied(),
+ MacroUserIdStr((*request_context.user_id).copied()),
Some(limit),
models_pagination::Query::Sort(CreatedAt, ()),
)
@@ -209,7 +210,7 @@ where
service_context
.service
.update_notifications(UpdateNotificationsRequest {
- user_id: (*request_context.user_id).clone(),
+ user_id: MacroUserIdStr((*request_context.user_id).clone()),
notification_ids: &self.notification_ids,
status: NotificationStatus::Seen,
})
@@ -263,7 +264,7 @@ where
service_context
.service
.update_notifications(UpdateNotificationsRequest {
- user_id: (*request_context.user_id).clone(),
+ user_id: MacroUserIdStr((*request_context.user_id).clone()),
notification_ids: &self.notification_ids,
status: NotificationStatus::Done(self.done),
})
diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
index 7ed16b62ee..92b8873d1c 100644
--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs
+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
@@ -76,7 +76,7 @@ async fn main() {
let toolset = soup_toolset();
let context = RequestContext {
- user_id: Arc::new(user_id),
+ user_id,
jwt: Arc::new(String::new()),
};
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
index f82087d76b..6a12844551 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -151,7 +151,7 @@ where
soup_type: SoupType::Expanded,
limit: RESULT_LIMIT,
cursor: SoupQuery::new_sort_simple(sort_method, Default::default()),
- user: (*request_context.user_id).clone(),
+ user: request_context.user_id,
email_preview_view: PreviewView::default(),
link_id: None,
})
diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.toml
index 48866be586..9999eed3c0 100644
--- a/rust/cloud-storage/sqs_client/Cargo.toml
+++ b/rust/cloud-storage/sqs_client/Cargo.toml
@@ -44,5 +44,6 @@ serde_json = { workspace = true }
strum = { workspace = true, features = ["derive"] }
tracing = { workspace = true }
uuid = { workspace = true, optional = true }
+macro_user_id = { path = "../macro_user_id", optional = true }
models_opensearch = { path = "../models_opensearch", optional = true }
futures = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/target/lambda/memory_scheduler/bootstrap.zip b/rust/cloud-storage/target/lambda/memory_scheduler/bootstrap.zip
new file mode 100644
index 0000000000..c3d2310a95
Binary files /dev/null and b/rust/cloud-storage/target/lambda/memory_scheduler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/memory_worker/bootstrap.zip b/rust/cloud-storage/target/lambda/memory_worker/bootstrap.zip
new file mode 100644
index 0000000000..baabef3b28
Binary files /dev/null and b/rust/cloud-storage/target/lambda/memory_worker/bootstrap.zip differ