Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): basic ai projection CRUD (#4230)
Will Hutchinson8734c1c8001d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 742f6d01b8..a31a651f1d 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -16,6 +16,15 @@"non_empty","workspace-hack"],+ "ai_projections": [+ "ai_projections",+ "cowlike",+ "macro_user_id",+ "macro_uuid",+ "model-error-response",+ "model_user",+ "workspace-hack"+ ],"ai_tools": ["agent","ai_tools",@@ -1012,6 +1021,7 @@],"document_cognition_service": ["agent",+ "ai_projections","ai_tools","ai_toolset","ai_usage",diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex 605bc161cf..50f29da148 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -27,6 +27,7 @@ import type {MemoryResponse,ModelsResponse,PatchChatRequest,+ ProjectionStateResponse,RejectToolCallRequest,SendChatMessageResponse,ServerResponse,@@ -43,6 +44,7 @@ import type {UpdateServerRequest,UpdateToolCallRequest,UpdateToolResponseRequest,+ UpsertProjectionRequest,UsageRequest,UsageSummary,} from './schemas';@@ -167,6 +169,70 @@ export const getUsageHandler = async (} as getUsageHandlerResponse;};+/**+ * @summary Gets or creates an ai projection and the requesting user's cold instance.+ */+export type upsertAiProjectionResponse200 = {+ data: ProjectionStateResponse;+ status: 200;+};++export type upsertAiProjectionResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type upsertAiProjectionResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type upsertAiProjectionResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type upsertAiProjectionResponseSuccess =+ upsertAiProjectionResponse200 & {+ headers: Headers;+ };+export type upsertAiProjectionResponseError = (+ | upsertAiProjectionResponse400+ | upsertAiProjectionResponse403+ | upsertAiProjectionResponse500+) & {+ headers: Headers;+};++export type upsertAiProjectionResponse =+ | upsertAiProjectionResponseSuccess+ | upsertAiProjectionResponseError;++export const getUpsertAiProjectionUrl = () => {+ return `/ai-projections`;+};++export const upsertAiProjection = async (+ upsertProjectionRequest: UpsertProjectionRequest,+ options?: RequestInit+): Promise<upsertAiProjectionResponse> => {+ const res = await fetch(getUpsertAiProjectionUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(upsertProjectionRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: upsertAiProjectionResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as upsertAiProjectionResponse;+};+export type getChatsForAttachmentHandlerResponse200 = {data: GetChatsForAttachmentResponse;status: 200;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/expiry.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/expiry.tsnew file mode 100644index 0000000000..117bbbba67--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/expiry.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * How long a projection remains active without being requested.+ */+export type Expiry = (typeof Expiry)[keyof typeof Expiry];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const Expiry = {+ day: 'day',+ week: 'week',+ month: 'month',+} as const;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.tsindex 821e7d1b94..91b8c79224 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@@ -102,6 +102,7 @@ export * from './entity';export * from './entityType';export * from './errorBody';export * from './errorResponse';+export * from './expiry';export * from './featureUsage';export * from './fileType';export * from './genericErrorResponse';@@ -133,6 +134,12 @@ export * from './patchChatRequestName';export * from './patchChatRequestProjectId';export * from './patchChatRequestSharePermission';export * from './price';+export * from './projectionStateResponse';+export * from './projectionStateResponseData';+export * from './projectionStateResponseGeneratedAt';+export * from './projectionStateResponseStaleAt';+export * from './projectionStatus';+export * from './refreshCadence';export * from './rejectToolCallRequest';export * from './role';export * from './sendChatMessagePayload';@@ -162,6 +169,7 @@ export * from './structuredCompletionError';export * from './structuredCompletionRequest';export * from './structuredCompletionRequestAdditionalInstructions';export * from './structuredCompletionResponse';+export * from './targetType';export * from './toolSet';export * from './toolSetOneOf';export * from './toolSetOneOfThree';@@ -179,6 +187,7 @@ export * from './updateSharePermissionRequestV2IsPublic';export * from './updateSharePermissionRequestV2PublicAccessLevel';export * from './updateToolCallRequest';export * from './updateToolResponseRequest';+export * from './upsertProjectionRequest';export * from './usage';export * from './usagePrice';export * from './usageRequest';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponse.tsnew file mode 100644index 0000000000..8d96778ffb--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponse.ts@@ -0,0 +1,26 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ProjectionStateResponseData } from './projectionStateResponseData';+import type { ProjectionStateResponseGeneratedAt } from './projectionStateResponseGeneratedAt';+import type { ProjectionStateResponseStaleAt } from './projectionStateResponseStaleAt';+import type { ProjectionStatus } from './projectionStatus';++/**+ * The current state of a user's projection instance.+ */+export interface ProjectionStateResponse {+ /** The cached result, if any. */+ data?: ProjectionStateResponseData;+ /** When the result was generated. */+ generated_at?: ProjectionStateResponseGeneratedAt;+ /** The projection id. */+ id: string;+ /** When the result becomes stale. */+ stale_at?: ProjectionStateResponseStaleAt;+ /** The materialization status. */+ status: ProjectionStatus;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseData.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseData.tsnew file mode 100644index 0000000000..352a6dcff8--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseData.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The cached result, if any.+ */+export type ProjectionStateResponseData = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseGeneratedAt.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseGeneratedAt.tsnew file mode 100644index 0000000000..b5766ac446--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseGeneratedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * When the result was generated.+ */+export type ProjectionStateResponseGeneratedAt = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseStaleAt.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseStaleAt.tsnew file mode 100644index 0000000000..ecc069802c--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStateResponseStaleAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * When the result becomes stale.+ */+export type ProjectionStateResponseStaleAt = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStatus.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStatus.tsnew file mode 100644index 0000000000..a72a635275--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/projectionStatus.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The materialization status of a user's projection instance.+ */+export type ProjectionStatus =+ (typeof ProjectionStatus)[keyof typeof ProjectionStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ProjectionStatus = {+ loading: 'loading',+ cold: 'cold',+ ready: 'ready',+ refreshing: 'refreshing',+ error: 'error',+} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/refreshCadence.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/refreshCadence.tsnew file mode 100644index 0000000000..0fa3b13127--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/refreshCadence.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * How frequently an active projection is regenerated.+ */+export type RefreshCadence =+ (typeof RefreshCadence)[keyof typeof RefreshCadence];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RefreshCadence = {+ high: 'high',+ medium: 'medium',+ low: 'low',+} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/targetType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/targetType.tsnew file mode 100644index 0000000000..9710bbf8cf--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/targetType.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The kind of entity a projection is materialized for.+ */+export type TargetType = (typeof TargetType)[keyof typeof TargetType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TargetType = {+ user: 'user',+ team: 'team',+} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/upsertProjectionRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/upsertProjectionRequest.tsnew file mode 100644index 0000000000..877d8b05a1--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/upsertProjectionRequest.ts@@ -0,0 +1,26 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { Expiry } from './expiry';+import type { RefreshCadence } from './refreshCadence';+import type { TargetType } from './targetType';++/**+ * Request body for getting or creating an ai projection. The concrete target+id is resolved from the authenticated user, so only the target type is sent.+ */+export interface UpsertProjectionRequest {+ /** How long the projection remains active without being requested. */+ expiry: Expiry;+ /** The frontend-defined projection id (e.g. `notification_important_widget`). */+ id: string;+ /** The prompt used to materialize the projection. */+ prompt: string;+ /** How frequently the projection should be regenerated. */+ refresh_cadence: RefreshCadence;+ /** Whether the projection is materialized for the requesting user or their team. */+ target_type: TargetType;+}diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex e6cd82e917..a5b74c3f26 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -112,6 +112,65 @@}}},+ "/ai-projections": {+ "post": {+ "tags": ["ai_projections::inbound::axum_router::upsert_projection"],+ "summary": "Gets or creates an ai projection and the requesting user's cold instance.",+ "operationId": "upsert_ai_projection",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpsertProjectionRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProjectionStateResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/attachments/{attachment_id}/chats": {"get": {"tags": ["get_chats_for_attachment"],@@ -2382,6 +2441,11 @@}}},+ "Expiry": {+ "type": "string",+ "description": "How long a projection remains active without being requested.",+ "enum": ["day", "week", "month"]+ },"FeatureUsage": {"type": "object","description": "Usage for a single feature, with its rolled-up dollar total.",@@ -3155,6 +3219,45 @@}}},+ "ProjectionStateResponse": {+ "type": "object",+ "description": "The current state of a user's projection instance.",+ "required": ["id", "status"],+ "properties": {+ "data": {+ "type": ["string", "null"],+ "description": "The cached result, if any."+ },+ "generated_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the result was generated."+ },+ "id": {+ "type": "string",+ "description": "The projection id."+ },+ "stale_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the result becomes stale."+ },+ "status": {+ "$ref": "#/components/schemas/ProjectionStatus",+ "description": "The materialization status."+ }+ }+ },+ "ProjectionStatus": {+ "type": "string",+ "description": "The materialization status of a user's projection instance.",+ "enum": ["loading", "cold", "ready", "refreshing", "error"]+ },+ "RefreshCadence": {+ "type": "string",+ "description": "How frequently an active projection is regenerated.",+ "enum": ["high", "medium", "low"]+ },"RejectToolCallRequest": {"type": "object","description": "Request body for rejecting a pending tool call.",@@ -3473,6 +3576,11 @@"result": {}}},+ "TargetType": {+ "type": "string",+ "description": "The kind of entity a projection is materialized for.",+ "enum": ["user", "team"]+ },"ToolSet": {"oneOf": [{@@ -3609,6 +3717,39 @@}}},+ "UpsertProjectionRequest": {+ "type": "object",+ "description": "Request body for getting or creating an ai projection. The concrete target\nid is resolved from the authenticated user, so only the target type is sent.",+ "required": [+ "id",+ "prompt",+ "target_type",+ "refresh_cadence",+ "expiry"+ ],+ "properties": {+ "expiry": {+ "$ref": "#/components/schemas/Expiry",+ "description": "How long the projection remains active without being requested."+ },+ "id": {+ "type": "string",+ "description": "The frontend-defined projection id (e.g. `notification_important_widget`)."+ },+ "prompt": {+ "type": "string",+ "description": "The prompt used to materialize the projection."+ },+ "refresh_cadence": {+ "$ref": "#/components/schemas/RefreshCadence",+ "description": "How frequently the projection should be regenerated."+ },+ "target_type": {+ "$ref": "#/components/schemas/TargetType",+ "description": "Whether the projection is materialized for the requesting user or their team."+ }+ }+ },"Usage": {"type": "object","description": "The token usage and resolved cost of a single completion.",diff --git a/rust/cloud-storage/.sqlx/query-44e7fd51a0308617c9641b7d42de6a2ddd91a43806bde7e2910e4ae7d536a041.json b/rust/cloud-storage/.sqlx/query-44e7fd51a0308617c9641b7d42de6a2ddd91a43806bde7e2910e4ae7d536a041.jsonnew file mode 100644index 0000000000..d7864e5efb--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-44e7fd51a0308617c9641b7d42de6a2ddd91a43806bde7e2910e4ae7d536a041.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, prompt, prompt_hash, target_type, refresh_cadence, expiry, created_at, updated_at\n FROM ai_projection\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "prompt",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "prompt_hash",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "target_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "refresh_cadence",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "expiry",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "44e7fd51a0308617c9641b7d42de6a2ddd91a43806bde7e2910e4ae7d536a041"+}diff --git a/rust/cloud-storage/.sqlx/query-663af7d62849f2b928e48fefb52662cf24d94b18ee47caaa4f12dc6492fc2931.json b/rust/cloud-storage/.sqlx/query-663af7d62849f2b928e48fefb52662cf24d94b18ee47caaa4f12dc6492fc2931.jsonnew file mode 100644index 0000000000..6d04ee83ec--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-663af7d62849f2b928e48fefb52662cf24d94b18ee47caaa4f12dc6492fc2931.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_projection (id, prompt, prompt_hash, target_type, refresh_cadence, expiry)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "663af7d62849f2b928e48fefb52662cf24d94b18ee47caaa4f12dc6492fc2931"+}diff --git a/rust/cloud-storage/.sqlx/query-6accab3729368a1bf0121c67139732fe3a42a7ff5975a89bfd8207d398666af6.json b/rust/cloud-storage/.sqlx/query-6accab3729368a1bf0121c67139732fe3a42a7ff5975a89bfd8207d398666af6.jsonnew file mode 100644index 0000000000..893ac1a007--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6accab3729368a1bf0121c67139732fe3a42a7ff5975a89bfd8207d398666af6.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM \"RolesOnUsers\" ru\n JOIN \"RolesOnPermissions\" rp ON ru.\"roleId\" = rp.\"roleId\"\n WHERE ru.\"userId\" = $1 AND rp.\"permissionId\" = $2\n ) AS \"has_permission!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "has_permission!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "6accab3729368a1bf0121c67139732fe3a42a7ff5975a89bfd8207d398666af6"+}diff --git a/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.json b/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.jsonnew file mode 100644index 0000000000..24ee293f43--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, ai_projection_id, target_id, prompt_hash, status,\n result, error, generated_at, stale_at\n FROM user_ai_projection\n WHERE ai_projection_id = $1 AND target_id = $2 AND prompt_hash = $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "ai_projection_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "target_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "prompt_hash",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "result",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "error",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "generated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "stale_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "84fb3301148d3792bfca937697189ad987c7e885d3511cfe05458f238fab47ce"+}diff --git a/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.json b/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.jsonnew file mode 100644index 0000000000..2bbca7918a--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO user_ai_projection (id, ai_projection_id, target_id, prompt_hash, status)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (ai_projection_id, target_id, prompt_hash) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "99c9ad24f9161d5e905fff30e7be239d5346e410be2b8f4cabf6106cf5badbc8"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex bf8aaa1764..5403ab3fcf 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -94,6 +94,32 @@ dependencies = ["memchr",]+[[package]]+name = "ai_projections"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "chrono",+ "http-body-util",+ "macro_db_migrator",+ "macro_user_id",+ "macro_uuid",+ "model-error-response",+ "model_user",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tower 0.5.3",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "ai_tools"version = "0.1.0"@@ -3467,6 +3493,7 @@ version = "0.1.0"dependencies = ["agent","aho-corasick",+ "ai_projections","ai_tools","ai_toolset","ai_usage",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 02a9c305dc..f6a36b4a0c 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -3,6 +3,7 @@ resolver = "2"members = ["agent",+ "ai_projections","ai_usage","authentication_service","backfill_entity_access",diff --git a/rust/cloud-storage/ai_projections/Cargo.toml b/rust/cloud-storage/ai_projections/Cargo.tomlnew file mode 100644index 0000000000..054f1b4429--- /dev/null+++ b/rust/cloud-storage/ai_projections/Cargo.toml@@ -0,0 +1,53 @@+[package]+edition = "2024"+name = "ai_projections"+publish = false+version = "0.1.0"++[features]+axum = [+ "dep:axum",+ "dep:model-error-response",+ "dep:model_user",+ "dep:utoipa",+]+default = ["axum", "inbound", "outbound", "ports"]+inbound = ["axum", "ports"]+outbound = [+ "dep:macro_uuid",+ "dep:sqlx",+ "ports",+]+ports = ["dep:tokio"]++[dependencies]+# Core+anyhow = { workspace = true }+chrono = { workspace = true }+macro_user_id = { path = "../macro_user_id" }+serde = { workspace = true }+sha2 = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++# Async runtime (for ports)+tokio = { workspace = true, optional = true }++# Axum dependencies (for inbound)+axum = { workspace = true, optional = true }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+utoipa = { workspace = true, optional = true }++# Outbound dependencies+macro_uuid = { path = "../macro_uuid", optional = true }+sqlx = { workspace = true, optional = true }++[dev-dependencies]+http-body-util = { workspace = true }+macro_db_migrator = { path = "../macro_db_migrator" }+serde_json = { workspace = true }+tokio = { workspace = true }+tower = { workspace = true }diff --git a/rust/cloud-storage/ai_projections/fixtures/ai_projections.sql b/rust/cloud-storage/ai_projections/fixtures/ai_projections.sqlnew file mode 100644index 0000000000..0f84687fb2--- /dev/null+++ b/rust/cloud-storage/ai_projections/fixtures/ai_projections.sql@@ -0,0 +1,19 @@+-- A professional user (has the read:professional_features permission via the+-- seeded `professional_subscriber` role) and a free user (no roles).+INSERT INTO "macro_user" (id, username, email, stripe_customer_id) VALUES+ ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'cus_pro'),+ ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_free');++INSERT INTO "User" (id, email, "macro_user_id") VALUES+ ('macro|[email protected]', '[email protected]', 'a1111111-1111-1111-1111-111111111111'),+ ('macro|[email protected]', '[email protected]', 'a2222222-2222-2222-2222-222222222222');++INSERT INTO "RolesOnUsers" ("userId", "roleId") VALUES+ ('macro|[email protected]', 'professional_subscriber');++-- A team the professional user belongs to (for team-target resolution tests).+INSERT INTO team (id, name, owner_id, seat_count) VALUES+ ('11111111-1111-1111-1111-111111111111', 'pro team', 'macro|[email protected]', 1);++INSERT INTO team_user (team_id, user_id, team_role) VALUES+ ('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner');diff --git a/rust/cloud-storage/ai_projections/src/domain.rs b/rust/cloud-storage/ai_projections/src/domain.rsnew file mode 100644index 0000000000..cb85d0f9ee--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain.rs@@ -0,0 +1,5 @@+//! Contains the domain logic for ai projections++pub mod ai_projection_repo;+pub mod ai_projection_service;+pub mod model;diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rsnew file mode 100644index 0000000000..249f32ce51--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_repo.rs@@ -0,0 +1,45 @@+//! Outbound port for ai projection persistence.++use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::model::{+ AiProjection, AiProjectionError, Expiry, RefreshCadence, TargetType, UserAiProjection,+};++/// The AiProjectionRepository defines the persistence actions for ai projections.+pub trait AiProjectionRepository: Clone + Send + Sync + 'static {+ /// Gets an existing projection definition by id, or creates it if it does+ /// not exist. Existing definitions are returned unchanged.+ fn get_or_create_projection(+ &self,+ id: &str,+ prompt: &str,+ prompt_hash: &str,+ target_type: TargetType,+ refresh_cadence: RefreshCadence,+ expiry: Expiry,+ ) -> impl Future<Output = Result<AiProjection, AiProjectionError>> + Send;++ /// Gets the target's instance of a projection, or creates a cold instance+ /// if one does not exist for the given prompt version.+ fn get_or_create_target_projection(+ &self,+ ai_projection_id: &str,+ target_id: &str,+ prompt_hash: &str,+ ) -> impl Future<Output = Result<UserAiProjection, AiProjectionError>> + Send;++ /// Returns whether the user has the given permission id+ /// (e.g. `read:professional_features`).+ fn user_has_permission(+ &self,+ user_id: &MacroUserIdStr<'_>,+ permission: &str,+ ) -> impl Future<Output = Result<bool, AiProjectionError>> + Send;++ /// Returns the ids of the teams the user belongs to.+ fn get_user_team_ids(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<uuid::Uuid>, AiProjectionError>> + Send;+}diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rsnew file mode 100644index 0000000000..2ae7c5c1cc--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service.rs@@ -0,0 +1,149 @@+//! Service layer (inbound port) for ai projections.++#[cfg(test)]+mod test;++use macro_user_id::user_id::MacroUserIdStr;+use sha2::{Digest, Sha256};++use crate::domain::{+ ai_projection_repo::AiProjectionRepository,+ model::{+ AiProjectionError, TargetType, UpsertProjectionError, UpsertProjectionParams,+ UserAiProjection,+ },+};++/// The permission required to read professional (premium) features.+pub const READ_PROFESSIONAL_FEATURES: &str = "read:professional_features";++/// The AiProjectionService defines the high-level operations for ai projections.+pub trait AiProjectionService: Clone + Send + Sync + 'static {+ /// Gets or creates a projection definition and the target's cold instance+ /// of it, returning that instance. The concrete target id is resolved from+ /// the authenticated user: a `user` target resolves to the user's own id,+ /// a `team` target resolves to the user's (single) team.+ fn upsert_projection(+ &self,+ user_id: &MacroUserIdStr<'_>,+ params: UpsertProjectionParams,+ ) -> impl Future<Output = Result<UserAiProjection, UpsertProjectionError>> + Send;++ /// Returns whether the user has the `read:professional_features` permission.+ fn has_professional_features(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<bool, AiProjectionError>> + Send;+}++/// Implementation of [`AiProjectionService`] backed by an [`AiProjectionRepository`].+#[derive(Debug, Clone)]+pub struct AiProjectionServiceImpl<R>+where+ R: AiProjectionRepository,+{+ repository: R,+}++impl<R> AiProjectionServiceImpl<R>+where+ R: AiProjectionRepository,+{+ /// Creates a new AiProjectionServiceImpl.+ pub fn new(repository: R) -> Self {+ Self { repository }+ }++ /// Resolves the concrete target id from the authenticated user and the+ /// requested target type. A `user` target resolves to the user's own id; a+ /// `team` target resolves to the user's single team (erroring if the user+ /// is in zero or multiple teams).+ async fn resolve_target_id(+ &self,+ user_id: &MacroUserIdStr<'_>,+ target_type: TargetType,+ ) -> Result<String, UpsertProjectionError> {+ match target_type {+ TargetType::User => Ok(user_id.as_ref().to_string()),+ TargetType::Team => {+ let mut team_ids = self.repository.get_user_team_ids(user_id).await?;+ match team_ids.len() {+ 1 => Ok(team_ids.remove(0).to_string()),+ 0 => Err(UpsertProjectionError::BadRequest(+ "user is not a member of any team".to_string(),+ )),+ _ => Err(UpsertProjectionError::BadRequest(+ "user belongs to multiple teams; team target is ambiguous".to_string(),+ )),+ }+ }+ }+ }+}++/// Computes the prompt version hash used as part of a projection's cache key.+pub fn hash_prompt(prompt: &str) -> String {+ let digest = Sha256::digest(prompt.as_bytes());+ let mut hex = String::with_capacity(digest.len() * 2);+ for byte in digest {+ use std::fmt::Write;+ let _ = write!(hex, "{byte:02x}");+ }+ hex+}++impl<R> AiProjectionService for AiProjectionServiceImpl<R>+where+ R: AiProjectionRepository,+{+ #[tracing::instrument(skip(self), err)]+ async fn upsert_projection(+ &self,+ user_id: &MacroUserIdStr<'_>,+ params: UpsertProjectionParams,+ ) -> Result<UserAiProjection, UpsertProjectionError> {+ if params.id.trim().is_empty() {+ return Err(UpsertProjectionError::BadRequest(+ "projection id cannot be empty".to_string(),+ ));+ }+ if params.prompt.trim().is_empty() {+ return Err(UpsertProjectionError::BadRequest(+ "projection prompt cannot be empty".to_string(),+ ));+ }++ let target_id = self.resolve_target_id(user_id, params.target_type).await?;++ let prompt_hash = hash_prompt(¶ms.prompt);++ let projection = self+ .repository+ .get_or_create_projection(+ ¶ms.id,+ ¶ms.prompt,+ &prompt_hash,+ params.target_type,+ params.refresh_cadence,+ params.expiry,+ )+ .await?;++ let target_projection = self+ .repository+ .get_or_create_target_projection(&projection.id, &target_id, &projection.prompt_hash)+ .await?;++ Ok(target_projection)+ }++ #[tracing::instrument(skip(self), err)]+ async fn has_professional_features(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<bool, AiProjectionError> {+ self.repository+ .user_has_permission(user_id, READ_PROFESSIONAL_FEATURES)+ .await+ }+}diff --git a/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rs b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rsnew file mode 100644index 0000000000..63d13a75ce--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain/ai_projection_service/test.rs@@ -0,0 +1,235 @@+use std::sync::{Arc, Mutex};++use chrono::Utc;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};++use crate::domain::{+ ai_projection_repo::AiProjectionRepository,+ ai_projection_service::{AiProjectionService, AiProjectionServiceImpl, hash_prompt},+ model::{+ AiProjection, AiProjectionError, Expiry, ProjectionStatus, RefreshCadence, TargetType,+ UpsertProjectionError, UpsertProjectionParams, UserAiProjection,+ },+};++/// A tiny in-memory mock repository for exercising the service layer.+#[derive(Clone, Default)]+struct MockRepo {+ has_permission: bool,+ team_ids: Vec<uuid::Uuid>,+ created_target_projections: Arc<Mutex<Vec<UserAiProjection>>>,+}++impl AiProjectionRepository for MockRepo {+ async fn get_or_create_projection(+ &self,+ id: &str,+ prompt: &str,+ prompt_hash: &str,+ target_type: TargetType,+ refresh_cadence: RefreshCadence,+ expiry: Expiry,+ ) -> Result<AiProjection, AiProjectionError> {+ Ok(AiProjection {+ id: id.to_string(),+ prompt: prompt.to_string(),+ prompt_hash: prompt_hash.to_string(),+ target_type,+ refresh_cadence,+ expiry,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ })+ }++ async fn get_or_create_target_projection(+ &self,+ ai_projection_id: &str,+ target_id: &str,+ prompt_hash: &str,+ ) -> Result<UserAiProjection, AiProjectionError> {+ let target_projection = UserAiProjection {+ id: macro_uuid::generate_uuid_v7(),+ ai_projection_id: ai_projection_id.to_string(),+ target_id: target_id.to_string(),+ prompt_hash: prompt_hash.to_string(),+ status: ProjectionStatus::Cold,+ result: None,+ error: None,+ generated_at: None,+ stale_at: None,+ };+ self.created_target_projections+ .lock()+ .unwrap()+ .push(target_projection.clone());+ Ok(target_projection)+ }++ async fn user_has_permission(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ _permission: &str,+ ) -> Result<bool, AiProjectionError> {+ Ok(self.has_permission)+ }++ async fn get_user_team_ids(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ ) -> Result<Vec<uuid::Uuid>, AiProjectionError> {+ Ok(self.team_ids.clone())+ }+}++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned()+}++#[test]+fn hash_prompt_is_deterministic_and_hex() {+ let a = hash_prompt("hello world");+ let b = hash_prompt("hello world");+ let c = hash_prompt("different");+ assert_eq!(a, b);+ assert_ne!(a, c);+ assert_eq!(a.len(), 64);+ assert!(a.chars().all(|ch| ch.is_ascii_hexdigit()));+}++#[tokio::test]+async fn has_professional_features_delegates_to_repo() {+ let service = AiProjectionServiceImpl::new(MockRepo {+ has_permission: true,+ ..Default::default()+ });+ assert!(service.has_professional_features(&user_id()).await.unwrap());++ let service = AiProjectionServiceImpl::new(MockRepo {+ has_permission: false,+ ..Default::default()+ });+ assert!(!service.has_professional_features(&user_id()).await.unwrap());+}++fn user_params(id: &str, prompt: &str) -> UpsertProjectionParams {+ UpsertProjectionParams {+ id: id.to_string(),+ prompt: prompt.to_string(),+ target_type: TargetType::User,+ refresh_cadence: RefreshCadence::High,+ expiry: Expiry::Day,+ }+}++#[tokio::test]+async fn upsert_projection_creates_cold_target_instance_for_user() {+ let repo = MockRepo::default();+ let service = AiProjectionServiceImpl::new(repo.clone());++ let target_projection = service+ .upsert_projection(+ &user_id(),+ user_params("inbox/important", "What is important?"),+ )+ .await+ .unwrap();++ assert_eq!(target_projection.ai_projection_id, "inbox/important");+ // The user target id is resolved from the authenticated user.+ assert_eq!(target_projection.target_id, "macro|[email protected]");+ assert_eq!(target_projection.status, ProjectionStatus::Cold);+ assert_eq!(+ target_projection.prompt_hash,+ hash_prompt("What is important?")+ );+ assert_eq!(repo.created_target_projections.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn upsert_projection_resolves_team_target_from_user() {+ let team_id = macro_uuid::generate_uuid_v7();+ let repo = MockRepo {+ team_ids: vec![team_id],+ ..Default::default()+ };+ let service = AiProjectionServiceImpl::new(repo.clone());++ let target_projection = service+ .upsert_projection(+ &user_id(),+ UpsertProjectionParams {+ id: "team/focus".to_string(),+ prompt: "What is my team focused on?".to_string(),+ target_type: TargetType::Team,+ refresh_cadence: RefreshCadence::Medium,+ expiry: Expiry::Week,+ },+ )+ .await+ .unwrap();++ assert_eq!(target_projection.target_id, team_id.to_string());+}++#[tokio::test]+async fn upsert_projection_team_target_errors_without_exactly_one_team() {+ // Zero teams -> bad request.+ let service = AiProjectionServiceImpl::new(MockRepo::default());+ let err = service+ .upsert_projection(+ &user_id(),+ UpsertProjectionParams {+ id: "team/focus".to_string(),+ prompt: "What is my team focused on?".to_string(),+ target_type: TargetType::Team,+ refresh_cadence: RefreshCadence::Medium,+ expiry: Expiry::Week,+ },+ )+ .await+ .unwrap_err();+ assert!(matches!(err, UpsertProjectionError::BadRequest(_)));++ // Multiple teams -> ambiguous bad request.+ let service = AiProjectionServiceImpl::new(MockRepo {+ team_ids: vec![+ macro_uuid::generate_uuid_v7(),+ macro_uuid::generate_uuid_v7(),+ ],+ ..Default::default()+ });+ let err = service+ .upsert_projection(+ &user_id(),+ UpsertProjectionParams {+ id: "team/focus".to_string(),+ prompt: "What is my team focused on?".to_string(),+ target_type: TargetType::Team,+ refresh_cadence: RefreshCadence::Medium,+ expiry: Expiry::Week,+ },+ )+ .await+ .unwrap_err();+ assert!(matches!(err, UpsertProjectionError::BadRequest(_)));+}++#[tokio::test]+async fn upsert_projection_rejects_empty_id_and_prompt() {+ let service = AiProjectionServiceImpl::new(MockRepo::default());++ let err = service+ .upsert_projection(&user_id(), user_params(" ", "valid"))+ .await+ .unwrap_err();+ assert!(matches!(err, UpsertProjectionError::BadRequest(_)));++ let err = service+ .upsert_projection(&user_id(), user_params("valid", ""))+ .await+ .unwrap_err();+ assert!(matches!(err, UpsertProjectionError::BadRequest(_)));+}diff --git a/rust/cloud-storage/ai_projections/src/domain/model.rs b/rust/cloud-storage/ai_projections/src/domain/model.rsnew file mode 100644index 0000000000..bbc8a29c46--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/domain/model.rs@@ -0,0 +1,269 @@+//! Domain models, enums, and error types for ai projections.++use std::{fmt::Display, str::FromStr};++use chrono::{DateTime, Utc};++/// The kind of entity a projection is materialized for.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "lowercase")]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub enum TargetType {+ /// The projection targets an individual user.+ User,+ /// The projection targets a team.+ Team,+}++/// How frequently an active projection is regenerated.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "lowercase")]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub enum RefreshCadence {+ /// Regenerate frequently.+ High,+ /// Regenerate at a moderate rate.+ Medium,+ /// Regenerate infrequently.+ Low,+}++/// How long a projection remains active without being requested.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "lowercase")]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub enum Expiry {+ /// Expires after a day.+ Day,+ /// Expires after a week.+ Week,+ /// Expires after a month.+ Month,+}++/// The materialization status of a user's projection instance.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "lowercase")]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub enum ProjectionStatus {+ /// The projection is being materialized for the first time.+ Loading,+ /// The projection instance exists but has no materialized result yet.+ Cold,+ /// The projection has a materialized result available.+ Ready,+ /// The projection is being refreshed in the background.+ Refreshing,+ /// The projection failed to materialize.+ Error,+}++impl Display for RefreshCadence {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let s = match self {+ RefreshCadence::High => "high",+ RefreshCadence::Medium => "medium",+ RefreshCadence::Low => "low",+ };+ write!(f, "{s}")+ }+}++impl FromStr for RefreshCadence {+ type Err = ParseEnumError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "high" => Ok(RefreshCadence::High),+ "medium" => Ok(RefreshCadence::Medium),+ "low" => Ok(RefreshCadence::Low),+ other => Err(ParseEnumError::new("RefreshCadence", other)),+ }+ }+}++impl Display for Expiry {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let s = match self {+ Expiry::Day => "day",+ Expiry::Week => "week",+ Expiry::Month => "month",+ };+ write!(f, "{s}")+ }+}++impl FromStr for Expiry {+ type Err = ParseEnumError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "day" => Ok(Expiry::Day),+ "week" => Ok(Expiry::Week),+ "month" => Ok(Expiry::Month),+ other => Err(ParseEnumError::new("Expiry", other)),+ }+ }+}++impl Display for ProjectionStatus {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let s = match self {+ ProjectionStatus::Loading => "loading",+ ProjectionStatus::Cold => "cold",+ ProjectionStatus::Ready => "ready",+ ProjectionStatus::Refreshing => "refreshing",+ ProjectionStatus::Error => "error",+ };+ write!(f, "{s}")+ }+}++impl FromStr for ProjectionStatus {+ type Err = ParseEnumError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "loading" => Ok(ProjectionStatus::Loading),+ "cold" => Ok(ProjectionStatus::Cold),+ "ready" => Ok(ProjectionStatus::Ready),+ "refreshing" => Ok(ProjectionStatus::Refreshing),+ "error" => Ok(ProjectionStatus::Error),+ other => Err(ParseEnumError::new("ProjectionStatus", other)),+ }+ }+}++impl Display for TargetType {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let s = match self {+ TargetType::User => "user",+ TargetType::Team => "team",+ };+ write!(f, "{s}")+ }+}++impl FromStr for TargetType {+ type Err = ParseEnumError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "user" => Ok(TargetType::User),+ "team" => Ok(TargetType::Team),+ other => Err(ParseEnumError::new("TargetType", other)),+ }+ }+}++/// Error returned when a stored string cannot be parsed into a domain enum.+#[derive(Debug, thiserror::Error)]+#[error("invalid {kind} value: {value}")]+pub struct ParseEnumError {+ /// The name of the enum that failed to parse.+ pub kind: &'static str,+ /// The offending value.+ pub value: String,+}++impl ParseEnumError {+ fn new(kind: &'static str, value: &str) -> Self {+ Self {+ kind,+ value: value.to_string(),+ }+ }+}++/// The high-level definition of an AI projection.+///+/// Keyed by a frontend-defined text `id`. Multiple users share a single+/// definition; each user's materialized instance is a [`UserAiProjection`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AiProjection {+ /// The frontend-defined identifier (e.g. `notification_important_widget`).+ pub id: String,+ /// The prompt used to materialize the projection.+ pub prompt: String,+ /// A hash of the prompt, used to version cached instances.+ pub prompt_hash: String,+ /// Whether this projection is materialized per user or per team.+ pub target_type: TargetType,+ /// How frequently the projection should be regenerated.+ pub refresh_cadence: RefreshCadence,+ /// How long the projection remains active without being requested.+ pub expiry: Expiry,+ /// When the definition was created.+ pub created_at: DateTime<Utc>,+ /// When the definition was last updated.+ pub updated_at: DateTime<Utc>,+}++/// A per-user cached instance of an [`AiProjection`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct UserAiProjection {+ /// The surrogate id of the instance.+ pub id: uuid::Uuid,+ /// The id of the projection definition this instance materializes.+ pub ai_projection_id: String,+ /// The target this instance belongs to (a user id or a team id, per the+ /// parent projection's `target_type`).+ pub target_id: String,+ /// The prompt hash at the time the instance was created.+ pub prompt_hash: String,+ /// The materialization status.+ pub status: ProjectionStatus,+ /// The cached result, if any. A plain string for now.+ pub result: Option<String>,+ /// An error message, if materialization failed.+ pub error: Option<String>,+ /// When the result was generated.+ pub generated_at: Option<DateTime<Utc>>,+ /// When the result becomes stale.+ pub stale_at: Option<DateTime<Utc>>,+}++/// Parameters for getting or creating a projection and the requesting user's+/// instance of it.+#[derive(Debug, Clone)]+pub struct UpsertProjectionParams {+ /// The frontend-defined projection id.+ pub id: String,+ /// The prompt used to materialize the projection.+ pub prompt: String,+ /// Whether the projection is materialized for the requesting user or their+ /// team. The concrete target id is resolved from the authenticated user.+ pub target_type: TargetType,+ /// How frequently the projection should be regenerated.+ pub refresh_cadence: RefreshCadence,+ /// How long the projection remains active without being requested.+ pub expiry: Expiry,+}++/// Errors for ai projection storage operations.+#[derive(Debug, thiserror::Error)]+pub enum AiProjectionError {+ /// The projection does not exist.+ #[error("the projection does not exist")]+ NotFound,+ /// The request was invalid.+ #[error("bad request: {0}")]+ BadRequest(String),+ /// A stored value could not be parsed into a domain type.+ #[error("invalid stored data: {0}")]+ InvalidStoredData(#[from] ParseEnumError),+ /// Storage layer error.+ #[error("storage layer error: {0}")]+ StorageLayerError(#[from] anyhow::Error),+}++/// Errors for the get-or-create projection operation.+#[derive(Debug, thiserror::Error)]+pub enum UpsertProjectionError {+ /// The request was invalid.+ #[error("bad request: {0}")]+ BadRequest(String),+ /// Underlying storage error.+ #[error(transparent)]+ AiProjectionError(#[from] AiProjectionError),+}diff --git a/rust/cloud-storage/ai_projections/src/inbound.rs b/rust/cloud-storage/ai_projections/src/inbound.rsnew file mode 100644index 0000000000..32beca2bf0--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/inbound.rs@@ -0,0 +1,4 @@+//! Inbound adapters for the ai projections domain.++#[cfg(feature = "axum")]+pub mod axum_router;diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rsnew file mode 100644index 0000000000..342d590f05--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/mod.rs@@ -0,0 +1,93 @@+//! Axum router for ai projection endpoints.++/// Extractor ensuring the authenticated user has professional features.+pub mod premium_user;+/// Get-or-create a projection and the requesting user's instance.+pub mod upsert_projection;++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::post,+};+use model_error_response::ErrorResponse;++use crate::domain::{+ ai_projection_service::AiProjectionService,+ model::{AiProjectionError, UpsertProjectionError},+};++/// Router state containing the ai projection service.+pub struct AiProjectionRouterState<T> {+ /// The ai projection service implementation.+ pub service: Arc<T>,+}++// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).+impl<T> Clone for AiProjectionRouterState<T> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++/// Build the ai projections router with all endpoints.+pub fn ai_projections_router<T, S>(state: AiProjectionRouterState<T>) -> Router<S>+where+ T: AiProjectionService,+ S: Send + Sync + 'static,+{+ Router::new()+ .route("/ai-projections", post(upsert_projection::handler::<T>))+ .with_state(state)+}++// --- Error IntoResponse implementations ---++impl IntoResponse for AiProjectionError {+ fn into_response(self) -> Response {+ match self {+ AiProjectionError::NotFound => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "projection does not exist".into(),+ }),+ ),+ AiProjectionError::BadRequest(msg) => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: msg.into(),+ }),+ ),+ AiProjectionError::InvalidStoredData(_) | AiProjectionError::StorageLayerError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal server error".into(),+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for UpsertProjectionError {+ fn into_response(self) -> Response {+ match self {+ UpsertProjectionError::BadRequest(msg) => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: msg.into(),+ }),+ )+ .into_response(),+ UpsertProjectionError::AiProjectionError(err) => err.into_response(),+ }+ }+}diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/premium_user.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/premium_user.rsnew file mode 100644index 0000000000..803b1edcbf--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/premium_user.rs@@ -0,0 +1,85 @@+//! Extractor that ensures the authenticated user has professional features.++use axum::{+ Json,+ extract::FromRequestParts,+ http::{StatusCode, request::Parts},+ response::{IntoResponse, Response},+};+use macro_user_id::user_id::MacroUserIdStr;+use model_error_response::ErrorResponse;+use model_user::axum_extractor::{MacroUserExtractor, UserExtractorErr};++use crate::domain::{ai_projection_service::AiProjectionService, model::AiProjectionError};++use super::AiProjectionRouterState;++/// Extractor that ensures the authenticated user has the+/// `read:professional_features` permission.+pub struct PremiumUserExtractor {+ /// The authenticated professional user's id.+ pub macro_user_id: MacroUserIdStr<'static>,+}++/// Rejection returned when the professional features check fails.+#[derive(Debug, thiserror::Error)]+pub enum PremiumUserRejection {+ /// The user could not be extracted from the request.+ #[error(transparent)]+ User(#[from] UserExtractorErr),+ /// The user does not have the required permission.+ #[error("professional features required")]+ NotAuthorized,+ /// The permission check could not be performed.+ #[error(transparent)]+ Service(#[from] AiProjectionError),+}++impl IntoResponse for PremiumUserRejection {+ fn into_response(self) -> Response {+ match self {+ PremiumUserRejection::User(err) => err.into_response(),+ PremiumUserRejection::NotAuthorized => (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: "professional features required".into(),+ }),+ )+ .into_response(),+ PremiumUserRejection::Service(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal server error".into(),+ }),+ )+ .into_response(),+ }+ }+}++impl<T> FromRequestParts<AiProjectionRouterState<T>> for PremiumUserExtractor+where+ T: AiProjectionService,+{+ type Rejection = PremiumUserRejection;++ #[tracing::instrument(err, skip(parts, state))]+ async fn from_request_parts(+ parts: &mut Parts,+ state: &AiProjectionRouterState<T>,+ ) -> Result<Self, Self::Rejection> {+ let user = MacroUserExtractor::from_request_parts(parts, state).await?;++ if !state+ .service+ .has_professional_features(&user.macro_user_id)+ .await?+ {+ return Err(PremiumUserRejection::NotAuthorized);+ }++ Ok(Self {+ macro_user_id: user.macro_user_id,+ })+ }+}diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..d63c551e10--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/test.rs@@ -0,0 +1,106 @@+//! Integration tests for the ai projections axum router.++use std::sync::Arc;++use axum::{Extension, http::StatusCode};+use http_body_util::BodyExt;+use macro_user_id::user_id::MacroUserIdStr;+use model_user::UserContext;+use tower::ServiceExt;++use super::{AiProjectionRouterState, ai_projections_router};+use crate::domain::{+ ai_projection_service::AiProjectionService,+ model::{+ AiProjectionError, ProjectionStatus, UpsertProjectionError, UpsertProjectionParams,+ UserAiProjection,+ },+};++#[derive(Clone)]+struct MockService {+ has_permission: bool,+}++impl AiProjectionService for MockService {+ async fn upsert_projection(+ &self,+ user_id: &MacroUserIdStr<'_>,+ params: UpsertProjectionParams,+ ) -> Result<UserAiProjection, UpsertProjectionError> {+ Ok(UserAiProjection {+ id: macro_uuid::generate_uuid_v7(),+ ai_projection_id: params.id,+ target_id: user_id.as_ref().to_string(),+ prompt_hash: "hash".to_string(),+ status: ProjectionStatus::Cold,+ result: None,+ error: None,+ generated_at: None,+ stale_at: None,+ })+ }++ async fn has_professional_features(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ ) -> Result<bool, AiProjectionError> {+ Ok(self.has_permission)+ }+}++fn test_user_context() -> UserContext {+ UserContext {+ user_id: "macro|[email protected]".to_string(),+ fusion_user_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),+ permissions: None,+ organization_id: None,+ }+}++fn build_router(has_permission: bool) -> axum::Router {+ let state = AiProjectionRouterState {+ service: Arc::new(MockService { has_permission }),+ };+ ai_projections_router(state).layer(Extension(test_user_context()))+}++fn post_request() -> axum::http::Request<axum::body::Body> {+ axum::http::Request::builder()+ .uri("/ai-projections")+ .method("POST")+ .header("content-type", "application/json")+ .body(axum::body::Body::from(+ serde_json::json!({+ "id": "inbox/important",+ "prompt": "What is important?",+ "target_type": "user",+ "refresh_cadence": "high",+ "expiry": "day"+ })+ .to_string(),+ ))+ .unwrap()+}++#[tokio::test]+async fn upsert_projection_returns_cold_state_for_professional_user() {+ let app = build_router(true);++ let response = app.oneshot(post_request()).await.unwrap();+ assert_eq!(response.status(), StatusCode::OK);++ let body = response.into_body().collect().await.unwrap().to_bytes();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(json["id"], "inbox/important");+ assert_eq!(json["status"], "cold");+ assert!(json["data"].is_null());+}++#[tokio::test]+async fn upsert_projection_is_forbidden_without_professional_features() {+ let app = build_router(false);++ let response = app.oneshot(post_request()).await.unwrap();+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+}diff --git a/rust/cloud-storage/ai_projections/src/inbound/axum_router/upsert_projection.rs b/rust/cloud-storage/ai_projections/src/inbound/axum_router/upsert_projection.rsnew file mode 100644index 0000000000..8e243e151f--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/inbound/axum_router/upsert_projection.rs@@ -0,0 +1,94 @@+//! Handler that gets or creates a projection definition and the requesting+//! user's instance of it.++use axum::{Json, extract::State};+use chrono::{DateTime, Utc};++use crate::domain::{+ ai_projection_service::AiProjectionService,+ model::{+ Expiry, ProjectionStatus, RefreshCadence, TargetType, UpsertProjectionError,+ UpsertProjectionParams, UserAiProjection,+ },+};++use super::{AiProjectionRouterState, premium_user::PremiumUserExtractor};++/// Request body for getting or creating an ai projection. The concrete target+/// id is resolved from the authenticated user, so only the target type is sent.+#[derive(Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct UpsertProjectionRequest {+ /// The frontend-defined projection id (e.g. `notification_important_widget`).+ pub id: String,+ /// The prompt used to materialize the projection.+ pub prompt: String,+ /// Whether the projection is materialized for the requesting user or their team.+ pub target_type: TargetType,+ /// How frequently the projection should be regenerated.+ pub refresh_cadence: RefreshCadence,+ /// How long the projection remains active without being requested.+ pub expiry: Expiry,+}++/// The current state of a user's projection instance.+#[derive(Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct ProjectionStateResponse {+ /// The projection id.+ pub id: String,+ /// The materialization status.+ pub status: ProjectionStatus,+ /// The cached result, if any.+ pub data: Option<String>,+ /// When the result was generated.+ pub generated_at: Option<DateTime<Utc>>,+ /// When the result becomes stale.+ pub stale_at: Option<DateTime<Utc>>,+}++impl From<UserAiProjection> for ProjectionStateResponse {+ fn from(instance: UserAiProjection) -> Self {+ Self {+ id: instance.ai_projection_id,+ status: instance.status,+ data: instance.result,+ generated_at: instance.generated_at,+ stale_at: instance.stale_at,+ }+ }+}++/// Gets or creates an ai projection and the requesting user's cold instance.+#[utoipa::path(+ post,+ path = "/ai-projections",+ operation_id = "upsert_ai_projection",+ request_body = UpsertProjectionRequest,+ responses(+ (status = 200, body = ProjectionStateResponse),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 403, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: AiProjectionService>(+ State(state): State<AiProjectionRouterState<T>>,+ premium_user: PremiumUserExtractor,+ Json(req): Json<UpsertProjectionRequest>,+) -> Result<Json<ProjectionStateResponse>, UpsertProjectionError> {+ let target_projection = state+ .service+ .upsert_projection(+ &premium_user.macro_user_id,+ UpsertProjectionParams {+ id: req.id,+ prompt: req.prompt,+ target_type: req.target_type,+ refresh_cadence: req.refresh_cadence,+ expiry: req.expiry,+ },+ )+ .await?;++ Ok(Json(target_projection.into()))+}diff --git a/rust/cloud-storage/ai_projections/src/lib.rs b/rust/cloud-storage/ai_projections/src/lib.rsnew file mode 100644index 0000000000..6907fa30d9--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/lib.rs@@ -0,0 +1,25 @@+#![deny(missing_docs)]+//! AI projections hexagonal architecture crate.+//!+//! An AI projection is a materialized, cached AI-generated view of a user's+//! underlying data, keyed by a frontend-defined text id (e.g.+//! `notification_important_widget`). The high-level definition lives in the+//! `ai_projection` table, while each user's cached instance lives in the+//! `user_ai_projection` table.+//!+//! # Architecture+//!+//! - **domain**: Domain models, ports (traits), and the service implementation+//! - **outbound**: Adapters for external dependencies (PostgreSQL)+//! - **inbound**: Adapters for incoming requests (Axum handlers)++/// The domain module contains the domain logic for ai projections+pub mod domain;++/// The inbound module contains the inbound adapters for ai projections+#[cfg(feature = "inbound")]+pub mod inbound;++/// The outbound module contains the outbound adapters for ai projections+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/ai_projections/src/outbound.rs b/rust/cloud-storage/ai_projections/src/outbound.rsnew file mode 100644index 0000000000..5d86bc5af7--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/outbound.rs@@ -0,0 +1,3 @@+//! Outbound adapters for the ai projections domain.++pub mod ai_projection_repo;diff --git a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rsnew file mode 100644index 0000000000..3445e20306--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo.rs@@ -0,0 +1,192 @@+//! Implementation of [`AiProjectionRepository`] backed by MacroDB.++use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;++use crate::domain::{+ ai_projection_repo::AiProjectionRepository,+ model::{+ AiProjection, AiProjectionError, Expiry, ProjectionStatus, RefreshCadence, TargetType,+ UserAiProjection,+ },+};++#[cfg(test)]+mod test;++/// The AiProjectionRepositoryImpl is a wrapper around a sqlx::PgPool connected+/// to macrodb.+#[derive(Clone)]+pub struct AiProjectionRepositoryImpl {+ /// The underlying sqlx::PgPool connected to macrodb.+ pool: PgPool,+}++impl AiProjectionRepositoryImpl {+ /// Creates a new instance of AiProjectionRepositoryImpl.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl AiProjectionRepository for AiProjectionRepositoryImpl {+ #[tracing::instrument(skip(self), err)]+ async fn get_or_create_projection(+ &self,+ id: &str,+ prompt: &str,+ prompt_hash: &str,+ target_type: TargetType,+ refresh_cadence: RefreshCadence,+ expiry: Expiry,+ ) -> Result<AiProjection, AiProjectionError> {+ // Get-or-create: insert if absent, leave existing rows untouched, then+ // read back the canonical row.+ sqlx::query!(+ r#"+ INSERT INTO ai_projection (id, prompt, prompt_hash, target_type, refresh_cadence, expiry)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (id) DO NOTHING+ "#,+ id,+ prompt,+ prompt_hash,+ target_type.to_string(),+ refresh_cadence.to_string(),+ expiry.to_string(),+ )+ .execute(&self.pool)+ .await+ .map_err(sqlx_err)?;++ let row = sqlx::query!(+ r#"+ SELECT id, prompt, prompt_hash, target_type, refresh_cadence, expiry, created_at, updated_at+ FROM ai_projection+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(&self.pool)+ .await+ .map_err(sqlx_err)?;++ Ok(AiProjection {+ id: row.id,+ prompt: row.prompt,+ prompt_hash: row.prompt_hash,+ target_type: row.target_type.parse()?,+ refresh_cadence: row.refresh_cadence.parse()?,+ expiry: row.expiry.parse()?,+ created_at: row.created_at,+ updated_at: row.updated_at,+ })+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_or_create_target_projection(+ &self,+ ai_projection_id: &str,+ target_id: &str,+ prompt_hash: &str,+ ) -> Result<UserAiProjection, AiProjectionError> {+ let id = macro_uuid::generate_uuid_v7();++ sqlx::query!(+ r#"+ INSERT INTO user_ai_projection (id, ai_projection_id, target_id, prompt_hash, status)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (ai_projection_id, target_id, prompt_hash) DO NOTHING+ "#,+ id,+ ai_projection_id,+ target_id,+ prompt_hash,+ ProjectionStatus::Cold.to_string(),+ )+ .execute(&self.pool)+ .await+ .map_err(sqlx_err)?;++ let row = sqlx::query!(+ r#"+ SELECT id, ai_projection_id, target_id, prompt_hash, status,+ result, error, generated_at, stale_at+ FROM user_ai_projection+ WHERE ai_projection_id = $1 AND target_id = $2 AND prompt_hash = $3+ "#,+ ai_projection_id,+ target_id,+ prompt_hash,+ )+ .fetch_one(&self.pool)+ .await+ .map_err(sqlx_err)?;++ Ok(UserAiProjection {+ id: row.id,+ ai_projection_id: row.ai_projection_id,+ target_id: row.target_id,+ prompt_hash: row.prompt_hash,+ status: row.status.parse()?,+ result: row.result,+ error: row.error,+ generated_at: row.generated_at,+ stale_at: row.stale_at,+ })+ }++ #[tracing::instrument(skip(self), err)]+ async fn user_has_permission(+ &self,+ user_id: &MacroUserIdStr<'_>,+ permission: &str,+ ) -> Result<bool, AiProjectionError> {+ let has_permission = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM "RolesOnUsers" ru+ JOIN "RolesOnPermissions" rp ON ru."roleId" = rp."roleId"+ WHERE ru."userId" = $1 AND rp."permissionId" = $2+ ) AS "has_permission!"+ "#,+ user_id.as_ref(),+ permission,+ )+ .fetch_one(&self.pool)+ .await+ .map_err(sqlx_err)?;++ Ok(has_permission)+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_user_team_ids(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<Vec<uuid::Uuid>, AiProjectionError> {+ let team_ids = sqlx::query_scalar!(+ r#"+ SELECT team_id+ FROM team_user+ WHERE user_id = $1+ "#,+ user_id.as_ref(),+ )+ .fetch_all(&self.pool)+ .await+ .map_err(sqlx_err)?;++ Ok(team_ids)+ }+}++/// Maps a [`sqlx::Error`] into an [`AiProjectionError`], surfacing missing rows+/// as [`AiProjectionError::NotFound`].+fn sqlx_err(e: sqlx::Error) -> AiProjectionError {+ match e {+ sqlx::Error::RowNotFound => AiProjectionError::NotFound,+ other => AiProjectionError::StorageLayerError(other.into()),+ }+}diff --git a/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rsnew file mode 100644index 0000000000..8b425e1a3f--- /dev/null+++ b/rust/cloud-storage/ai_projections/src/outbound/ai_projection_repo/test.rs@@ -0,0 +1,164 @@+//! Tests for the AiProjectionRepositoryImpl.++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::{Pool, Postgres};++use super::*;+use crate::domain::ai_projection_service::READ_PROFESSIONAL_FEATURES;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn get_or_create_projection_is_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool);++ let first = repo+ .get_or_create_projection(+ "inbox/important",+ "What is important?",+ "hash_v1",+ TargetType::User,+ RefreshCadence::High,+ Expiry::Day,+ )+ .await?;++ // A second call with a different prompt/target_type must NOT update the existing row.+ let second = repo+ .get_or_create_projection(+ "inbox/important",+ "A totally different prompt",+ "hash_v2",+ TargetType::Team,+ RefreshCadence::Low,+ Expiry::Month,+ )+ .await?;++ assert_eq!(first, second);+ assert_eq!(second.prompt, "What is important?");+ assert_eq!(second.prompt_hash, "hash_v1");+ assert_eq!(second.target_type, TargetType::User);+ assert_eq!(second.refresh_cadence, RefreshCadence::High);+ assert_eq!(second.expiry, Expiry::Day);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn get_or_create_target_projection_is_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool);+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]")?;++ repo.get_or_create_projection(+ "inbox/important",+ "What is important?",+ "hash_v1",+ TargetType::User,+ RefreshCadence::High,+ Expiry::Day,+ )+ .await?;++ let first = repo+ .get_or_create_target_projection("inbox/important", user.as_ref(), "hash_v1")+ .await?;+ let second = repo+ .get_or_create_target_projection("inbox/important", user.as_ref(), "hash_v1")+ .await?;++ assert_eq!(first.id, second.id);+ assert_eq!(first.ai_projection_id, "inbox/important");+ assert_eq!(first.target_id, "macro|[email protected]");+ assert_eq!(first.status, ProjectionStatus::Cold);+ assert!(first.result.is_none());++ // A new prompt version creates a separate instance.+ let other_version = repo+ .get_or_create_target_projection("inbox/important", user.as_ref(), "hash_v2")+ .await?;+ assert_ne!(first.id, other_version.id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn get_or_create_target_projection_supports_team_targets(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool);++ repo.get_or_create_projection(+ "team/focus",+ "What is my team focused on?",+ "hash_v1",+ TargetType::Team,+ RefreshCadence::Medium,+ Expiry::Week,+ )+ .await?;++ // A team target id (not a user id) is stored verbatim.+ let team_id = "11111111-1111-1111-1111-111111111111";+ let instance = repo+ .get_or_create_target_projection("team/focus", team_id, "hash_v1")+ .await?;++ assert_eq!(instance.target_id, team_id);+ assert_eq!(instance.status, ProjectionStatus::Cold);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn get_user_team_ids_returns_memberships(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool);++ let pro = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let free = MacroUserIdStr::parse_from_str("macro|[email protected]")?;++ let pro_teams = repo.get_user_team_ids(&pro).await?;+ assert_eq!(pro_teams.len(), 1);+ assert_eq!(+ pro_teams[0],+ uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111")?+ );++ assert!(repo.get_user_team_ids(&free).await?.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("ai_projections"))+)]+async fn user_has_permission_reflects_roles(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = AiProjectionRepositoryImpl::new(pool);++ let pro = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let free = MacroUserIdStr::parse_from_str("macro|[email protected]")?;++ assert!(+ repo.user_has_permission(&pro, READ_PROFESSIONAL_FEATURES)+ .await?+ );+ assert!(+ !repo+ .user_has_permission(&free, READ_PROFESSIONAL_FEATURES)+ .await?+ );++ Ok(())+}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 15b3fd2096..f2c11a1c02 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -25,6 +25,7 @@ local_queue = [][dependencies]agent = { path = "../agent", features = ["debug-messages"] }+ai_projections = { path = "../ai_projections" }ai_usage = { path = "../ai_usage" }aho-corasick = "1.1.3"attachment = { path = "../attachment", features = ["provider"] }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.rsindex 682f792f55..565eee0821 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@@ -58,6 +58,12 @@ pub type DcsMemoryService =pub type DcsUsageService =ai_usage::domain::service::UsageServiceImpl<ai_usage::outbound::PgUsageRepo>;+/// The AI projections service wired to the Postgres projection repo.+pub type DcsAiProjectionService =+ ai_projections::domain::ai_projection_service::AiProjectionServiceImpl<+ ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl,+ >;+/// Concrete MCP router state for DCS.pub type DcsMcpRouterState = mcp_client::inbound::McpRouterState<mcp_client::outbound::pg_server_repo::PgServerRepo,@@ -86,6 +92,7 @@ pub struct ApiContext {pub document_tool_context: ToolDocumentToolContext,pub memory_service: Arc<DcsMemoryService>,pub usage_service: Arc<DcsUsageService>,+ pub ai_projections_service: Arc<DcsAiProjectionService>,pub properties_tool_context: ToolPropertiesToolContext,pub email_tool_context: ToolEmailToolContext,pub call_tool_context: ToolCallToolContext,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.rsindex 4e6c54f81e..0abf596505 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@@ -347,6 +347,14 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_usage::outbound::PgUsageRepo::new(pool.clone()),));+ let ai_projections_service = Arc::new(+ ai_projections::domain::ai_projection_service::AiProjectionServiceImpl::new(+ ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(+ pool.clone(),+ ),+ ),+ );+let api_context = ApiContext {db: pool.clone(),sqs_client: Arc::new(sqs_client),@@ -370,6 +378,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ardocument_tool_context: document_tool_context.clone(),memory_service,usage_service,+ ai_projections_service,properties_tool_context,email_tool_context,call_tool_context,diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex b0664ff1b1..5816644349 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -72,6 +72,7 @@ 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 usage_service = api_context.usage_service.clone();+ let ai_projections_service = api_context.ai_projections_service.clone();let mcp_state = api_context.mcp_state.clone();@@ -97,6 +98,11 @@ fn api_router(api_context: ApiContext) -> Router {.nest("/id_mapping", id_mapping::router()).merge(memory::inbound::axum_router::memory_router(memory_service)).merge(ai_usage::inbound::ai_usage_router(usage_service))+ .merge(ai_projections::inbound::axum_router::ai_projections_router(+ ai_projections::inbound::axum_router::AiProjectionRouterState {+ service: ai_projections_service,+ },+ )).merge(mcp_client::inbound::mcp_router(mcp_state.clone())).with_state(api_context.clone()).route(diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex 11b4fa2a2f..f592476b1c 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -17,6 +17,10 @@ use crate::model::{response::attachments::GetChatsForAttachmentResponse,stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},};+use ai_projections::domain::model::{Expiry, ProjectionStatus, RefreshCadence, TargetType};+use ai_projections::inbound::axum_router::upsert_projection::{+ ProjectionStateResponse, UpsertProjectionRequest,+};use ai_usage::inbound::axum_router::{self as ai_usage_api};use mcp_client::inbound::axum_router::{self as mcp_api, AddServerRequest, ServerResponse, StartAuthRequest, StartAuthResponse,@@ -86,6 +90,7 @@ use utoipa::OpenApi;memory_api::get_memory_handler,ai_usage_api::get_usage_handler,ai_usage_api::set_pricing_handler,+ ai_projections::inbound::axum_router::upsert_projection::handler::<crate::api::context::DcsAiProjectionService>,mcp_api::list_servers,mcp_api::add_server,mcp_api::update_server,@@ -185,6 +190,14 @@ use utoipa::OpenApi;ai_usage::Price,ai_usage::AiFeature,+ // AI projections+ UpsertProjectionRequest,+ ProjectionStateResponse,+ TargetType,+ RefreshCadence,+ Expiry,+ ProjectionStatus,+// MCPServerResponse,AddServerRequest,diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 83ea1310f3..c27923005c 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -412,6 +412,16 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized ai cost service");+ let ai_projections_service = Arc::new(+ ai_projections::domain::ai_projection_service::AiProjectionServiceImpl::new(+ ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(+ db.clone(),+ ),+ ),+ );++ tracing::info!("initialized ai projections service");+let mcp_credentials_key_b64 = match config.environment {Environment::Local => config.mcp_credentials_key_secret_name.clone(),_ => secretsmanager_client@@ -459,6 +469,7 @@ async fn main() -> anyhow::Result<()> {document_tool_context,memory_service,usage_service,+ ai_projections_service,properties_tool_context,email_tool_context: email_tool_context.clone(),call_tool_context,diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 860dcb042c..f8ff897f03 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -113,6 +113,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./bots/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./call_recording_preview_handler/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./share_permission_db_utils/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./ai_projections/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260622133041_create_ai_projection_tables.sql b/rust/cloud-storage/macro_db_client/migrations/20260622133041_create_ai_projection_tables.sqlnew file mode 100644index 0000000000..5c2b06fc3c--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260622133041_create_ai_projection_tables.sql@@ -0,0 +1,45 @@+-- High-level AI projection definitions, keyed by a frontend-defined text id+-- (e.g. `notification_important_widget`). `target_type` declares whether the+-- projection is materialized per user or per team.+CREATE TABLE ai_projection (+ id TEXT NOT NULL,+ prompt TEXT NOT NULL,+ prompt_hash TEXT NOT NULL,+ target_type TEXT NOT NULL,+ refresh_cadence TEXT NOT NULL,+ expiry TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT ai_projection_pkey PRIMARY KEY (id),+ CONSTRAINT ai_projection_target_type_check CHECK (target_type IN ('user', 'team')),+ CONSTRAINT ai_projection_refresh_cadence_check CHECK (refresh_cadence IN ('high', 'medium', 'low')),+ CONSTRAINT ai_projection_expiry_check CHECK (expiry IN ('day', 'week', 'month'))+);++-- Per-target cached instances of an AI projection. `target_id` holds either a+-- user id or a team id, interpreted via the parent projection's `target_type`.+-- Keyed by (ai_projection_id, target_id, prompt_hash) so a projection is+-- cached, refreshed, and expired independently per target and prompt version.+CREATE TABLE user_ai_projection (+ id UUID NOT NULL,+ ai_projection_id TEXT NOT NULL REFERENCES ai_projection (id) ON DELETE CASCADE,+ target_id TEXT NOT NULL,+ prompt_hash TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'cold',+ result TEXT,+ error TEXT,+ generated_at TIMESTAMPTZ,+ stale_at TIMESTAMPTZ,+ last_requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT user_ai_projection_pkey PRIMARY KEY (id),+ CONSTRAINT user_ai_projection_cache_key UNIQUE (ai_projection_id, target_id, prompt_hash),+ CONSTRAINT user_ai_projection_status_check+ CHECK (status IN ('loading', 'cold', 'ready', 'refreshing', 'error'))+);++CREATE INDEX user_ai_projection_target_idx ON user_ai_projection (target_id);+CREATE INDEX user_ai_projection_projection_idx ON user_ai_projection (ai_projection_id);