🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(topic): persist topic analysis after the auto summary (#22012)
Arvin Xu6445edecf5dc
diff --git a/apps/server/src/router-hono/workflows/topic-auto-summary/execute.test.ts b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.test.tsnew file mode 100644index 00000000000..e12ee3bcc00--- /dev/null+++ b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.test.ts@@ -0,0 +1,56 @@+import type { WorkflowContext } from '@upstash/workflow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ExecuteTopicAutoSummaryPayload } from '@/server/workflows/topicAutoSummary';++import { executeTopicAutoSummary } from './execute';++const mocks = vi.hoisted(() => ({ analyze: vi.fn(), summarize: vi.fn() }));++vi.mock('@/database/server', () => ({ getServerDB: vi.fn(async () => ({})) }));+vi.mock('@/server/services/topicAutoSummary', () => ({+ TopicAutoSummaryService: class {+ analyze = mocks.analyze;+ summarize = mocks.summarize;+ },+}));++const createContext = () => {+ const steps: string[] = [];+ const context = {+ requestPayload: { topicId: 'topic-1', userId: 'user-1' },+ run: vi.fn(async (name: string, fn: () => Promise<unknown>) => {+ steps.push(name);+ return fn();+ }),+ } as unknown as WorkflowContext<ExecuteTopicAutoSummaryPayload>;+ return { context, steps };+};++describe('executeTopicAutoSummary', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.summarize.mockResolvedValue({ summarized: true });+ mocks.analyze.mockResolvedValue({ analyzed: true });+ });++ it('analyzes in its own step after a successful summary', async () => {+ const { context, steps } = createContext();++ const result = await executeTopicAutoSummary(context);++ expect(steps).toEqual(['topic-auto-summary:generate-and-save', 'topic-auto-summary:analyze']);+ expect(result).toEqual({ analysis: { analyzed: true }, summarized: true });+ });++ it('does not analyze when no summary was written', async () => {+ mocks.summarize.mockResolvedValue({ reason: 'stale', summarized: false });+ const { context, steps } = createContext();++ const result = await executeTopicAutoSummary(context);++ expect(steps).toEqual(['topic-auto-summary:generate-and-save']);+ expect(result).toEqual({ reason: 'stale', summarized: false });+ expect(mocks.analyze).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.tsindex 9cfd12b7918..dfba8d25cf2 100644--- a/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts+++ b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts@@ -11,10 +11,19 @@ export const executeTopicAutoSummary = async (const { force, topicId, userId, workspaceId } = context.requestPayload ?? {};if (!topicId || !userId) return { error: 'Missing topicId or userId', summarized: false };- return runStep(context, 'topic-auto-summary:generate-and-save', async () => {+ const summary = await runStep(context, 'topic-auto-summary:generate-and-save', async () => {const db = await getServerDB();return new TopicAutoSummaryService(db, userId, workspaceId).summarize(topicId, { force });});+ if (!summary.summarized) return summary;++ // A separate step gets its own time budget and retry boundary, so a slow or+ // failing analysis never replays (and re-bills) the summary committed above.+ const analysis = await runStep(context, 'topic-auto-summary:analyze', async () => {+ const db = await getServerDB();+ return new TopicAutoSummaryService(db, userId, workspaceId).analyze(topicId, { force });+ });+ return { ...summary, analysis };};export const executeTopicAutoSummaryOptions = {diff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsindex b1638b96b0f..76dd461ba98 100644--- a/apps/server/src/services/topicAutoSummary/index.test.ts+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -5,12 +5,26 @@ import type { LobeChatDatabase } from '@/database/type';import { TopicAutoSummaryService } from './index';const mocks = vi.hoisted(() => ({+ analyzeTopic: vi.fn(),generateObject: vi.fn(),+ isTopicAnalysisEnabled: vi.fn(),+ saveTopicAnalysis: vi.fn(),+ snapshotTopicUsage: vi.fn(),getUserSettings: vi.fn(),resolveSystemAgentModelConfig: vi.fn(),updateSummaryIfCurrent: vi.fn(),}));+vi.mock('@/business/server/topicAnalysis', () => ({+ analyzeTopic: mocks.analyzeTopic,+ isTopicAnalysisEnabled: mocks.isTopicAnalysisEnabled,+}));+vi.mock('@/database/models/topicAnalysis', () => ({+ TopicAnalysisModel: class {+ save = mocks.saveTopicAnalysis;+ snapshotTopicUsage = mocks.snapshotTopicUsage;+ },+}));vi.mock('@/database/models/topicSummary', () => ({TopicSummaryModel: class {updateSummaryIfCurrent = mocks.updateSummaryIfCurrent;@@ -163,4 +177,112 @@ describe('TopicAutoSummaryService', () => {await expect(service.summarize('topic-1', { force: true })).rejects.toThrow('provider down');});++ describe('analyze', () => {+ const analysis = {+ category: 'coding',+ intent: 'doing',+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ taxonomyVersion: 'v1',+ };+ const usage = { toolCalls: 2, totalTokens: 1000, userMessages: 1 };++ beforeEach(() => {+ mocks.isTopicAnalysisEnabled.mockReturnValue(true);+ mocks.analyzeTopic.mockResolvedValue(analysis);+ mocks.saveTopicAnalysis.mockResolvedValue({ id: 'row-1' });+ mocks.snapshotTopicUsage.mockResolvedValue(usage);+ });++ it('does nothing when the deployment has no topic analysis', async () => {+ mocks.isTopicAnalysisEnabled.mockReturnValue(false);+ const db = createDb();++ const result = await new TopicAutoSummaryService(db, 'user-1').analyze('topic-1');++ expect(result).toEqual({ analyzed: false, reason: 'disabled' });+ expect(mocks.getUserSettings).not.toHaveBeenCalled();+ expect(mocks.analyzeTopic).not.toHaveBeenCalled();+ });++ it('classifies the rolling summary and recent transcript and saves the snapshot', async () => {+ const service = new TopicAutoSummaryService(createDb(), 'user-1', 'ws-1');++ const result = await service.analyze('topic-1');++ expect(result).toEqual({ analyzed: true });+ expect(mocks.analyzeTopic).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ summary: 'Earlier decision: use PostgreSQL.',+ topicId: 'topic-1',+ transcript: 'USER: What is next?',+ userId: 'user-1',+ workspaceId: 'ws-1',+ }),+ );+ expect(mocks.saveTopicAnalysis).toHaveBeenCalledWith({+ lastMessageId: 'message-1',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ result: analysis,+ topicId: 'topic-1',+ usage,+ });+ expect(mocks.snapshotTopicUsage).toHaveBeenCalledWith('topic-1');+ expect(mocks.generateObject).not.toHaveBeenCalled();+ });++ it('applies the same opt-in and visitor guards as the summary', async () => {+ mocks.getUserSettings.mockResolvedValue({});+ expect(await new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1')).toEqual({+ analyzed: false,+ reason: 'disabled',+ });++ mocks.getUserSettings.mockResolvedValue({+ systemAgent: { topicAutoSummary: { enabled: true } },+ });+ const visitorDb = createDb([[{ historySummary: null, senderId: 'visitor-9' }]]);+ expect(await new TopicAutoSummaryService(visitorDb, 'creator-1').analyze('topic-1')).toEqual({+ analyzed: false,+ reason: 'disabled',+ });+ expect(mocks.analyzeTopic).not.toHaveBeenCalled();+ });++ it('records nothing when the analysis has no usable result', async () => {+ mocks.analyzeTopic.mockResolvedValue(null);++ const result = await new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1');++ expect(result).toEqual({ analyzed: false, reason: 'invalid-output' });+ expect(mocks.saveTopicAnalysis).not.toHaveBeenCalled();+ });++ it('reports a stale result when a newer analysis is already stored', async () => {+ mocks.saveTopicAnalysis.mockResolvedValue(undefined);++ const result = await new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1');++ expect(result).toEqual({ analyzed: false, reason: 'stale' });+ });++ it('skips device-only models and rethrows other failures for the step to retry', async () => {+ mocks.analyzeTopic.mockRejectedValueOnce({+ errorType: 'ClientLlmExecutorUnavailable',+ });+ expect(await new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1')).toEqual({+ analyzed: false,+ reason: 'no-executor',+ });++ mocks.analyzeTopic.mockRejectedValueOnce(new Error('provider down'));+ await expect(+ new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1'),+ ).rejects.toThrow('provider down');+ expect(mocks.saveTopicAnalysis).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsindex 55cd04915ca..8f7c0b6dfb0 100644--- a/apps/server/src/services/topicAutoSummary/index.ts+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -10,6 +10,8 @@ import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';import debug from 'debug';import { and, desc, eq } from 'drizzle-orm';+import { analyzeTopic, isTopicAnalysisEnabled } from '@/business/server/topicAnalysis';+import { TopicAnalysisModel } from '@/database/models/topicAnalysis';import { topicSummaryEligibleMessage, TopicSummaryModel } from '@/database/models/topicSummary';import { UserModel } from '@/database/models/user';import { messages, topics } from '@/database/schemas';@@ -25,11 +27,29 @@ const MAX_MESSAGE_CHARS = 12_000;const MAX_PREVIOUS_SUMMARY_CHARS = 20_000;const MAX_TRANSCRIPT_CHARS = 60_000;+type SkipReason = 'disabled' | 'empty' | 'stale';+export interface TopicAutoSummaryResult {- reason?: 'disabled' | 'empty' | 'stale' | 'invalid-output' | 'no-executor';+ reason?: SkipReason | 'invalid-output' | 'no-executor';summarized: boolean;}+export interface TopicAnalysisOutcome {+ analyzed: boolean;+ reason?: SkipReason | 'invalid-output' | 'no-executor';+}++interface TopicContext {+ config: Partial<SystemAgentItem> | undefined;+ historySummary: string | null;+ latest: { id: string; updatedAt: Date };+ transcript: string;+}++const isClientOnlyModelError = (error: unknown) =>+ (error as { errorType?: unknown })?.errorType ===+ AgentRuntimeErrorType.ClientLlmExecutorUnavailable;+export class TopicAutoSummaryService {constructor(private readonly db: LobeChatDatabase,@@ -41,13 +61,127 @@ export class TopicAutoSummaryService {topicId: string,options: { force?: boolean } = {},): Promise<TopicAutoSummaryResult> => {+ const loaded = await this.loadContext(topicId, options.force);+ if ('reason' in loaded) return { reason: loaded.reason, summarized: false };+ const { config, historySummary, latest, transcript } = loaded.context;++ const { model, provider } = await resolveSystemAgentModelConfig({+ taskConfig: config,+ taskKey: 'topicAutoSummary',+ });+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ let output: { description?: string; summary?: string };+ try {+ output = (await ai.generateObject(+ {+ ...chainTopicAutoSummary({+ customPrompt: config?.customPrompt,+ previousSummary: historySummary?.slice(-MAX_PREVIOUS_SUMMARY_CHARS),+ transcript,+ }),+ model,+ provider,+ schema: TOPIC_AUTO_SUMMARY_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.TopicSummary },+ tracing: {+ promptVersion: TOPIC_AUTO_SUMMARY_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicAutoSummary,+ schemaName: TOPIC_AUTO_SUMMARY_JSON_SCHEMA.name,+ topicId,+ } satisfies TracingOptions,+ },+ )) as { description?: string; summary?: string };+ } catch (error) {+ // A device-only model (Ollama, LM Studio) runs in the user's open tab,+ // and this summary runs in a workflow with no tab attached. That is a+ // settled outcome, not a transient failure: skip the summary instead of+ // failing the step, which would only make the workflow retry in vain.+ if (isClientOnlyModelError(error)) {+ log('skip topic %s: %s has no executor outside a browser tab', topicId, provider);+ return { reason: 'no-executor', summarized: false };+ }+ throw error;+ }++ const description = output.description?.trim();+ const summary = output.summary?.trim();+ if (!description || !summary) return { reason: 'invalid-output', summarized: false };++ const updated = await new TopicSummaryModel(this.db).updateSummaryIfCurrent({+ description,+ lastMessageId: latest.id,+ lastMessageUpdatedAt: latest.updatedAt,+ summary,+ topicId,+ });++ return updated ? { summarized: true } : { reason: 'stale', summarized: false };+ };++ /**+ * Classify the topic from its rolling summary plus the recent transcript, and+ * record the result. Runs as its own workflow step after a successful summary,+ * so a failure retries only the analysis, never the committed summary.+ */+ analyze = async (+ topicId: string,+ options: { force?: boolean } = {},+ ): Promise<TopicAnalysisOutcome> => {+ if (!isTopicAnalysisEnabled()) return { analyzed: false, reason: 'disabled' };++ const loaded = await this.loadContext(topicId, options.force);+ if ('reason' in loaded) return { analyzed: false, reason: loaded.reason };+ const { config, historySummary, latest, transcript } = loaded.context;++ const { model, provider } = await resolveSystemAgentModelConfig({+ taskConfig: config,+ taskKey: 'topicAutoSummary',+ });+ let result: Awaited<ReturnType<typeof analyzeTopic>>;+ try {+ result = await analyzeTopic({+ db: this.db,+ model,+ provider,+ summary: historySummary?.slice(-MAX_PREVIOUS_SUMMARY_CHARS) || undefined,+ topicId,+ transcript,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ } catch (error) {+ if (isClientOnlyModelError(error)) return { analyzed: false, reason: 'no-executor' };+ throw error;+ }+ if (!result) {+ log('topic %s: analysis by %s/%s returned no usable result', topicId, provider, model);+ return { analyzed: false, reason: 'invalid-output' };+ }++ const analysisModel = new TopicAnalysisModel(this.db, this.userId, this.workspaceId);+ const saved = await analysisModel.save({+ lastMessageId: latest.id,+ lastMessageUpdatedAt: latest.updatedAt,+ result,+ topicId,+ usage: await analysisModel.snapshotTopicUsage(topicId),+ });+ return saved ? { analyzed: true } : { analyzed: false, reason: 'stale' };+ };++ /** Shared opt-in, ownership and visitor guards, then the bounded recent transcript. */+ private loadContext = async (+ topicId: string,+ force?: boolean,+ ): Promise<{ reason: SkipReason } | { context: TopicContext }> => {const settings = await new UserModel(this.db, this.userId).getUserSettings();const systemAgent = settings?.systemAgent as Partial<UserSystemAgentConfig> | undefined;const config = systemAgent?.topicAutoSummary as Partial<SystemAgentItem> | undefined;// Opt-in, so an absent setting means disabled — the dispatch query filters on// the same default, and this guard also covers replays that skip dispatch.- if (!options.force && config?.enabled !== true)- return { reason: 'disabled', summarized: false };+ if (!force && config?.enabled !== true) return { reason: 'disabled' };const ownership = this.workspaceId? eq(messages.workspaceId, this.workspaceId)@@ -65,7 +199,7 @@ export class TopicAutoSummaryService {// live-topic fence no longer finds it.if (!topic) {log('skipping missing or trashed topic %s', topicId);- return { reason: 'stale', summarized: false };+ return { reason: 'stale' };}// Share-visitor topics are creator-billed only through the share spend// gate. Reject them defensively before any LLM call — the dispatch query@@ -76,7 +210,7 @@ export class TopicAutoSummaryService {'skipping share-visitor topic %s: visitor turns are outside the auto-summary scope',topicId,);- return { reason: 'disabled', summarized: false };+ return { reason: 'disabled' };}const recent = await this.db.select({@@ -91,7 +225,7 @@ export class TopicAutoSummaryService {.limit(MAX_MESSAGES);const latest = recent[0];- if (!latest) return { reason: 'empty', summarized: false };+ if (!latest) return { reason: 'empty' };const transcript = recent.reverse()@@ -101,61 +235,9 @@ export class TopicAutoSummaryService {).join('\n\n').slice(-MAX_TRANSCRIPT_CHARS);- const { model, provider } = await resolveSystemAgentModelConfig({- taskConfig: config,- taskKey: 'topicAutoSummary',- });- const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);- let output: { description?: string; summary?: string };- try {- output = (await ai.generateObject(- {- ...chainTopicAutoSummary({- customPrompt: config?.customPrompt,- previousSummary: topic?.historySummary?.slice(-MAX_PREVIOUS_SUMMARY_CHARS),- transcript,- }),- model,- provider,- schema: TOPIC_AUTO_SUMMARY_JSON_SCHEMA,- },- {- metadata: { trigger: RequestTrigger.TopicSummary },- tracing: {- promptVersion: TOPIC_AUTO_SUMMARY_PROMPT_VERSION,- scenario: TRACING_SCENARIOS.TopicAutoSummary,- schemaName: TOPIC_AUTO_SUMMARY_JSON_SCHEMA.name,- topicId,- } satisfies TracingOptions,- },- )) as { description?: string; summary?: string };- } catch (error) {- // A device-only model (Ollama, LM Studio) runs in the user's open tab,- // and this summary runs in a workflow with no tab attached. That is a- // settled outcome, not a transient failure: skip the summary instead of- // failing the step, which would only make the workflow retry in vain.- if (- (error as { errorType?: unknown })?.errorType ===- AgentRuntimeErrorType.ClientLlmExecutorUnavailable- ) {- log('skip topic %s: %s has no executor outside a browser tab', topicId, provider);- return { reason: 'no-executor', summarized: false };- }- throw error;- }-- const description = output.description?.trim();- const summary = output.summary?.trim();- if (!description || !summary) return { reason: 'invalid-output', summarized: false };-- const updated = await new TopicSummaryModel(this.db).updateSummaryIfCurrent({- description,- lastMessageId: latest.id,- lastMessageUpdatedAt: latest.updatedAt,- summary,- topicId,- });- return updated ? { summarized: true } : { reason: 'stale', summarized: false };+ return {+ context: { config, historySummary: topic.historySummary ?? null, latest, transcript },+ };};}diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbmlindex 1038a7cd1aa..b66c85d9aeb 100644--- a/docs/development/database-schema.dbml+++ b/docs/development/database-schema.dbml@@ -4450,6 +4450,44 @@ table topics {}}+table topic_analyses {+ id uuid [pk, not null, default: `gen_random_uuid()`]+ topic_id text [not null]+ user_id text [not null]+ workspace_id text+ taxonomy_version text [not null]+ category text [not null]+ secondary_category text+ intent text+ outcome text+ labels jsonb+ metadata jsonb+ model text+ provider text+ topic_model text+ topic_provider text+ total_tokens integer+ total_input_tokens integer+ total_output_tokens integer+ total_cost "numeric(20, 6)"+ llm_calls integer+ tool_calls integer+ user_messages integer+ assistant_messages integer+ last_message_id text+ last_message_updated_at "timestamp with time zone"+ accessed_at "timestamp with time zone" [not null, default: `now()`]+ created_at "timestamp with time zone" [not null, default: `now()`]+ updated_at "timestamp with time zone" [not null, default: `now()`]++ indexes {+ (topic_id, taxonomy_version) [name: 'topic_analyses_topic_version_unique', unique]+ (user_id, created_at) [name: 'topic_analyses_user_id_created_at_idx']+ (workspace_id, created_at) [name: 'topic_analyses_workspace_id_created_at_idx']+ (taxonomy_version, category) [name: 'topic_analyses_version_category_idx']+ }+}+table topic_comment_mentions {id uuid [pk, not null, default: `gen_random_uuid()`]comment_id text [not null]diff --git a/locales/en-US/spend.json b/locales/en-US/spend.jsonindex fc5c54969d0..376bf1b79f8 100644--- a/locales/en-US/spend.json+++ b/locales/en-US/spend.json@@ -49,6 +49,7 @@"table.columns.trigger.enums.task": "Task","table.columns.trigger.enums.thread_title": "Thread Title","table.columns.trigger.enums.topic": "Topic Title (Legacy)",+ "table.columns.trigger.enums.topic_analysis": "Topic Analysis","table.columns.trigger.enums.topic_summary": "Topic Summary","table.columns.trigger.enums.topic_title": "Topic Title","table.columns.trigger.enums.translate": "Translation",diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.jsonindex 7ae3277ec51..2277bd636cc 100644--- a/locales/zh-CN/spend.json+++ b/locales/zh-CN/spend.json@@ -49,6 +49,7 @@"table.columns.trigger.enums.task": "任务","table.columns.trigger.enums.thread_title": "子话题标题","table.columns.trigger.enums.topic": "话题标题(旧)",+ "table.columns.trigger.enums.topic_analysis": "话题分析","table.columns.trigger.enums.topic_summary": "话题摘要","table.columns.trigger.enums.topic_title": "话题标题","table.columns.trigger.enums.translate": "翻译",diff --git a/packages/business-server/src/topicAnalysis.ts b/packages/business-server/src/topicAnalysis.tsnew file mode 100644index 00000000000..7a36cbf5c09--- /dev/null+++ b/packages/business-server/src/topicAnalysis.ts@@ -0,0 +1,23 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { TopicAnalysisResult } from '@lobechat/types';++export interface AnalyzeTopicParams {+ db: LobeChatDatabase;+ /** Model and provider the user assigned to the topic auto summary. */+ model: string;+ provider: string;+ /** Rolling summary of the whole topic; the transcript only covers the recent window. */+ summary?: string;+ topicId: string;+ /** Recent user / assistant messages, oldest first, bounded like the summary input. */+ transcript: string;+ userId: string;+ workspaceId?: string;+}++export const isTopicAnalysisEnabled = () => false;++/** Returns `null` when there is nothing to record for this topic. */+export const analyzeTopic = async (+ _params: AnalyzeTopicParams,+): Promise<TopicAnalysisResult | null> => null;diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex c785dbfd292..57769be443c 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -42,6 +42,7 @@ export const TRACING_SCENARIOS = {TaskInstruction: 'task_instruction',TaskIntent: 'task_intent',TopicTitle: 'topic_title',+ TopicAnalysis: 'topic_analysis',TopicAutoSummary: 'topic_auto_summary',UnderstandingAnalysis: 'understanding_analysis',UnderstandingDetailedPersona: 'understanding_detailed_persona',diff --git a/packages/database/migrations/0199_topic_analyses.sql b/packages/database/migrations/0199_topic_analyses.sqlnew file mode 100644index 00000000000..27c43bd828e--- /dev/null+++ b/packages/database/migrations/0199_topic_analyses.sql@@ -0,0 +1,41 @@+CREATE TABLE IF NOT EXISTS "topic_analyses" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "topic_id" text NOT NULL,+ "user_id" text NOT NULL,+ "workspace_id" text,+ "taxonomy_version" text NOT NULL,+ "category" text NOT NULL,+ "secondary_category" text,+ "intent" text,+ "outcome" text,+ "labels" jsonb,+ "metadata" jsonb,+ "model" text,+ "provider" text,+ "topic_model" text,+ "topic_provider" text,+ "total_tokens" integer,+ "total_input_tokens" integer,+ "total_output_tokens" integer,+ "total_cost" numeric(20, 6),+ "llm_calls" integer,+ "tool_calls" integer,+ "user_messages" integer,+ "assistant_messages" integer,+ "last_message_id" text,+ "last_message_updated_at" timestamp with time zone,+ "accessed_at" timestamp with time zone DEFAULT now() NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+ALTER TABLE "topic_analyses" DROP CONSTRAINT IF EXISTS "topic_analyses_topic_id_topics_id_fk";--> statement-breakpoint+ALTER TABLE "topic_analyses" ADD CONSTRAINT "topic_analyses_topic_id_topics_id_fk" FOREIGN KEY ("topic_id") REFERENCES "public"."topics"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "topic_analyses" DROP CONSTRAINT IF EXISTS "topic_analyses_user_id_users_id_fk";--> statement-breakpoint+ALTER TABLE "topic_analyses" ADD CONSTRAINT "topic_analyses_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "topic_analyses" DROP CONSTRAINT IF EXISTS "topic_analyses_workspace_id_workspaces_id_fk";--> statement-breakpoint+ALTER TABLE "topic_analyses" ADD CONSTRAINT "topic_analyses_workspace_id_workspaces_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspaces"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "topic_analyses_topic_version_unique" ON "topic_analyses" USING btree ("topic_id","taxonomy_version");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "topic_analyses_user_id_created_at_idx" ON "topic_analyses" USING btree ("user_id","created_at");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "topic_analyses_workspace_id_created_at_idx" ON "topic_analyses" USING btree ("workspace_id","created_at") WHERE "topic_analyses"."workspace_id" IS NOT NULL;--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "topic_analyses_version_category_idx" ON "topic_analyses" USING btree ("taxonomy_version","category");\ No newline at end of filediff --git a/packages/database/migrations/meta/0189_snapshot.json b/packages/database/migrations/meta/0199_snapshot.jsonsimilarity index 92%rename from packages/database/migrations/meta/0189_snapshot.jsonrename to packages/database/migrations/meta/0199_snapshot.jsonindex 3a701d3965d..04bd9359f97 100644--- a/packages/database/migrations/meta/0189_snapshot.json+++ b/packages/database/migrations/meta/0199_snapshot.json@@ -6,9 +6,9 @@},"dialect": "postgresql","enums": {},- "id": "b53caa01-9a61-4972-b254-fc9d88855dd5",+ "id": "15428217-3557-46ba-8f4f-431a23829ead","policies": {},- "prevId": "c5c00e30-513b-4e9c-a0b1-6b40e986f12b",+ "prevId": "2abb741e-cd71-49d5-baa4-0563f57e3a75","roles": {},"schemas": {},"sequences": {@@ -7162,6 +7162,388 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.agent_device_account_bindings": {+ "name": "agent_device_account_bindings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "device_id": {+ "name": "device_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_device_account_bindings_agent_device_unique": {+ "name": "agent_device_account_bindings_agent_device_unique",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_device_account_bindings_device_id_idx": {+ "name": "agent_device_account_bindings_device_id_idx",+ "columns": [+ {+ "expression": "device_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_device_account_bindings_account_device_idx": {+ "name": "agent_device_account_bindings_account_device_idx",+ "columns": [+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_device_account_bindings_user_id_idx": {+ "name": "agent_device_account_bindings_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_device_account_bindings_workspace_id_idx": {+ "name": "agent_device_account_bindings_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_device_account_bindings_agent_id_agents_id_fk": {+ "name": "agent_device_account_bindings_agent_id_agents_id_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_device_account_bindings_user_id_users_id_fk": {+ "name": "agent_device_account_bindings_user_id_users_id_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_device_account_bindings_workspace_id_workspaces_id_fk": {+ "name": "agent_device_account_bindings_workspace_id_workspaces_id_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_device_account_bindings_device_id_devices_id_fk": {+ "name": "agent_device_account_bindings_device_id_devices_id_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "devices",+ "columnsFrom": ["device_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_device_account_bindings_account_id_agent_provider_accounts_id_fk": {+ "name": "agent_device_account_bindings_account_id_agent_provider_accounts_id_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "agent_provider_accounts",+ "columnsFrom": ["account_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_device_account_bindings_login_fk": {+ "name": "agent_device_account_bindings_login_fk",+ "tableFrom": "agent_device_account_bindings",+ "tableTo": "agent_provider_account_logins",+ "columnsFrom": ["account_id", "device_id"],+ "columnsTo": ["account_id", "device_id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_provider_account_logins": {+ "name": "agent_provider_account_logins",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "account_id": {+ "name": "account_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "device_id": {+ "name": "device_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_provider_account_logins_device_id_idx": {+ "name": "agent_provider_account_logins_device_id_idx",+ "columns": [+ {+ "expression": "device_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_provider_account_logins_user_id_idx": {+ "name": "agent_provider_account_logins_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_provider_account_logins_workspace_id_idx": {+ "name": "agent_provider_account_logins_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_provider_account_logins_account_id_agent_provider_accounts_id_fk": {+ "name": "agent_provider_account_logins_account_id_agent_provider_accounts_id_fk",+ "tableFrom": "agent_provider_account_logins",+ "tableTo": "agent_provider_accounts",+ "columnsFrom": ["account_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_provider_account_logins_device_id_devices_id_fk": {+ "name": "agent_provider_account_logins_device_id_devices_id_fk",+ "tableFrom": "agent_provider_account_logins",+ "tableTo": "devices",+ "columnsFrom": ["device_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_provider_account_logins_user_id_users_id_fk": {+ "name": "agent_provider_account_logins_user_id_users_id_fk",+ "tableFrom": "agent_provider_account_logins",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_provider_account_logins_workspace_id_workspaces_id_fk": {+ "name": "agent_provider_account_logins_workspace_id_workspaces_id_fk",+ "tableFrom": "agent_provider_account_logins",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_provider_account_logins_account_device_unique": {+ "name": "agent_provider_account_logins_account_device_unique",+ "nullsNotDistinct": false,+ "columns": ["account_id", "device_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.agent_provider_accounts": {"name": "agent_provider_accounts","schema": "",@@ -7185,6 +7567,13 @@"primaryKey": false,"notNull": false},+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'public'"+ },"provider": {"name": "provider","type": "text",@@ -7337,6 +7726,33 @@"method": "btree","with": {}},+ "agent_provider_accounts_workspace_visibility_idx": {+ "name": "agent_provider_accounts_workspace_visibility_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "visibility",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"agent_provider_accounts_token_expires_at_idx": {"name": "agent_provider_accounts_token_expires_at_idx","columns": [@@ -10343,13 +10759,6 @@"primaryKey": false,"notNull": true},- "delivery_key": {- "name": "delivery_key",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'initial'"- },"status": {"name": "status","type": "text",@@ -10491,12 +10900,6 @@"isExpression": false,"asc": true,"nulls": "last"- },- {- "expression": "delivery_key",- "isExpression": false,- "asc": true,- "nulls": "last"}],"isUnique": true,@@ -10992,12 +11395,12 @@"notNull": false,"default": "'{}'::jsonb"},- "active": {- "name": "active",- "type": "boolean",+ "status": {+ "name": "status",+ "type": "text","primaryKey": false,"notNull": true,- "default": true+ "default": "'active'"},"created_at": {"name": "created_at",@@ -11549,6 +11952,13 @@"notNull": true,"default": "'[]'::jsonb"},+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },"metadata": {"name": "metadata","type": "jsonb",@@ -11679,6 +12089,13 @@"notNull": true,"default": 0},+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },"visibility": {"name": "visibility","type": "text",@@ -14085,6 +14502,24 @@"primaryKey": false,"notNull": true},+ "editor_ids": {+ "name": "editor_ids",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "operation_id": {+ "name": "operation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },"saved_at": {"name": "saved_at","type": "timestamp with time zone",@@ -17145,6 +17580,208 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.user_favorites": {+ "name": "user_favorites",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_favorites_personal_target_unique": {+ "name": "user_favorites_personal_target_unique",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_favorites\".\"workspace_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_favorites_workspace_target_unique": {+ "name": "user_favorites_workspace_target_unique",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_favorites\".\"workspace_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_favorites_user_id_idx": {+ "name": "user_favorites_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_favorites_workspace_id_idx": {+ "name": "user_favorites_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_favorites_user_id_users_id_fk": {+ "name": "user_favorites_user_id_users_id_fk",+ "tableFrom": "user_favorites",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_favorites_workspace_id_workspaces_id_fk": {+ "name": "user_favorites_workspace_id_workspaces_id_fk",+ "tableFrom": "user_favorites",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.documents": {"name": "documents","schema": "",@@ -18592,6 +19229,164 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.file_shares": {+ "name": "file_shares",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "file_id": {+ "name": "file_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "page_view_count": {+ "name": "page_view_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "file_shares_file_id_unique": {+ "name": "file_shares_file_id_unique",+ "columns": [+ {+ "expression": "file_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "file_shares_user_id_idx": {+ "name": "file_shares_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "file_shares_workspace_id_idx": {+ "name": "file_shares_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "file_shares_file_id_files_id_fk": {+ "name": "file_shares_file_id_files_id_fk",+ "tableFrom": "file_shares",+ "tableTo": "files",+ "columnsFrom": ["file_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "file_shares_user_id_users_id_fk": {+ "name": "file_shares_user_id_users_id_fk",+ "tableFrom": "file_shares",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "file_shares_workspace_id_workspaces_id_fk": {+ "name": "file_shares_workspace_id_workspaces_id_fk",+ "tableFrom": "file_shares",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.fts_search_sync_capture_version": {"name": "fts_search_sync_capture_version","schema": "",@@ -19440,6 +20235,13 @@"primaryKey": false,"notNull": false},+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'public'"+ },"deleted_at": {"name": "deleted_at","type": "timestamp with time zone",@@ -19498,6 +20300,33 @@"method": "btree","with": {}},+ "goals_workspace_visibility_idx": {+ "name": "goals_workspace_visibility_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "visibility",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"goals_agent_id_idx": {"name": "goals_agent_id_idx","columns": [@@ -20492,6 +21321,164 @@},"isRLSEnabled": false},+ "public.goal_shares": {+ "name": "goal_shares",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "goal_id": {+ "name": "goal_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "page_view_count": {+ "name": "page_view_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "goal_shares_goal_id_unique": {+ "name": "goal_shares_goal_id_unique",+ "columns": [+ {+ "expression": "goal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "goal_shares_user_id_idx": {+ "name": "goal_shares_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "goal_shares_workspace_id_idx": {+ "name": "goal_shares_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "goal_shares_goal_id_goals_id_fk": {+ "name": "goal_shares_goal_id_goals_id_fk",+ "tableFrom": "goal_shares",+ "tableTo": "goals",+ "columnsFrom": ["goal_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "goal_shares_user_id_users_id_fk": {+ "name": "goal_shares_user_id_users_id_fk",+ "tableFrom": "goal_shares",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "goal_shares_workspace_id_workspaces_id_fk": {+ "name": "goal_shares_workspace_id_workspaces_id_fk",+ "tableFrom": "goal_shares",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.goal_subscriptions": {"name": "goal_subscriptions","schema": "",@@ -21232,6 +22219,211 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.linear_sync_rules": {+ "name": "linear_sync_rules",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "team_name": {+ "name": "team_name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "linear_project_id": {+ "name": "linear_project_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "linear_project_name": {+ "name": "linear_project_name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "state_types": {+ "name": "state_types",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "last_run_at": {+ "name": "last_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_result": {+ "name": "last_result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "linear_sync_rules_project_id_idx": {+ "name": "linear_sync_rules_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "linear_sync_rules_connection_id_idx": {+ "name": "linear_sync_rules_connection_id_idx",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "linear_sync_rules_user_id_idx": {+ "name": "linear_sync_rules_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "linear_sync_rules_workspace_id_idx": {+ "name": "linear_sync_rules_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "linear_sync_rules_project_id_projects_id_fk": {+ "name": "linear_sync_rules_project_id_projects_id_fk",+ "tableFrom": "linear_sync_rules",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "linear_sync_rules_connection_id_linear_connections_id_fk": {+ "name": "linear_sync_rules_connection_id_linear_connections_id_fk",+ "tableFrom": "linear_sync_rules",+ "tableTo": "linear_connections",+ "columnsFrom": ["connection_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "linear_sync_rules_user_id_users_id_fk": {+ "name": "linear_sync_rules_user_id_users_id_fk",+ "tableFrom": "linear_sync_rules",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "linear_sync_rules_workspace_id_workspaces_id_fk": {+ "name": "linear_sync_rules_workspace_id_workspaces_id_fk",+ "tableFrom": "linear_sync_rules",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.llm_generation_tracing": {"name": "llm_generation_tracing","schema": "",@@ -35360,6 +36552,257 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.task_external_links": {+ "name": "task_external_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "external_identifier": {+ "name": "external_identifier",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_container_id": {+ "name": "external_container_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "external_updated_at": {+ "name": "external_updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "synced_hash": {+ "name": "synced_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_synced_at": {+ "name": "last_synced_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_external_links_task_id_unique": {+ "name": "task_external_links_task_id_unique",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_external_links_personal_unique": {+ "name": "task_external_links_personal_unique",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"task_external_links\".\"workspace_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_external_links_workspace_unique": {+ "name": "task_external_links_workspace_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"task_external_links\".\"workspace_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_external_links_container_idx": {+ "name": "task_external_links_container_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_container_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_external_links_user_id_idx": {+ "name": "task_external_links_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_external_links_task_id_tasks_id_fk": {+ "name": "task_external_links_task_id_tasks_id_fk",+ "tableFrom": "task_external_links",+ "tableTo": "tasks",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "task_external_links_user_id_users_id_fk": {+ "name": "task_external_links_user_id_users_id_fk",+ "tableFrom": "task_external_links",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "task_external_links_workspace_id_workspaces_id_fk": {+ "name": "task_external_links_workspace_id_workspaces_id_fk",+ "tableFrom": "task_external_links",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.threads": {"name": "threads","schema": "",@@ -36539,6 +37982,305 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.topic_analyses": {+ "name": "topic_analyses",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "topic_id": {+ "name": "topic_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "taxonomy_version": {+ "name": "taxonomy_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "category": {+ "name": "category",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secondary_category": {+ "name": "secondary_category",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "labels": {+ "name": "labels",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "topic_model": {+ "name": "topic_model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "topic_provider": {+ "name": "topic_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "total_tokens": {+ "name": "total_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "total_input_tokens": {+ "name": "total_input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "total_output_tokens": {+ "name": "total_output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "total_cost": {+ "name": "total_cost",+ "type": "numeric(20, 6)",+ "primaryKey": false,+ "notNull": false+ },+ "llm_calls": {+ "name": "llm_calls",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "tool_calls": {+ "name": "tool_calls",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_messages": {+ "name": "user_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "assistant_messages": {+ "name": "assistant_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_message_id": {+ "name": "last_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_message_updated_at": {+ "name": "last_message_updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "topic_analyses_topic_version_unique": {+ "name": "topic_analyses_topic_version_unique",+ "columns": [+ {+ "expression": "topic_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "taxonomy_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "topic_analyses_user_id_created_at_idx": {+ "name": "topic_analyses_user_id_created_at_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "topic_analyses_workspace_id_created_at_idx": {+ "name": "topic_analyses_workspace_id_created_at_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"topic_analyses\".\"workspace_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "topic_analyses_version_category_idx": {+ "name": "topic_analyses_version_category_idx",+ "columns": [+ {+ "expression": "taxonomy_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "category",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "topic_analyses_topic_id_topics_id_fk": {+ "name": "topic_analyses_topic_id_topics_id_fk",+ "tableFrom": "topic_analyses",+ "tableTo": "topics",+ "columnsFrom": ["topic_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "topic_analyses_user_id_users_id_fk": {+ "name": "topic_analyses_user_id_users_id_fk",+ "tableFrom": "topic_analyses",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "topic_analyses_workspace_id_workspaces_id_fk": {+ "name": "topic_analyses_workspace_id_workspaces_id_fk",+ "tableFrom": "topic_analyses",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.topic_comment_mentions": {"name": "topic_comment_mentions","schema": "",@@ -37656,8 +39398,8 @@"checkConstraints": {},"isRLSEnabled": false},- "public.user_memories": {- "name": "user_memories",+ "public.user_memories_activities": {+ "name": "user_memories_activities","schema": "","columns": {"id": {@@ -37672,84 +39414,115 @@"primaryKey": false,"notNull": false},- "memory_category": {- "name": "memory_category",+ "user_memory_id": {+ "name": "user_memory_id","type": "varchar(255)","primaryKey": false,"notNull": false},- "memory_layer": {- "name": "memory_layer",- "type": "varchar(255)",+ "metadata": {+ "name": "metadata",+ "type": "jsonb","primaryKey": false,"notNull": false},- "memory_type": {- "name": "memory_type",+ "tags": {+ "name": "tags",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "timezone": {+ "name": "timezone","type": "varchar(255)","primaryKey": false,"notNull": false},- "metadata": {- "name": "metadata",+ "starts_at": {+ "name": "starts_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "associated_objects": {+ "name": "associated_objects","type": "jsonb","primaryKey": false,"notNull": false},- "tags": {- "name": "tags",- "type": "text[]",+ "associated_subjects": {+ "name": "associated_subjects",+ "type": "jsonb","primaryKey": false,"notNull": false},- "title": {- "name": "title",- "type": "varchar(255)",+ "associated_locations": {+ "name": "associated_locations",+ "type": "jsonb","primaryKey": false,"notNull": false},- "summary": {- "name": "summary",+ "notes": {+ "name": "notes","type": "text","primaryKey": false,"notNull": false},- "summary_vector_1024": {- "name": "summary_vector_1024",+ "narrative": {+ "name": "narrative",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "narrative_vector": {+ "name": "narrative_vector","type": "vector(1024)","primaryKey": false,"notNull": false},- "details": {- "name": "details",+ "feedback": {+ "name": "feedback","type": "text","primaryKey": false,"notNull": false},- "details_vector_1024": {- "name": "details_vector_1024",+ "feedback_vector": {+ "name": "feedback_vector","type": "vector(1024)","primaryKey": false,"notNull": false},- "status": {- "name": "status",+ "dossier_id": {+ "name": "dossier_id","type": "varchar(255)","primaryKey": false,"notNull": false},- "accessed_count": {- "name": "accessed_count",- "type": "bigint",- "primaryKey": false,- "notNull": false,- "default": 0- },- "last_accessed_at": {- "name": "last_accessed_at",- "type": "timestamp with time zone",+ "injectable": {+ "name": "injectable",+ "type": "boolean","primaryKey": false,- "notNull": true+ "notNull": true,+ "default": true},"captured_at": {"name": "captured_at",@@ -37758,18 +39531,6 @@"notNull": true,"default": "now()"},- "deleted_at": {- "name": "deleted_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "is_deleted": {- "name": "is_deleted",- "type": "boolean",- "primaryKey": false,- "notNull": false- },"accessed_at": {"name": "accessed_at","type": "timestamp with time zone",@@ -37793,11 +39554,11 @@}},"indexes": {- "user_memories_summary_vector_1024_index": {- "name": "user_memories_summary_vector_1024_index",+ "user_memories_activities_narrative_vector_index": {+ "name": "user_memories_activities_narrative_vector_index","columns": [{- "expression": "summary_vector_1024",+ "expression": "narrative_vector","isExpression": false,"asc": true,"nulls": "last",@@ -37809,11 +39570,11 @@"method": "hnsw","with": {}},- "user_memories_details_vector_1024_index": {- "name": "user_memories_details_vector_1024_index",+ "user_memories_activities_feedback_vector_index": {+ "name": "user_memories_activities_feedback_vector_index","columns": [{- "expression": "details_vector_1024",+ "expression": "feedback_vector","isExpression": false,"asc": true,"nulls": "last",@@ -37825,8 +39586,23 @@"method": "hnsw","with": {}},- "user_memories_user_id_index": {- "name": "user_memories_user_id_index",+ "user_memories_activities_type_index": {+ "name": "user_memories_activities_type_index",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_activities_user_id_index": {+ "name": "user_memories_activities_user_id_index","columns": [{"expression": "user_id",@@ -37839,17 +39615,81 @@"concurrently": false,"method": "btree","with": {}+ },+ "user_memories_activities_user_memory_id_index": {+ "name": "user_memories_activities_user_memory_id_index",+ "columns": [+ {+ "expression": "user_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_activities_status_index": {+ "name": "user_memories_activities_status_index",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_activities_dossier_id_index": {+ "name": "user_memories_activities_dossier_id_index",+ "columns": [+ {+ "expression": "dossier_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"user_memories_activities\".\"dossier_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {- "user_memories_user_id_users_id_fk": {- "name": "user_memories_user_id_users_id_fk",- "tableFrom": "user_memories",+ "user_memories_activities_user_id_users_id_fk": {+ "name": "user_memories_activities_user_id_users_id_fk",+ "tableFrom": "user_memories_activities","tableTo": "users","columnsFrom": ["user_id"],"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"+ },+ "user_memories_activities_user_memory_id_user_memories_id_fk": {+ "name": "user_memories_activities_user_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_activities",+ "tableTo": "user_memories",+ "columnsFrom": ["user_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_activities_dossier_id_user_memories_dossiers_id_fk": {+ "name": "user_memories_activities_dossier_id_user_memories_dossiers_id_fk",+ "tableFrom": "user_memories_activities",+ "tableTo": "user_memories_dossiers",+ "columnsFrom": ["dossier_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -37858,8 +39698,8 @@"checkConstraints": {},"isRLSEnabled": false},- "public.user_memories_activities": {- "name": "user_memories_activities",+ "public.user_memories": {+ "name": "user_memories","schema": "","columns": {"id": {@@ -37874,8 +39714,20 @@"primaryKey": false,"notNull": false},- "user_memory_id": {- "name": "user_memory_id",+ "memory_category": {+ "name": "memory_category",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "memory_layer": {+ "name": "memory_layer",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "memory_type": {+ "name": "memory_type","type": "varchar(255)","primaryKey": false,"notNull": false@@ -37892,84 +39744,67 @@"primaryKey": false,"notNull": false},- "type": {- "name": "type",- "type": "varchar(255)",- "primaryKey": false,- "notNull": true- },- "status": {- "name": "status",- "type": "varchar(255)",- "primaryKey": false,- "notNull": true,- "default": "'pending'"- },- "timezone": {- "name": "timezone",+ "title": {+ "name": "title","type": "varchar(255)","primaryKey": false,"notNull": false},- "starts_at": {- "name": "starts_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "ends_at": {- "name": "ends_at",- "type": "timestamp with time zone",+ "summary": {+ "name": "summary",+ "type": "text","primaryKey": false,"notNull": false},- "associated_objects": {- "name": "associated_objects",- "type": "jsonb",+ "summary_vector_1024": {+ "name": "summary_vector_1024",+ "type": "vector(1024)","primaryKey": false,"notNull": false},- "associated_subjects": {- "name": "associated_subjects",- "type": "jsonb",+ "details": {+ "name": "details",+ "type": "text","primaryKey": false,"notNull": false},- "associated_locations": {- "name": "associated_locations",- "type": "jsonb",+ "details_vector_1024": {+ "name": "details_vector_1024",+ "type": "vector(1024)","primaryKey": false,"notNull": false},- "notes": {- "name": "notes",- "type": "text",+ "status": {+ "name": "status",+ "type": "varchar(255)","primaryKey": false,"notNull": false},- "narrative": {- "name": "narrative",+ "state": {+ "name": "state","type": "text","primaryKey": false,"notNull": false},- "narrative_vector": {- "name": "narrative_vector",- "type": "vector(1024)",+ "user_locked": {+ "name": "user_locked",+ "type": "boolean","primaryKey": false,- "notNull": false+ "notNull": false,+ "default": false},- "feedback": {- "name": "feedback",- "type": "text",+ "accessed_count": {+ "name": "accessed_count",+ "type": "bigint","primaryKey": false,- "notNull": false+ "notNull": false,+ "default": 0},- "feedback_vector": {- "name": "feedback_vector",- "type": "vector(1024)",+ "last_accessed_at": {+ "name": "last_accessed_at",+ "type": "timestamp with time zone","primaryKey": false,- "notNull": false+ "notNull": true},"captured_at": {"name": "captured_at",@@ -37978,6 +39813,18 @@"notNull": true,"default": "now()"},+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "is_deleted": {+ "name": "is_deleted",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },"accessed_at": {"name": "accessed_at","type": "timestamp with time zone",@@ -38001,11 +39848,11 @@}},"indexes": {- "user_memories_activities_narrative_vector_index": {- "name": "user_memories_activities_narrative_vector_index",+ "user_memories_summary_vector_1024_index": {+ "name": "user_memories_summary_vector_1024_index","columns": [{- "expression": "narrative_vector",+ "expression": "summary_vector_1024","isExpression": false,"asc": true,"nulls": "last",@@ -38017,11 +39864,11 @@"method": "hnsw","with": {}},- "user_memories_activities_feedback_vector_index": {- "name": "user_memories_activities_feedback_vector_index",+ "user_memories_details_vector_1024_index": {+ "name": "user_memories_details_vector_1024_index","columns": [{- "expression": "feedback_vector",+ "expression": "details_vector_1024","isExpression": false,"asc": true,"nulls": "last",@@ -38033,11 +39880,11 @@"method": "hnsw","with": {}},- "user_memories_activities_type_index": {- "name": "user_memories_activities_type_index",+ "user_memories_user_id_index": {+ "name": "user_memories_user_id_index","columns": [{- "expression": "type",+ "expression": "user_id","isExpression": false,"asc": true,"nulls": "last"@@ -38047,27 +39894,129 @@"concurrently": false,"method": "btree","with": {}+ }+ },+ "foreignKeys": {+ "user_memories_user_id_users_id_fk": {+ "name": "user_memories_user_id_users_id_fk",+ "tableFrom": "user_memories",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_memories_context_projects": {+ "name": "user_memories_context_projects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"},- "user_memories_activities_user_id_index": {- "name": "user_memories_activities_user_id_index",+ "context_id": {+ "name": "context_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "evidence_count": {+ "name": "evidence_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "is_primary": {+ "name": "is_primary",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_context_projects_context_id_project_id_unique": {+ "name": "user_memories_context_projects_context_id_project_id_unique","columns": [{- "expression": "user_id",+ "expression": "context_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id","isExpression": false,"asc": true,"nulls": "last"}],- "isUnique": false,+ "isUnique": true,"concurrently": false,"method": "btree","with": {}},- "user_memories_activities_user_memory_id_index": {- "name": "user_memories_activities_user_memory_id_index",+ "user_memories_context_projects_project_id_index": {+ "name": "user_memories_context_projects_project_id_index","columns": [{- "expression": "user_memory_id",+ "expression": "project_id","isExpression": false,"asc": true,"nulls": "last"@@ -38078,11 +40027,11 @@"method": "btree","with": {}},- "user_memories_activities_status_index": {- "name": "user_memories_activities_status_index",+ "user_memories_context_projects_user_id_index": {+ "name": "user_memories_context_projects_user_id_index","columns": [{- "expression": "status",+ "expression": "user_id","isExpression": false,"asc": true,"nulls": "last"@@ -38095,20 +40044,29 @@}},"foreignKeys": {- "user_memories_activities_user_id_users_id_fk": {- "name": "user_memories_activities_user_id_users_id_fk",- "tableFrom": "user_memories_activities",- "tableTo": "users",- "columnsFrom": ["user_id"],+ "user_memories_context_projects_context_id_user_memories_contexts_id_fk": {+ "name": "user_memories_context_projects_context_id_user_memories_contexts_id_fk",+ "tableFrom": "user_memories_context_projects",+ "tableTo": "user_memories_contexts",+ "columnsFrom": ["context_id"],"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},- "user_memories_activities_user_memory_id_user_memories_id_fk": {- "name": "user_memories_activities_user_memory_id_user_memories_id_fk",- "tableFrom": "user_memories_activities",- "tableTo": "user_memories",- "columnsFrom": ["user_memory_id"],+ "user_memories_context_projects_project_id_projects_id_fk": {+ "name": "user_memories_context_projects_project_id_projects_id_fk",+ "tableFrom": "user_memories_context_projects",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_context_projects_user_id_users_id_fk": {+ "name": "user_memories_context_projects_user_id_users_id_fk",+ "tableFrom": "user_memories_context_projects",+ "tableTo": "users",+ "columnsFrom": ["user_id"],"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"@@ -38136,6 +40094,12 @@"primaryKey": false,"notNull": false},+ "user_memory_id": {+ "name": "user_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },"user_memory_ids": {"name": "user_memory_ids","type": "jsonb",@@ -38210,6 +40174,42 @@"notNull": false,"default": 0},+ "now": {+ "name": "now",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_steps": {+ "name": "next_steps",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "open_questions": {+ "name": "open_questions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_evidence_at": {+ "name": "last_evidence_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "synthesized_at": {+ "name": "synthesized_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },"captured_at": {"name": "captured_at","type": "timestamp with time zone",@@ -38300,16 +40300,1112 @@"concurrently": false,"method": "gin","with": {}- }- },- "foreignKeys": {- "user_memories_contexts_user_id_users_id_fk": {- "name": "user_memories_contexts_user_id_users_id_fk",- "tableFrom": "user_memories_contexts",- "tableTo": "users",- "columnsFrom": ["user_id"],- "columnsTo": ["id"],- "onDelete": "cascade",+ },+ "user_memories_contexts_user_memory_id_index": {+ "name": "user_memories_contexts_user_memory_id_index",+ "columns": [+ {+ "expression": "user_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_contexts_user_id_last_evidence_at_index": {+ "name": "user_memories_contexts_user_id_last_evidence_at_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "last_evidence_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_contexts_user_id_users_id_fk": {+ "name": "user_memories_contexts_user_id_users_id_fk",+ "tableFrom": "user_memories_contexts",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_contexts_user_memory_id_user_memories_id_fk": {+ "name": "user_memories_contexts_user_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_contexts",+ "tableTo": "user_memories",+ "columnsFrom": ["user_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_memories_dossiers": {+ "name": "user_memories_dossiers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(255)",+ "primaryKey": true,+ "notNull": true+ },+ "context_id": {+ "name": "context_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_memory_id": {+ "name": "user_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary_vector": {+ "name": "summary_vector",+ "type": "vector(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "now": {+ "name": "now",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decisions": {+ "name": "decisions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_evidence_at": {+ "name": "last_evidence_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "activity_count": {+ "name": "activity_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_dossiers_summary_vector_index": {+ "name": "user_memories_dossiers_summary_vector_index",+ "columns": [+ {+ "expression": "summary_vector",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "vector_cosine_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "hnsw",+ "with": {}+ },+ "user_memories_dossiers_context_id_index": {+ "name": "user_memories_dossiers_context_id_index",+ "columns": [+ {+ "expression": "context_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_dossiers_user_id_last_evidence_at_index": {+ "name": "user_memories_dossiers_user_id_last_evidence_at_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "last_evidence_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_dossiers_user_memory_id_index": {+ "name": "user_memories_dossiers_user_memory_id_index",+ "columns": [+ {+ "expression": "user_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_dossiers_workspace_visibility_idx": {+ "name": "user_memories_dossiers_workspace_visibility_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "visibility",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_dossiers_agent_id_index": {+ "name": "user_memories_dossiers_agent_id_index",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_dossiers_project_id_index": {+ "name": "user_memories_dossiers_project_id_index",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_dossiers_context_id_user_memories_contexts_id_fk": {+ "name": "user_memories_dossiers_context_id_user_memories_contexts_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "user_memories_contexts",+ "columnsFrom": ["context_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "user_memories_dossiers_user_id_users_id_fk": {+ "name": "user_memories_dossiers_user_id_users_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_dossiers_workspace_id_workspaces_id_fk": {+ "name": "user_memories_dossiers_workspace_id_workspaces_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_dossiers_agent_id_agents_id_fk": {+ "name": "user_memories_dossiers_agent_id_agents_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_dossiers_project_id_projects_id_fk": {+ "name": "user_memories_dossiers_project_id_projects_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_dossiers_user_memory_id_user_memories_id_fk": {+ "name": "user_memories_dossiers_user_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_dossiers",+ "tableTo": "user_memories",+ "columnsFrom": ["user_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_memories_edges": {+ "name": "user_memories_edges",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "source_memory_id": {+ "name": "source_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "target_memory_id": {+ "name": "target_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "relation": {+ "name": "relation",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "evidence_count": {+ "name": "evidence_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_edges_source_target_relation_unique": {+ "name": "user_memories_edges_source_target_relation_unique",+ "columns": [+ {+ "expression": "source_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "relation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_edges_target_memory_id_relation_index": {+ "name": "user_memories_edges_target_memory_id_relation_index",+ "columns": [+ {+ "expression": "target_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "relation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_edges_user_id_relation_index": {+ "name": "user_memories_edges_user_id_relation_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "relation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_edges_workspace_id_relation_index": {+ "name": "user_memories_edges_workspace_id_relation_index",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "relation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_edges_source_memory_id_user_memories_id_fk": {+ "name": "user_memories_edges_source_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_edges",+ "tableTo": "user_memories",+ "columnsFrom": ["source_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_edges_target_memory_id_user_memories_id_fk": {+ "name": "user_memories_edges_target_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_edges",+ "tableTo": "user_memories",+ "columnsFrom": ["target_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_edges_user_id_users_id_fk": {+ "name": "user_memories_edges_user_id_users_id_fk",+ "tableFrom": "user_memories_edges",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_edges_workspace_id_workspaces_id_fk": {+ "name": "user_memories_edges_workspace_id_workspaces_id_fk",+ "tableFrom": "user_memories_edges",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_memories_entities": {+ "name": "user_memories_entities",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(255)",+ "primaryKey": true,+ "notNull": true+ },+ "parent_entity_id": {+ "name": "parent_entity_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_memory_id": {+ "name": "user_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'other'"+ },+ "relationship": {+ "name": "relationship",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description_vector": {+ "name": "description_vector",+ "type": "vector(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "is_self": {+ "name": "is_self",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_entities_description_vector_index": {+ "name": "user_memories_entities_description_vector_index",+ "columns": [+ {+ "expression": "description_vector",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "vector_cosine_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "hnsw",+ "with": {}+ },+ "user_memories_entities_user_id_index": {+ "name": "user_memories_entities_user_id_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_parent_entity_id_index": {+ "name": "user_memories_entities_parent_entity_id_index",+ "columns": [+ {+ "expression": "parent_entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_user_memory_id_index": {+ "name": "user_memories_entities_user_memory_id_index",+ "columns": [+ {+ "expression": "user_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_user_id_self_unique": {+ "name": "user_memories_entities_user_id_self_unique",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_memories_entities\".\"is_self\"",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_workspace_visibility_idx": {+ "name": "user_memories_entities_workspace_visibility_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "visibility",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_agent_id_index": {+ "name": "user_memories_entities_agent_id_index",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entities_project_id_index": {+ "name": "user_memories_entities_project_id_index",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_entities_parent_entity_id_user_memories_entities_id_fk": {+ "name": "user_memories_entities_parent_entity_id_user_memories_entities_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "user_memories_entities",+ "columnsFrom": ["parent_entity_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "user_memories_entities_user_id_users_id_fk": {+ "name": "user_memories_entities_user_id_users_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entities_workspace_id_workspaces_id_fk": {+ "name": "user_memories_entities_workspace_id_workspaces_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entities_agent_id_agents_id_fk": {+ "name": "user_memories_entities_agent_id_agents_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "agents",+ "columnsFrom": ["agent_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entities_project_id_projects_id_fk": {+ "name": "user_memories_entities_project_id_projects_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "projects",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entities_user_memory_id_user_memories_id_fk": {+ "name": "user_memories_entities_user_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_entities",+ "tableTo": "user_memories",+ "columnsFrom": ["user_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_memories_entity_names": {+ "name": "user_memories_entity_names",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "entity_id": {+ "name": "entity_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "normalized": {+ "name": "normalized",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'alias'"+ },+ "source_memory_id": {+ "name": "source_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_entity_names_entity_id_normalized_unique": {+ "name": "user_memories_entity_names_entity_id_normalized_unique",+ "columns": [+ {+ "expression": "entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entity_names_user_id_normalized_index": {+ "name": "user_memories_entity_names_user_id_normalized_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_entity_names_workspace_id_normalized_index": {+ "name": "user_memories_entity_names_workspace_id_normalized_index",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_entity_names_entity_id_user_memories_entities_id_fk": {+ "name": "user_memories_entity_names_entity_id_user_memories_entities_id_fk",+ "tableFrom": "user_memories_entity_names",+ "tableTo": "user_memories_entities",+ "columnsFrom": ["entity_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entity_names_user_id_users_id_fk": {+ "name": "user_memories_entity_names_user_id_users_id_fk",+ "tableFrom": "user_memories_entity_names",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entity_names_workspace_id_workspaces_id_fk": {+ "name": "user_memories_entity_names_workspace_id_workspaces_id_fk",+ "tableFrom": "user_memories_entity_names",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_entity_names_source_memory_id_user_memories_id_fk": {+ "name": "user_memories_entity_names_source_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_entity_names",+ "tableTo": "user_memories",+ "columnsFrom": ["source_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "set null","onUpdate": "no action"}},@@ -38634,6 +41730,12 @@"primaryKey": false,"notNull": false},+ "entity_id": {+ "name": "entity_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },"captured_at": {"name": "captured_at","type": "timestamp with time zone",@@ -38724,6 +41826,21 @@"concurrently": false,"method": "btree","with": {}+ },+ "user_memories_identities_entity_id_index": {+ "name": "user_memories_identities_entity_id_index",+ "columns": [+ {+ "expression": "entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {@@ -38744,6 +41861,15 @@"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"+ },+ "user_memories_identities_entity_id_user_memories_entities_id_fk": {+ "name": "user_memories_identities_entity_id_user_memories_entities_id_fk",+ "tableFrom": "user_memories_identities",+ "tableTo": "user_memories_entities",+ "columnsFrom": ["entity_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -38752,8 +41878,8 @@"checkConstraints": {},"isRLSEnabled": false},- "public.user_memories_preferences": {- "name": "user_memories_preferences",+ "public.user_memories_operations": {+ "name": "user_memories_operations","schema": "","columns": {"id": {@@ -38768,9 +41894,9 @@"primaryKey": false,"notNull": false},- "user_memory_id": {- "name": "user_memory_id",- "type": "varchar(255)",+ "workspace_id": {+ "name": "workspace_id",+ "type": "text","primaryKey": false,"notNull": false},@@ -38780,49 +41906,65 @@"primaryKey": false,"notNull": false},- "tags": {- "name": "tags",- "type": "text[]",+ "op": {+ "name": "op",+ "type": "text","primaryKey": false,- "notNull": false+ "notNull": true},- "conclusion_directives": {- "name": "conclusion_directives",+ "actor": {+ "name": "actor","type": "text","primaryKey": false,+ "notNull": true+ },+ "targets": {+ "name": "targets",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "before": {+ "name": "before",+ "type": "jsonb",+ "primaryKey": false,"notNull": false},- "conclusion_directives_vector": {- "name": "conclusion_directives_vector",- "type": "vector(1024)",+ "after": {+ "name": "after",+ "type": "jsonb","primaryKey": false,"notNull": false},- "type": {- "name": "type",- "type": "varchar(255)",+ "confidence": {+ "name": "confidence",+ "type": "real","primaryKey": false,"notNull": false},- "suggestions": {- "name": "suggestions",+ "reason": {+ "name": "reason","type": "text","primaryKey": false,"notNull": false},- "score_priority": {- "name": "score_priority",- "type": "numeric",+ "gate": {+ "name": "gate",+ "type": "text","primaryKey": false,- "notNull": false,- "default": 0+ "notNull": true},- "captured_at": {- "name": "captured_at",+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resolved_at": {+ "name": "resolved_at","type": "timestamp with time zone","primaryKey": false,- "notNull": true,- "default": "now()"+ "notNull": false},"accessed_at": {"name": "accessed_at",@@ -38847,27 +41989,23 @@}},"indexes": {- "user_memories_preferences_conclusion_directives_vector_index": {- "name": "user_memories_preferences_conclusion_directives_vector_index",+ "user_memories_operations_user_id_state_created_at_index": {+ "name": "user_memories_operations_user_id_state_created_at_index","columns": [{- "expression": "conclusion_directives_vector",+ "expression": "user_id","isExpression": false,"asc": true,- "nulls": "last",- "opclass": "vector_cosine_ops"- }- ],- "isUnique": false,- "concurrently": false,- "method": "hnsw",- "with": {}- },- "user_memories_preferences_user_id_index": {- "name": "user_memories_preferences_user_id_index",- "columns": [+ "nulls": "last"+ },{- "expression": "user_id",+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at","isExpression": false,"asc": true,"nulls": "last"@@ -38878,11 +42016,23 @@"method": "btree","with": {}},- "user_memories_preferences_user_memory_id_index": {- "name": "user_memories_preferences_user_memory_id_index",+ "user_memories_operations_workspace_id_state_created_at_index": {+ "name": "user_memories_operations_workspace_id_state_created_at_index","columns": [{- "expression": "user_memory_id",+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at","isExpression": false,"asc": true,"nulls": "last"@@ -38895,20 +42045,20 @@}},"foreignKeys": {- "user_memories_preferences_user_id_users_id_fk": {- "name": "user_memories_preferences_user_id_users_id_fk",- "tableFrom": "user_memories_preferences",+ "user_memories_operations_user_id_users_id_fk": {+ "name": "user_memories_operations_user_id_users_id_fk",+ "tableFrom": "user_memories_operations","tableTo": "users","columnsFrom": ["user_id"],"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},- "user_memories_preferences_user_memory_id_user_memories_id_fk": {- "name": "user_memories_preferences_user_memory_id_user_memories_id_fk",- "tableFrom": "user_memories_preferences",- "tableTo": "user_memories",- "columnsFrom": ["user_memory_id"],+ "user_memories_operations_workspace_id_workspaces_id_fk": {+ "name": "user_memories_operations_workspace_id_workspaces_id_fk",+ "tableFrom": "user_memories_operations",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],"columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"@@ -39274,6 +42424,259 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.user_memories_preferences": {+ "name": "user_memories_preferences",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(255)",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_memory_id": {+ "name": "user_memory_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "tags": {+ "name": "tags",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "conclusion_directives": {+ "name": "conclusion_directives",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "conclusion_directives_vector": {+ "name": "conclusion_directives_vector",+ "type": "vector(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "suggestions": {+ "name": "suggestions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "score_priority": {+ "name": "score_priority",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "holder_entity_id": {+ "name": "holder_entity_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "applies_to_entity_id": {+ "name": "applies_to_entity_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "evidence_source": {+ "name": "evidence_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "evidence_count": {+ "name": "evidence_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "last_evidence_at": {+ "name": "last_evidence_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "accessed_at": {+ "name": "accessed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_memories_preferences_conclusion_directives_vector_index": {+ "name": "user_memories_preferences_conclusion_directives_vector_index",+ "columns": [+ {+ "expression": "conclusion_directives_vector",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "vector_cosine_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "hnsw",+ "with": {}+ },+ "user_memories_preferences_user_id_index": {+ "name": "user_memories_preferences_user_id_index",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_preferences_user_memory_id_index": {+ "name": "user_memories_preferences_user_memory_id_index",+ "columns": [+ {+ "expression": "user_memory_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_preferences_holder_entity_id_index": {+ "name": "user_memories_preferences_holder_entity_id_index",+ "columns": [+ {+ "expression": "holder_entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_memories_preferences_applies_to_entity_id_index": {+ "name": "user_memories_preferences_applies_to_entity_id_index",+ "columns": [+ {+ "expression": "applies_to_entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_memories_preferences_user_id_users_id_fk": {+ "name": "user_memories_preferences_user_id_users_id_fk",+ "tableFrom": "user_memories_preferences",+ "tableTo": "users",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_preferences_user_memory_id_user_memories_id_fk": {+ "name": "user_memories_preferences_user_memory_id_user_memories_id_fk",+ "tableFrom": "user_memories_preferences",+ "tableTo": "user_memories",+ "columnsFrom": ["user_memory_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_memories_preferences_holder_entity_id_user_memories_entities_id_fk": {+ "name": "user_memories_preferences_holder_entity_id_user_memories_entities_id_fk",+ "tableFrom": "user_memories_preferences",+ "tableTo": "user_memories_entities",+ "columnsFrom": ["holder_entity_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "user_memories_preferences_applies_to_entity_id_user_memories_entities_id_fk": {+ "name": "user_memories_preferences_applies_to_entity_id_user_memories_entities_id_fk",+ "tableFrom": "user_memories_preferences",+ "tableTo": "user_memories_entities",+ "columnsFrom": ["applies_to_entity_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.acceptances": {"name": "acceptances","schema": "",diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.jsonindex f21b8a8bea9..30be8c27930 100644--- a/packages/database/migrations/meta/_journal.json+++ b/packages/database/migrations/meta/_journal.json@@ -1393,6 +1393,13 @@"when": 1793450092790,"tag": "0198_goal_visibility","breakpoints": true+ },+ {+ "idx": 199,+ "version": "7",+ "when": 1793552841904,+ "tag": "0199_topic_analyses",+ "breakpoints": true}],"version": "6"diff --git a/packages/database/src/models/__tests__/topicAnalysis.test.ts b/packages/database/src/models/__tests__/topicAnalysis.test.tsnew file mode 100644index 00000000000..7b3856d091e--- /dev/null+++ b/packages/database/src/models/__tests__/topicAnalysis.test.ts@@ -0,0 +1,280 @@+// @vitest-environment node+import type { TopicAnalysisResult } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { messages, topicAnalyses, topics, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TopicAnalysisModel } from '../topicAnalysis';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-analysis-user';+const otherUserId = 'topic-analysis-user-2';+const workspaceId = 'topic-analysis-ws';+const topicId = 'tpc_analysis_1';+const workspaceTopicId = 'tpc_analysis_ws';++const personalModel = new TopicAnalysisModel(serverDB, userId);+const workspaceModel = new TopicAnalysisModel(serverDB, userId, workspaceId);++const result = (overrides: Partial<TopicAnalysisResult> = {}): TopicAnalysisResult => ({+ category: 'coding',+ intent: 'doing',+ labels: { collaboration: 'directive' },+ metadata: { promptVersion: 'p1' },+ model: 'model-a',+ outcome: 'success',+ provider: 'provider-a',+ taxonomyVersion: 'v1',+ ...overrides,+});++const T1 = new Date('2026-10-30T10:00:00Z');+const T2 = new Date('2026-10-30T11:00:00Z');+const snapshot = { lastMessageId: 'msg_1', lastMessageUpdatedAt: T1 };+const newerSnapshot = { lastMessageId: 'msg_2', lastMessageUpdatedAt: T2 };++/** A newer reply on the personal topic; msg_1 is seeded in beforeEach. */+const addNewerMessage = () =>+ serverDB+ .insert(messages)+ .values({ content: 'second', id: 'msg_2', role: 'assistant', topicId, updatedAt: T2, userId });++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.delete(workspaces);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values([{ id: workspaceId, name: 'Test WS', primaryOwnerId: userId, slug: 'analysis-ws' }]);+ await serverDB.insert(topics).values([+ { id: topicId, userId },+ { id: workspaceTopicId, userId, workspaceId },+ ]);+ await serverDB.insert(messages).values([+ { content: 'first', id: 'msg_1', role: 'user', topicId, updatedAt: T1, userId },+ {+ content: 'ws',+ id: 'msg_ws',+ role: 'user',+ topicId: workspaceTopicId,+ updatedAt: T1,+ userId,+ workspaceId,+ },+ ]);+});++afterEach(async () => {+ await serverDB.delete(messages);+ await serverDB.delete(topicAnalyses);+ await serverDB.delete(topics);+ await serverDB.delete(users);+ await serverDB.delete(workspaces);+});++describe('TopicAnalysisModel', () => {+ it('saves an analysis with its message snapshot', async () => {+ await personalModel.save({ ...snapshot, result: result(), topicId });++ const row = await personalModel.findByTopic(topicId, 'v1');+ expect(row).toMatchObject({+ category: 'coding',+ intent: 'doing',+ labels: { collaboration: 'directive' },+ lastMessageId: 'msg_1',+ metadata: { promptVersion: 'p1' },+ model: 'model-a',+ outcome: 'success',+ provider: 'provider-a',+ secondaryCategory: null,+ userId,+ workspaceId: null,+ });+ expect(row?.lastMessageUpdatedAt?.toISOString()).toBe('2026-10-30T10:00:00.000Z');+ });++ it('replaces the analysis for the same taxonomy version instead of duplicating it', async () => {+ await addNewerMessage();+ await personalModel.save({ ...snapshot, result: result(), topicId });+ await personalModel.save({+ ...newerSnapshot,+ result: result({ category: 'research', intent: 'asking', outcome: null }),+ topicId,+ });++ const rows = await serverDB.select().from(topicAnalyses);+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ category: 'research',+ intent: 'asking',+ lastMessageId: 'msg_2',+ outcome: null,+ });+ });++ it('rejects an overlapping run that analyzed an older snapshot', async () => {+ await addNewerMessage();+ await personalModel.save({+ ...newerSnapshot,+ result: result({ category: 'research' }),+ topicId,+ });++ const stale = await personalModel.save({ ...snapshot, result: result(), topicId });++ expect(stale).toBeUndefined();+ expect(await personalModel.findByTopic(topicId, 'v1')).toMatchObject({+ category: 'research',+ lastMessageId: 'msg_2',+ });+ });++ it('accepts a fresh analysis after the newest message was removed', async () => {+ await addNewerMessage();+ await personalModel.save({+ ...newerSnapshot,+ result: result({ category: 'research' }),+ topicId,+ });+ // The newest message goes to the recycle bin, so the latest remaining one is older.+ await serverDB.update(messages).set({ isDeleted: true }).where(eq(messages.id, 'msg_2'));++ const fresh = await personalModel.save({ ...snapshot, result: result(), topicId });++ expect(fresh).toBeDefined();+ expect(await personalModel.findByTopic(topicId, 'v1')).toMatchObject({+ category: 'coding',+ lastMessageId: 'msg_1',+ });+ });++ it('does not record a first analysis whose messages changed while it ran', async () => {+ await serverDB+ .update(messages)+ .set({ content: 'edited', updatedAt: T2 })+ .where(eq(messages.id, 'msg_1'));++ expect(await personalModel.save({ ...snapshot, result: result(), topicId })).toBeUndefined();+ expect(await serverDB.select().from(topicAnalyses)).toHaveLength(0);+ });++ it('does not record a first analysis whose messages were all removed', async () => {+ await serverDB.update(messages).set({ isDeleted: true }).where(eq(messages.id, 'msg_1'));++ expect(await personalModel.save({ ...snapshot, result: result(), topicId })).toBeUndefined();+ expect(await serverDB.select().from(topicAnalyses)).toHaveLength(0);+ });++ it('keeps one row per taxonomy version', async () => {+ await personalModel.save({ ...snapshot, result: result(), topicId });+ await personalModel.save({ ...snapshot, result: result({ taxonomyVersion: 'v2' }), topicId });++ expect(await serverDB.select().from(topicAnalyses)).toHaveLength(2);+ expect((await personalModel.findByTopic(topicId, 'v2'))?.taxonomyVersion).toBe('v2');+ });++ it('scopes reads to the owner and workspace', async () => {+ await workspaceModel.save({+ lastMessageId: 'msg_ws',+ lastMessageUpdatedAt: T1,+ result: result(),+ topicId: workspaceTopicId,+ });++ expect((await workspaceModel.findByTopic(workspaceTopicId, 'v1'))?.workspaceId).toBe(+ workspaceId,+ );+ expect(await personalModel.findByTopic(workspaceTopicId, 'v1')).toBeUndefined();+ expect(+ await new TopicAnalysisModel(serverDB, otherUserId, workspaceId).findByTopic(+ workspaceTopicId,+ 'v1',+ ),+ ).toBeUndefined();+ });++ it('is removed together with its topic', async () => {+ await personalModel.save({ ...snapshot, result: result(), topicId });+ await serverDB.delete(topics);++ expect(await serverDB.select().from(topicAnalyses)).toHaveLength(0);+ });++ describe('topic usage snapshot', () => {+ beforeEach(async () => {+ // Count only the messages each case inserts.+ await serverDB.delete(messages);+ });++ it('reads the topic totals and counts live messages by role', async () => {+ await serverDB+ .update(topics)+ .set({+ model: 'gpt-x',+ provider: 'openai',+ totalCost: 0.0123,+ totalInputTokens: 900,+ totalOutputTokens: 100,+ totalTokens: 1000,+ usage: { llm: { apiCalls: 3 } },+ })+ .where(eq(topics.id, topicId));+ await serverDB.insert(messages).values([+ { content: 'q1', role: 'user', topicId, userId },+ { content: 'a1', role: 'assistant', topicId, userId },+ { content: 'run', role: 'tool', topicId, userId },+ { content: 'run', role: 'tool', topicId, userId },+ { content: 'q2', role: 'user', topicId, userId },+ { content: 'trashed', isDeleted: true, role: 'user', topicId, userId },+ ]);++ expect(await personalModel.snapshotTopicUsage(topicId)).toEqual({+ assistantMessages: 1,+ llmCalls: 3,+ toolCalls: 2,+ topicModel: 'gpt-x',+ topicProvider: 'openai',+ totalCost: 0.0123,+ totalInputTokens: 900,+ totalOutputTokens: 100,+ totalTokens: 1000,+ userMessages: 2,+ });+ });++ it('keeps unmeasured totals null instead of zero', async () => {+ expect(await personalModel.snapshotTopicUsage(topicId)).toMatchObject({+ assistantMessages: 0,+ llmCalls: null,+ totalCost: null,+ totalTokens: null,+ userMessages: 0,+ });+ });++ it('stores the snapshot with the analysis', async () => {+ const usage = {+ assistantMessages: 4,+ llmCalls: 5,+ toolCalls: 6,+ topicModel: 'gpt-x',+ topicProvider: 'openai',+ totalCost: 1.5,+ totalInputTokens: 70,+ totalOutputTokens: 30,+ totalTokens: 100,+ userMessages: 3,+ };++ await serverDB+ .insert(messages)+ .values({ content: 'first', id: 'msg_1', role: 'user', topicId, updatedAt: T1, userId });+ await personalModel.save({ ...snapshot, result: result(), topicId, usage });++ expect(await personalModel.findByTopic(topicId, 'v1')).toMatchObject(usage);+ });+ });+});diff --git a/packages/database/src/models/topicAnalysis.ts b/packages/database/src/models/topicAnalysis.tsnew file mode 100644index 00000000000..f3bf68681c3--- /dev/null+++ b/packages/database/src/models/topicAnalysis.ts@@ -0,0 +1,192 @@+import type { TopicAnalysisResult } from '@lobechat/types';+import { and, count, eq, exists, gt, isNull, notExists, or, sql } from 'drizzle-orm';++import { messages, topicAnalyses, type TopicAnalysisItem, topics } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { notTrashed } from '../utils/softDelete';+import { topicSummaryEligibleMessage } from './topicSummary';++/** The topic's own consumption at analysis time; `null` means not measured. */+export interface TopicUsageSnapshot {+ assistantMessages: number;+ llmCalls: number | null;+ toolCalls: number;+ topicModel: string | null;+ topicProvider: string | null;+ totalCost: number | null;+ totalInputTokens: number | null;+ totalOutputTokens: number | null;+ totalTokens: number | null;+ userMessages: number;+}++export interface SaveTopicAnalysisParams {+ lastMessageId: string;+ lastMessageUpdatedAt: Date;+ result: TopicAnalysisResult;+ topicId: string;+ usage?: TopicUsageSnapshot;+}++/** Topic classifications owned by one user, scoped to a workspace when given. */+export class TopicAnalysisModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ /**+ * Insert the analysis, or replace the existing one for the same topic and+ * taxonomy version. Either write is accepted only while the analyzed snapshot+ * is still the topic's newest eligible message (the same fence the summary+ * write uses): an analysis whose messages were edited, removed or overtaken+ * while it ran is rejected, while a fresh analysis after the newest message was+ * deleted is not. Returns `undefined` when rejected.+ */+ save = async ({+ lastMessageId,+ lastMessageUpdatedAt,+ result,+ topicId,+ usage,+ }: SaveTopicAnalysisParams) => {+ const isCurrent = this.isSnapshotCurrent(topicId, lastMessageId, lastMessageUpdatedAt);++ // The insert branch has no WHERE of its own, so check the fence up front;+ // the conflict branch re-checks it atomically inside the same statement.+ const [current] = await this.db+ .select({ ok: sql<number>`1` })+ .from(topics)+ .where(and(eq(topics.id, topicId), isCurrent));+ if (!current) return;++ const values = {+ ...usage,+ category: result.category,+ intent: result.intent ?? null,+ labels: result.labels ?? null,+ lastMessageId,+ metadata: result.metadata ?? null,+ lastMessageUpdatedAt,+ model: result.model,+ outcome: result.outcome ?? null,+ provider: result.provider,+ secondaryCategory: result.secondaryCategory ?? null,+ };++ const [row] = await this.db+ .insert(topicAnalyses)+ .values({+ ...values,+ taxonomyVersion: result.taxonomyVersion,+ topicId,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })+ .onConflictDoUpdate({+ set: { ...values, updatedAt: new Date() },+ setWhere: isCurrent,+ target: [topicAnalyses.topicId, topicAnalyses.taxonomyVersion],+ })+ .returning();++ return row;+ };++ /** The snapshot message is unchanged and no newer eligible message exists. */+ private isSnapshotCurrent = (+ topicId: string,+ lastMessageId: string,+ lastMessageUpdatedAt: Date,+ ) =>+ and(+ exists(+ this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topicId),+ topicSummaryEligibleMessage,+ eq(messages.id, lastMessageId),+ eq(messages.updatedAt, lastMessageUpdatedAt),+ ),+ ),+ ),+ notExists(+ this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topicId),+ topicSummaryEligibleMessage,+ or(+ gt(messages.updatedAt, lastMessageUpdatedAt),+ and(eq(messages.updatedAt, lastMessageUpdatedAt), gt(messages.id, lastMessageId)),+ ),+ ),+ ),+ ),+ );++ /**+ * Read the topic's rolled-up token and cost totals plus live message counts.+ * The topic is not re-checked for ownership: callers pass a topic they already+ * resolved for this user.+ */+ snapshotTopicUsage = async (topicId: string): Promise<TopicUsageSnapshot | undefined> => {+ const [topic] = await this.db+ .select({+ llmCalls: sql<number | null>`NULLIF(${topics.usage}->'llm'->>'apiCalls', '')::int`,+ topicModel: topics.model,+ topicProvider: topics.provider,+ totalCost: topics.totalCost,+ totalInputTokens: topics.totalInputTokens,+ totalOutputTokens: topics.totalOutputTokens,+ totalTokens: topics.totalTokens,+ })+ .from(topics)+ .where(eq(topics.id, topicId))+ .limit(1);+ if (!topic) return;++ const roleCounts = await this.db+ .select({ count: count(), role: messages.role })+ .from(messages)+ .where(and(eq(messages.topicId, topicId), notTrashed(messages.isDeleted)))+ .groupBy(messages.role);+ const countOf = (role: string) => roleCounts.find((row) => row.role === role)?.count ?? 0;++ return {+ ...topic,+ assistantMessages: countOf('assistant'),+ llmCalls: topic.llmCalls === null ? null : Number(topic.llmCalls),+ toolCalls: countOf('tool'),+ userMessages: countOf('user'),+ };+ };++ findByTopic = async (+ topicId: string,+ taxonomyVersion: string,+ ): Promise<TopicAnalysisItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(topicAnalyses)+ .where(+ and(+ eq(topicAnalyses.topicId, topicId),+ eq(topicAnalyses.taxonomyVersion, taxonomyVersion),+ eq(topicAnalyses.userId, this.userId),+ this.workspaceId+ ? eq(topicAnalyses.workspaceId, this.workspaceId)+ : isNull(topicAnalyses.workspaceId),+ ),+ )+ .limit(1);++ return row;+ };+}diff --git a/packages/database/src/schemas/index.ts b/packages/database/src/schemas/index.tsindex b2bbf841f86..c1698868ddb 100644--- a/packages/database/src/schemas/index.ts+++ b/packages/database/src/schemas/index.ts@@ -69,6 +69,7 @@ export * from './systemBotProvider';export * from './task';export * from './taskExternalLink';export * from './topic';+export * from './topicAnalysis';export * from './topicComment';export * from './trash';export * from './user';diff --git a/packages/database/src/schemas/topicAnalysis.ts b/packages/database/src/schemas/topicAnalysis.tsnew file mode 100644index 00000000000..ebab7f72660--- /dev/null+++ b/packages/database/src/schemas/topicAnalysis.ts@@ -0,0 +1,73 @@+import { sql } from 'drizzle-orm';+import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle-orm/pg-core';++import { amountNumeric, timestamps, timestamptz } from './_helpers';+import { topics } from './topic';+import { users } from './user';+import { workspaces } from './workspace';++/**+ * One classification of a topic per taxonomy version, written after the topic's+ * auto summary. Re-analyzing the same topic under the same version replaces the+ * row; a new taxonomy version adds a row so earlier results stay comparable.+ */+export const topicAnalyses = pgTable(+ 'topic_analyses',+ {+ // Only read in bulk for reporting, never linked, so no id prefix.+ id: uuid('id').defaultRandom().primaryKey().notNull(),++ topicId: text('topic_id')+ .references(() => topics.id, { onDelete: 'cascade' })+ .notNull(),+ userId: text('user_id')+ .references(() => users.id, { onDelete: 'cascade' })+ .notNull(),+ workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),++ taxonomyVersion: text('taxonomy_version').notNull(),+ category: text('category').notNull(),+ secondaryCategory: text('secondary_category'),+ intent: text('intent'),+ outcome: text('outcome'),+ /** Extra classification dimensions. */+ labels: jsonb('labels').$type<Record<string, unknown>>(),+ /** How the analysis was produced (e.g. prompt version), kept apart from what it concluded. */+ metadata: jsonb('metadata').$type<Record<string, unknown>>(),++ /** Model and provider that produced this analysis. */+ model: text('model'),+ provider: text('provider'),++ // ---- The topic's own consumption when it was analyzed ----+ // A snapshot, not a join: reports group cost and effort by category without+ // the topic's running totals drifting after the analysis. NULL = not measured.+ topicModel: text('topic_model'),+ topicProvider: text('topic_provider'),+ totalTokens: integer('total_tokens'),+ totalInputTokens: integer('total_input_tokens'),+ totalOutputTokens: integer('total_output_tokens'),+ totalCost: amountNumeric('total_cost'),+ llmCalls: integer('llm_calls'),+ toolCalls: integer('tool_calls'),+ userMessages: integer('user_messages'),+ assistantMessages: integer('assistant_messages'),++ /** Newest message the analysis saw; a later message means the result is out of date. */+ lastMessageId: text('last_message_id'),+ lastMessageUpdatedAt: timestamptz('last_message_updated_at'),++ ...timestamps,+ },+ (t) => [+ uniqueIndex('topic_analyses_topic_version_unique').on(t.topicId, t.taxonomyVersion),+ index('topic_analyses_user_id_created_at_idx').on(t.userId, t.createdAt),+ index('topic_analyses_workspace_id_created_at_idx')+ .on(t.workspaceId, t.createdAt)+ .where(sql`${t.workspaceId} IS NOT NULL`),+ index('topic_analyses_version_category_idx').on(t.taxonomyVersion, t.category),+ ],+);++export type TopicAnalysisItem = typeof topicAnalyses.$inferSelect;+export type NewTopicAnalysis = typeof topicAnalyses.$inferInsert;diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.tsindex 37d1df594d1..c800f129bf5 100644--- a/packages/locales/src/default/spend.ts+++ b/packages/locales/src/default/spend.ts@@ -48,6 +48,7 @@ export default {'table.columns.trigger.enums.task': 'Task','table.columns.trigger.enums.thread_title': 'Thread Title','table.columns.trigger.enums.topic': 'Topic Title (Legacy)',+ 'table.columns.trigger.enums.topic_analysis': 'Topic Analysis','table.columns.trigger.enums.topic_summary': 'Topic Summary','table.columns.trigger.enums.topic_title': 'Topic Title','table.columns.trigger.enums.translate': 'Translation',diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex 114a82935e2..be6dbe3d2ec 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -68,6 +68,8 @@ export enum RequestTrigger {* {@link RequestTrigger.GenerationTopicTitle}; kept so historical logs still resolve a label.*/Topic = 'topic',+ /** Server-side topic classification that runs after the auto summary. */+ TopicAnalysis = 'topic_analysis',/** Server-side topic auto summary (description + rolling summary). */TopicSummary = 'topic_summary',/** Chat topic title summaries, both client and server generated. */diff --git a/packages/types/src/topic/analysis.ts b/packages/types/src/topic/analysis.tsnew file mode 100644index 00000000000..c967dd82f10--- /dev/null+++ b/packages/types/src/topic/analysis.ts@@ -0,0 +1,21 @@+/**+ * Classification of one topic, produced after its auto summary is written.+ * The label vocabularies are versioned by `taxonomyVersion`; this contract only+ * fixes the shape, not the label values.+ */+export interface TopicAnalysisResult {+ /** Primary task category id. */+ category: string;+ /** What the user wanted back, e.g. information vs. a produced result. */+ intent?: string | null;+ /** Additional classification dimensions that do not need their own column. */+ labels?: Record<string, unknown>;+ /** How the analysis was produced (prompt version, inputs, timings), not what it concluded. */+ metadata?: Record<string, unknown>;+ model: string;+ /** Whether the user's goal was reached. */+ outcome?: string | null;+ provider: string;+ secondaryCategory?: string | null;+ taxonomyVersion: string;+}diff --git a/packages/types/src/topic/index.ts b/packages/types/src/topic/index.tsindex 7acb303e4a1..a382dd4f597 100644--- a/packages/types/src/topic/index.ts+++ b/packages/types/src/topic/index.ts@@ -1,2 +1,3 @@+export * from './analysis';export * from './thread';export * from './topic';