🤯 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(expertise): add model and ingestion backend (#18362)
Arvin Xu848cd03241dd
diff --git a/apps/server/src/router-hono/workflows/expertise-history/index.ts b/apps/server/src/router-hono/workflows/expertise-history/index.tsnew file mode 100644index 00000000000..8138ffd3f8a--- /dev/null+++ b/apps/server/src/router-hono/workflows/expertise-history/index.ts@@ -0,0 +1,32 @@+import { withOtelMetricsForUpstashWorkflows } from '@lobechat/observability-otel/modules/upstash-workflow';+import { serve } from '@upstash/workflow/hono';+import { Hono } from 'hono';++import { runExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';+import { runExpertiseHistoryTopicWorkflow } from '@/server/workflows/expertiseHistory/topic';++import { createWorkflowQstashClient } from '../qstashClient';++const app = new Hono();++app.post(+ '/run',+ serve(+ withOtelMetricsForUpstashWorkflows(runExpertiseHistoryWorkflow, {+ url: '/api/workflows/expertise-history/run',+ }),+ { qstashClient: createWorkflowQstashClient() },+ ),+);++app.post(+ '/topic',+ serve(+ withOtelMetricsForUpstashWorkflows(runExpertiseHistoryTopicWorkflow, {+ url: '/api/workflows/expertise-history/topic',+ }),+ { qstashClient: createWorkflowQstashClient() },+ ),+);++export default app;diff --git a/apps/server/src/router-hono/workflows/index.ts b/apps/server/src/router-hono/workflows/index.tsindex 8c6d5570347..36aa3077b1e 100644--- a/apps/server/src/router-hono/workflows/index.ts+++ b/apps/server/src/router-hono/workflows/index.ts@@ -1,6 +1,7 @@import { Hono } from 'hono';import agentSignalApp from './agent-signal';+import expertiseHistoryApp from './expertise-history';import memoryUserMemoryApp from './memory-user-memory';import onboardingTaskRecommendationApp from './onboarding-task-recommendation';import onboardingUnderstandingApp from './onboarding-understanding';@@ -11,6 +12,7 @@ import verifyApp from './verify';const app = new Hono().basePath('/api/workflows');app.route('/agent-signal', agentSignalApp);+app.route('/expertise-history', expertiseHistoryApp);app.route('/memory-user-memory', memoryUserMemoryApp);app.route('/onboarding/understanding', onboardingUnderstandingApp);app.route('/onboarding/task-recommendations', onboardingTaskRecommendationApp);diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.tsnew file mode 100644index 00000000000..f466ef41031--- /dev/null+++ b/apps/server/src/routers/lambda/expertise.ts@@ -0,0 +1,234 @@+import { z } from 'zod';++import { ExpertiseModel } from '@/database/models/expertise';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { ExpertiseDomainService } from '@/server/services/expertise/domain';+import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';++import { recentLessonDelta } from './expertiseHelpers';++const expertiseProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ expertiseModel: new ExpertiseModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ expertiseDomainService: new ExpertiseDomainService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ expertiseIngestionService: new ExpertiseIngestionService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++/** Exposes fitted maturity only when the model has enough trustworthy evidence. */+const toMaturity = (s?: {+ fitComputedAt: Date | null;+ fitConfidence: string | null;+ fitR2: number | null;+ fitSampleSize: number | null;+ maturity: number | null;+ observedSpan: number | null;+ pInf: number | null;+ plateauKind: string | null;+ tau: number | null;+ tauPinned: boolean;+}) => {+ if (!s) return { reason: 'no-data' as const, usable: false as const };+ if (!s.fitComputedAt) return { reason: 'pending' as const, usable: false as const };+ if (s.tauPinned) return { reason: 'tau-pinned' as const, usable: false as const };+ if (s.fitConfidence !== 'ok') {+ return {+ plateauKind: s.plateauKind,+ reason: 'low-confidence' as const,+ usable: false as const,+ };+ }+ return {+ fitR2: s.fitR2,+ fitSampleSize: s.fitSampleSize,+ maturity: s.maturity,+ /** Values below one mean the observed data does not yet constrain the asymptote. */+ observedSpan: s.observedSpan,+ pInf: s.pInf,+ plateauKind: s.plateauKind,+ speculative: (s.observedSpan ?? 0) < 1,+ tau: s.tau,+ usable: true as const,+ };+};++export const expertiseRouter = router({+ /** L0: all expertise available to an agent and its latest state. */+ listByAgent: expertiseProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ ctx, input }) => {+ const bound = await ctx.expertiseModel.listDomainsForAgent(input.agentId);+ const domainIds = bound.map((b) => b.domain.id);+ const [snapshots, actors, insights, series] = await Promise.all([+ ctx.expertiseModel.latestSnapshots(domainIds),+ ctx.expertiseModel.actorsByDomain(domainIds),+ ctx.expertiseModel.listInsights(domainIds),+ ctx.expertiseModel.seriesForDomains(domainIds),+ ]);+ const snapByDomain = new Map(snapshots.map((s) => [s.domainId, s]));+ const actorsByDomain = new Map<string, string[]>();+ for (const a of actors) {+ actorsByDomain.set(a.domainId, [...(actorsByDomain.get(a.domainId) ?? []), a.actorId]);+ }+ const seriesByDomain = new Map<string, { n: number; run: number }[]>();+ for (const s of series) {+ seriesByDomain.set(s.domainId, [+ ...(seriesByDomain.get(s.domainId) ?? []),+ { n: s.activeCount, run: s.runIndex },+ ]);+ }++ const domains = bound.map(({ binding, domain }) => {+ const snap = snapByDomain.get(domain.id);+ const points = seriesByDomain.get(domain.id) ?? [];+ // Net change over the latest five runs distinguishes growth, retirement, and no learning.+ const delta = recentLessonDelta(points);+ return {+ activeRate: snap?.activeRate ?? null,+ actors: actorsByDomain.get(domain.id) ?? [],+ canonCoverage: snap?.canonCoverage ?? null,+ contributionMode: binding.contributionMode,+ delta,+ id: domain.id,+ /** Timestamp of the latest practice run. */+ lastPracticedAt: snap?.capturedAt ?? null,+ layerCounts: snap?.layerCounts ?? {},+ layerCoverage: snap?.layerCoverage ?? null,+ layers: domain.layers,+ layerSource: domain.layerSource,+ lessonCount: snap?.activeCount ?? 0,+ maturity: toMaturity(snap),+ runCount: snap?.runIndex ?? 0,+ /** Series used by the overlaid maturity chart. */+ series: points,+ slug: domain.slug,+ title: domain.title,+ };+ });++ return {+ domains,+ insights,+ totals: {+ domains: domains.length,+ lessons: domains.reduce((a, d) => a + d.lessonCount, 0),+ },+ };+ }),++ /** L1: the complete SCLPT domain state and time series. */+ getDomain: expertiseProcedure+ .input(z.object({ domainId: z.string() }))+ .query(async ({ ctx, input }) => {+ const domain = await ctx.expertiseModel.findDomain(input.domainId);+ if (!domain) return null;++ const [snapshots, runCount, humanFlags, lessonStats, layerCounts, canon] = await Promise.all([+ ctx.expertiseModel.listSnapshots(input.domainId),+ ctx.expertiseModel.countRuns(input.domainId),+ ctx.expertiseModel.runHumanFlags(input.domainId),+ ctx.expertiseModel.lessonStats(input.domainId),+ ctx.expertiseModel.layerCounts(input.domainId),+ ctx.expertiseModel.canonAnchorCounts(input.domainId),+ ]);+ const humanByRun = new Map(humanFlags.map((r) => [r.runIndex, r.hadHumanInLoop]));+ const latest = snapshots.at(-1);+ // Tail gain measures recent quantity while plateauKind describes the curve shape.+ const tail = snapshots.slice(-6);+ const tailGain = tail.length > 1 ? tail.at(-1)!.activeCount - tail[0].activeCount : 0;++ return {+ canonAnchorCounts: canon.byKey,+ domain,+ layerCounts,+ lessonStats,+ maturity: toMaturity(latest),+ runCount,+ /** The chart receives only the snapshot fields it renders. */+ series: snapshots.map((s) => ({+ activeCount: s.activeCount,+ compiledCount: s.compiledCount,+ /** Controls whether the chart marks this run as human-assisted. */+ hadHumanInLoop: humanByRun.get(s.runIndex) ?? false,+ runIndex: s.runIndex,+ })),+ tailGain,+ unanchoredCount: canon.unanchored,+ };+ }),++ /** L2: lessons ordered by hits with server-computed usage tiers. */+ listLessons: expertiseProcedure+ .input(+ z.object({+ domainId: z.string(),+ layer: z.string().optional(),+ search: z.string().optional(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const domain = await ctx.expertiseModel.findDomain(input.domainId);+ if (!domain) return [];+ return ctx.expertiseModel.listLessons(input.domainId, {+ layer: input.layer,+ search: input.search,+ });+ }),++ /** L3: one lesson together with its supporting and violating examples. */+ getLesson: expertiseProcedure+ .input(z.object({ lessonId: z.string() }))+ .query(async ({ ctx, input }) => {+ const lesson = await ctx.expertiseModel.findLesson(input.lessonId);+ if (!lesson) return null;+ const hits = await ctx.expertiseModel.listLessonHits(input.lessonId);+ return { hits, lesson };+ }),++ /** Creates an expertise domain from a natural-language brief. */+ createDomain: expertiseProcedure+ .input(+ z.object({+ agentId: z.string(),+ brief: z.string().min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => ctx.expertiseDomainService.createFromBrief(input)),++ /** Explicitly bootstraps expertise from conversations that existed before the domain did. */+ ingestHistory: expertiseProcedure+ .input(z.object({ agentId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const candidateCount = await ctx.expertiseIngestionService.countHistoricalTopics(+ input.agentId,+ );+ if (candidateCount === 0) return { candidateCount, workflowRunId: null };++ const { workflowRunId } = await ExpertiseHistoryWorkflow.trigger({+ agentId: input.agentId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ return { candidateCount, workflowRunId };+ }),++ /** Dismisses an incorrect generated insight. */+ dismissInsight: expertiseProcedure+ .input(z.object({ insightId: z.string(), reason: z.string().optional() }))+ .mutation(async ({ ctx, input }) => {+ await ctx.expertiseModel.dismissInsight(input.insightId, input.reason);+ }),+});diff --git a/apps/server/src/routers/lambda/expertiseHelpers.test.ts b/apps/server/src/routers/lambda/expertiseHelpers.test.tsnew file mode 100644index 00000000000..631e4c2953a--- /dev/null+++ b/apps/server/src/routers/lambda/expertiseHelpers.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { recentLessonDelta } from './expertiseHelpers';++describe('recentLessonDelta', () => {+ it('uses zero as the baseline for the first practice', () => {+ expect(recentLessonDelta([{ n: 1, run: 1 }])).toBe(1);+ });++ it('reports recent net change after multiple practices', () => {+ expect(+ recentLessonDelta([+ { n: 2, run: 1 },+ { n: 4, run: 2 },+ { n: 3, run: 3 },+ ]),+ ).toBe(1);+ });+});diff --git a/apps/server/src/routers/lambda/expertiseHelpers.ts b/apps/server/src/routers/lambda/expertiseHelpers.tsnew file mode 100644index 00000000000..58a630093d0--- /dev/null+++ b/apps/server/src/routers/lambda/expertiseHelpers.ts@@ -0,0 +1,12 @@+interface ExpertiseSeriesPoint {+ n: number;+ run: number;+}++/** Recent net growth, using zero as the baseline for a domain's first practice. */+export const recentLessonDelta = (points: ExpertiseSeriesPoint[]) => {+ const recent = points.slice(-6);+ if (recent.length === 0) return 0;+ if (recent.length === 1) return recent[0].n;+ return recent.at(-1)!.n - recent[0].n;+};diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 9c9b6c5aeb4..66c69445af3 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -47,6 +47,7 @@ import { configRouter } from './config';import { connectorRouter } from './connector';import { deviceRouter } from './device';import { documentRouter } from './document';+import { expertiseRouter } from './expertise';import { exporterRouter } from './exporter';import { fileRouter } from './file';import { followUpActionRouter } from './followUpAction';@@ -103,6 +104,7 @@ export const lambdaRouter = router({agentEvalExternal: agentEvalExternalRouter,agentLabel: agentLabelRouter,agentSkills: agentSkillsRouter,+ expertise: expertiseRouter,agentSignal: agentSignalRouter,task: taskRouter,changelog: changelogRouter,diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 07c4145ab04..c8334a57268 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -349,8 +349,30 @@ export class CompletionLifecycle {async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {try {const { assistantMessageId, metadata } = this.buildLifecycleEvent(operationId, state, reason);- const selfIteration =+ let selfIteration =reason === 'error' ? undefined : extractSelfIterationCompletionPayload(state);+ if (reason !== 'error' && !selfIteration) {+ try {+ const operation = await this.agentOperationModel.findById(operationId);+ const operationMetadata = operation?.metadata;+ if (operationMetadata?.agentSignal) {+ selfIteration = extractSelfIterationCompletionPayload({+ ...state,+ metadata: {+ ...operationMetadata,+ ...metadata,+ userId: metadata?.userId || this.userId,+ },+ });+ }+ } catch (error) {+ log(+ '[completion-lifecycle] failed to hydrate Agent Signal marker op=%s: %O',+ operationId,+ error,+ );+ }+ }if (reason !== 'error') {log('[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex c556d829d05..48944b1ffe7 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1072,6 +1072,48 @@ describe('CompletionLifecycle.emitSignalEvents — assistant anchor', () => {assistantMessageId: 'msg-assistant',});});++ it('hydrates a persisted self-reflection marker when terminal state metadata lost it', async () => {+ const emitSpy = vi+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')+ .mockResolvedValue(undefined as any);+ const lifecycle = buildLifecycle();+ (lifecycle as any).agentOperationModel = {+ findById: vi.fn().mockResolvedValue({+ metadata: {+ agentSignal: {+ agentId: 'agent-1',+ kind: 'self-reflection',+ sourceId: 'reflection-source-1',+ topicId: 'tpc-1',+ },+ },+ }),+ };++ await lifecycle.emitSignalEvents(+ 'op-1',+ {+ messages: [{ content: 'review complete', id: 'msg-assistant', role: 'assistant' }],+ metadata: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },+ stepCount: 1,+ },+ 'done',+ );++ const [emission] = emitSpy.mock.calls[0];+ expect(emission.payload).toMatchObject({+ selfIteration: {+ marker: {+ agentId: 'agent-1',+ kind: 'self-reflection',+ sourceId: 'reflection-source-1',+ topicId: 'tpc-1',+ },+ userId: 'user-1',+ },+ });+ });});describe('CompletionLifecycle.registerFileWorks', () => {diff --git a/apps/server/src/services/agentSignal/operationMarker.ts b/apps/server/src/services/agentSignal/operationMarker.tsindex aa48ed28797..8ac7a7b2ad5 100644--- a/apps/server/src/services/agentSignal/operationMarker.ts+++ b/apps/server/src/services/agentSignal/operationMarker.ts@@ -49,6 +49,7 @@ export const readAgentSignalMarker = (return {kind: kind as AgentSignalOperationKind,+ ...(str(marker.agentId) ? { agentId: str(marker.agentId) } : {}),...(str(marker.anchorMessageId) ? { anchorMessageId: str(marker.anchorMessageId) } : {}),...(str(marker.localDate) ? { localDate: str(marker.localDate) } : {}),...(str(marker.reviewWindowEnd) ? { reviewWindowEnd: str(marker.reviewWindowEnd) } : {}),diff --git a/apps/server/src/services/agentSignal/orchestrator.ts b/apps/server/src/services/agentSignal/orchestrator.tsindex dfab64fc98a..fe1adba03f9 100644--- a/apps/server/src/services/agentSignal/orchestrator.ts+++ b/apps/server/src/services/agentSignal/orchestrator.ts@@ -10,6 +10,8 @@ import type {import type { AgentSignalSourceType } from '@lobechat/agent-signal/source';import { createSourceEvent } from '@lobechat/agent-signal/source';+import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import type {AgentSignalEmitOptions,AgentSignalExecutionContext,@@ -103,9 +105,16 @@ const createPolicyOptions = (return {completion: {- onSelfIterationCompleted: createSelfIterationCompletionHandler(- options.receiptStore ? { receiptStore: options.receiptStore } : {},- ),+ onSelfIterationCompleted: async (input) => {+ await createSelfIterationCompletionHandler(+ options.receiptStore ? { receiptStore: options.receiptStore } : {},+ )(input);+ await new ExpertiseIngestionService(+ context.db,+ context.userId,+ context.workspaceId,+ ).ingestSelfReview(input);+ },},feedbackDomainJudge: {db: context.db,diff --git a/apps/server/src/services/agentSignal/policies/completionPolicy.test.ts b/apps/server/src/services/agentSignal/policies/completionPolicy.test.tsindex 15b1e63b605..e82c67a1060 100644--- a/apps/server/src/services/agentSignal/policies/completionPolicy.test.ts+++ b/apps/server/src/services/agentSignal/policies/completionPolicy.test.ts@@ -52,7 +52,7 @@ describe('createCompletionPolicy', () => {).resolves.toBeUndefined();});- it('ignores runs that carry no marker payload, regardless of agent', async () => {+ it('does not project a self-iteration receipt for an ordinary run', async () => {const onSelfIterationCompleted = vi.fn();const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));diff --git a/apps/server/src/services/agentSignal/policies/completionPolicy.ts b/apps/server/src/services/agentSignal/policies/completionPolicy.tsindex caf45e655c2..07d4acfa372 100644--- a/apps/server/src/services/agentSignal/policies/completionPolicy.ts+++ b/apps/server/src/services/agentSignal/policies/completionPolicy.ts@@ -61,8 +61,8 @@ export const createCompletionPolicy = (options: CreateCompletionPolicyOptions =);if (!agentId || !operationId) return;- // Marker-driven: only runs that stamped a marker carry a selfIteration- // payload. Unmarked runs have nothing to project.+ // Ordinary foreground completions stay cheap. Post-processing is attached to marked+ // self-review / self-reflection completions, after their bounded context window closes.if (!selfIteration) return;if (!options.onSelfIterationCompleted) {log('[completion-policy] no onSelfIterationCompleted wired — skipping projection');diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.tsindex 4266cf7a704..80926b81ecb 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts@@ -22,7 +22,7 @@ const buildState = (metadata: Record<string, unknown>, extra: Record<string, unkconst reviewMetadata = {agentId: 'agent_user_1',- agentSignal: { kind: 'nightly-review', sourceId: 'src_1' },+ agentSignal: { agentId: 'agent_user_1', kind: 'nightly-review', sourceId: 'src_1' },userId: 'user_1',};@@ -52,6 +52,7 @@ describe('extractSelfIterationCompletionPayload', () => {);expect(result?.marker.kind).toBe('nightly-review');+ expect(result?.marker.agentId).toBe('agent_user_1');expect(result?.userId).toBe('user_1');expect(result?.mutations).toHaveLength(1);expect(result?.mutations[0].apiName).toBe('createSelfReviewProposal');diff --git a/apps/server/src/services/expertise/domain.test.ts b/apps/server/src/services/expertise/domain.test.tsnew file mode 100644index 00000000000..ee979ce72f8--- /dev/null+++ b/apps/server/src/services/expertise/domain.test.ts@@ -0,0 +1,58 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ExpertiseDomainService } from './domain';++const getAgentModelConfig = vi.fn();+const generateObject = vi.fn();+const createDomain = vi.fn();++vi.mock('@/database/models/agent', () => ({+ AgentModel: class {+ getAgentModelConfig = getAgentModelConfig;+ },+}));+vi.mock('@/database/models/expertise', () => ({+ ExpertiseModel: class {+ createDomain = createDomain;+ },+}));+vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ generateObject = generateObject;+ },+}));++describe('ExpertiseDomainService', () => {+ beforeEach(() => vi.clearAllMocks());++ it('uses structured generation instead of parsing the brief with string rules', async () => {+ getAgentModelConfig.mockResolvedValue({ model: 'test-model', provider: 'test-provider' });+ generateObject.mockResolvedValue({+ domainFilter: 'Include production incident diagnosis and remediation.',+ outOfScope: 'Exclude general architecture discussions without an incident.',+ title: 'Production incident response',+ });+ createDomain.mockResolvedValue('domain_1');++ const result = await new ExpertiseDomainService({} as never, 'user_1').createFromBrief({+ agentId: 'agent_1',+ brief: 'Help it improve at production incidents, excluding general design discussions.',+ });++ expect(generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ schema: expect.objectContaining({ name: 'expertise_domain_brief' }),+ }),+ expect.any(Object),+ );+ expect(createDomain).toHaveBeenCalledWith({+ agentId: 'agent_1',+ brief: 'Help it improve at production incidents, excluding general design discussions.',+ domainFilter: 'Include production incident diagnosis and remediation.',+ outOfScope: 'Exclude general architecture discussions without an incident.',+ title: 'Production incident response',+ });+ expect(result).toBe('domain_1');+ });+});diff --git a/apps/server/src/services/expertise/domain.ts b/apps/server/src/services/expertise/domain.tsnew file mode 100644index 00000000000..1862bf10463--- /dev/null+++ b/apps/server/src/services/expertise/domain.ts@@ -0,0 +1,76 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import { z } from 'zod';++import { AgentModel } from '@/database/models/agent';+import { ExpertiseModel } from '@/database/models/expertise';+import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';++const DomainBriefSchema = z.object({+ domainFilter: z.string().min(1),+ outOfScope: z.string().nullable(),+ title: z.string().min(1).max(80),+});++const DOMAIN_BRIEF_JSON_SCHEMA: GenerateObjectSchema = {+ name: 'expertise_domain_brief',+ schema: {+ additionalProperties: false,+ properties: {+ domainFilter: { type: 'string' },+ outOfScope: { type: ['string', 'null'] },+ title: { maxLength: 80, type: 'string' },+ },+ required: ['domainFilter', 'outOfScope', 'title'],+ type: 'object',+ },+};++export class ExpertiseDomainService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ createFromBrief = async (input: { agentId: string; brief: string }) => {+ const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);+ const modelConfig = await agentModel.getAgentModelConfig(input.agentId);+ if (!modelConfig) throw new Error('Agent model configuration is unavailable');++ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const generated = DomainBriefSchema.parse(+ await ai.generateObject(+ {+ messages: [+ {+ content:+ 'Convert the user brief into one executable expertise domain. Return a concise title, a domainFilter that states what conversations and work count as practice, and outOfScope that states explicit exclusions. Preserve the user intent, do not invent a broader domain, and write all fields in the language used by the user.',+ role: 'system',+ },+ { content: input.brief.trim(), role: 'user' },+ ],+ ...modelConfig,+ schema: DOMAIN_BRIEF_JSON_SCHEMA,+ },+ {+ metadata: { trigger: 'expertise_domain_brief' },+ tracing: {+ agentId: input.agentId,+ promptVersion: 'expertise-domain-brief-v1',+ scenario: TRACING_SCENARIOS.TopicAutoSummary,+ schemaName: DOMAIN_BRIEF_JSON_SCHEMA.name,+ },+ },+ ),+ );++ return new ExpertiseModel(this.db, this.userId, this.workspaceId).createDomain({+ ...generated,+ agentId: input.agentId,+ brief: input.brief,+ outOfScope: generated.outOfScope ?? undefined,+ });+ };+}diff --git a/apps/server/src/services/expertise/ingestion.test.ts b/apps/server/src/services/expertise/ingestion.test.tsnew file mode 100644index 00000000000..8e7e8f6749e--- /dev/null+++ b/apps/server/src/services/expertise/ingestion.test.ts@@ -0,0 +1,161 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { expertiseHits, expertiseRuns } from '@/database/schemas';++import type { SelfIterationCompletionPayload } from '../agentSignal/services/selfIteration/completion';+import { ExpertiseIngestionService } from './ingestion';++const completion = (selfIteration: SelfIterationCompletionPayload) => ({+ agentId: 'agent-signal-reflection',+ operationId: 'op_review_1',+ selfIteration,+});++describe('ExpertiseIngestionService.ingestSelfReview', () => {+ it('ingests a topic only after its self-reflection run completes', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ const ingestCompletion = vi+ .spyOn(service, 'ingestCompletion')+ .mockResolvedValue({ ingested: 1, reason: 'matched' });++ await service.ingestSelfReview(+ completion({+ artifacts: [],+ marker: {+ agentId: 'agent_1',+ kind: 'self-reflection',+ sourceId: 'reflection_1',+ topicId: 'topic_1',+ },+ mutations: [],+ userId: 'user_1',+ }),+ );++ expect(ingestCompletion).toHaveBeenCalledWith({+ agentId: 'agent_1',+ operationId: 'op_review_1',+ topicId: 'topic_1',+ });+ });++ it('ignores self-iteration modes that are not review windows', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ const ingestCompletion = vi.spyOn(service, 'ingestCompletion');++ const result = await service.ingestSelfReview(+ completion({+ artifacts: [],+ marker: { agentId: 'agent_1', kind: 'memory', sourceId: 'memory_1' },+ mutations: [],+ userId: 'user_1',+ }),+ );++ expect(result).toEqual({ ingested: 0, reason: 'not-review' });+ expect(ingestCompletion).not.toHaveBeenCalled();+ });+});++describe('ExpertiseIngestionService historical ingestion', () => {+ it('uses a stable topic key instead of inventing an operation id', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ const ingestCompletion = vi+ .spyOn(service, 'ingestCompletion')+ .mockResolvedValue({ ingested: 1, reason: 'matched' });++ await service.ingestHistoricalTopic('agent_1', 'topic_1');++ expect(ingestCompletion).toHaveBeenCalledWith({+ agentId: 'agent_1',+ ingestionKey: 'historical-v1:topic_1',+ topicId: 'topic_1',+ });+ });++ it('processes old topics sequentially to bound model concurrency', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ vi.spyOn(service, 'listHistoricalTopics').mockResolvedValue([+ { topicId: 'topic_1' },+ { topicId: 'topic_2' },+ ] as never);+ const ingest = vi+ .spyOn(service, 'ingestHistoricalTopic')+ .mockResolvedValueOnce({ ingested: 1, reason: 'matched' })+ .mockResolvedValueOnce({ ingested: 0, reason: 'no-match' });++ await expect(service.ingestHistory('agent_1')).resolves.toEqual({ ingested: 1, scanned: 2 });+ expect(ingest.mock.calls).toEqual([+ ['agent_1', 'topic_1'],+ ['agent_1', 'topic_2'],+ ]);+ });+});++describe('ExpertiseIngestionService.persistDomainRun', () => {+ it('uses the persisted run id for the lesson hit', async () => {+ const inserted = new Map<unknown, Record<string, unknown>[]>();+ const selectResults = [+ [],+ [],+ [{ value: 0 }],+ [],+ [{ active: 1, compiled: 0, retired: 0 }],+ [],+ ];+ let selectIndex = 0;+ const selectChain = () => {+ const result = selectResults[selectIndex++];+ const chain = {+ from: () => chain,+ for: () => chain,+ groupBy: () => chain,+ limit: () => chain,+ orderBy: () => chain,+ // Drizzle query builders are awaitable thenables; mirror that contract in this boundary fake.+ // eslint-disable-next-line unicorn/no-thenable+ then: (resolve: (value: unknown) => void) => resolve(result),+ where: () => chain,+ };+ return chain;+ };+ const tx = {+ insert: (table: unknown) => ({+ values: async (value: Record<string, unknown>) => {+ inserted.set(table, [...(inserted.get(table) ?? []), value]);+ },+ }),+ select: selectChain,+ update: () => ({ set: () => ({ where: async () => undefined }) }),+ };+ const service = new ExpertiseIngestionService(+ {+ transaction: async (callback: (value: typeof tx) => Promise<void>) => callback(tx),+ } as never,+ 'user_1',+ );++ await service['persistDomainRun']({+ agentId: 'agent_1',+ domain: { id: 'domain_1', lessons: [] },+ observations: [+ {+ example: 'Observed evidence',+ existingCode: null,+ layer: null,+ outcome: 'pass',+ reasoning: 'Evidence supports the rule',+ title: 'Ground the conclusion in evidence',+ },+ ],+ operationId: 'operation_1',+ topicId: 'topic_1',+ });++ const run = inserted.get(expertiseRuns)?.[0];+ const hit = inserted.get(expertiseHits)?.[0];+ expect(run?.id).toMatch(/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i);+ expect(hit?.runId).toBe(run?.id);+ });+});diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsnew file mode 100644index 00000000000..cdac03567ae--- /dev/null+++ b/apps/server/src/services/expertise/ingestion.ts@@ -0,0 +1,526 @@+import { randomUUID } from 'node:crypto';++import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ expertiseDomains,+ expertiseDomainSnapshots,+ expertiseHits,+ expertiseLessons,+ expertiseRuns,+ messages,+ topics,+} from '@lobechat/database/schemas';+import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import {+ and,+ asc,+ countDistinct,+ desc,+ eq,+ gt,+ isNotNull,+ isNull,+ max,+ or,+ sql,+} from 'drizzle-orm';+import { z } from 'zod';++import { AgentModel } from '@/database/models/agent';+import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import { ExpertiseModel } from '@/database/models/expertise';+import type { LobeChatDatabase } from '@/database/type';+import type { CompletionCallbackParams } from '@/server/services/agentSignal/policies/completionPolicy';+import { AiGenerationService } from '@/server/services/aiGeneration';++const MAX_CONTEXT_MESSAGES = 24;+const MAX_CONTEXT_CHARS = 24_000;+const PROMPT_VERSION = 'expertise-ingestion-v1';++const AnalysisSchema = z.object({+ domains: z.array(+ z.object({+ domainId: z.string(),+ matches: z.boolean(),+ observations: z+ .array(+ z.object({+ existingCode: z.string().nullable(),+ example: z.string(),+ layer: z.string().nullable(),+ outcome: z.enum(['pass', 'violation']),+ reasoning: z.string(),+ title: z.string(),+ }),+ )+ .max(8),+ }),+ ),+});++const ANALYSIS_JSON_SCHEMA: GenerateObjectSchema = {+ name: 'expertise_topic_ingestion',+ schema: {+ additionalProperties: false,+ properties: {+ domains: {+ items: {+ additionalProperties: false,+ properties: {+ domainId: { type: 'string' },+ matches: { type: 'boolean' },+ observations: {+ items: {+ additionalProperties: false,+ properties: {+ existingCode: { type: ['string', 'null'] },+ example: { type: 'string' },+ layer: { type: ['string', 'null'] },+ outcome: { enum: ['pass', 'violation'], type: 'string' },+ reasoning: { type: 'string' },+ title: { type: 'string' },+ },+ required: ['existingCode', 'example', 'layer', 'outcome', 'reasoning', 'title'],+ type: 'object',+ },+ maxItems: 8,+ type: 'array',+ },+ },+ required: ['domainId', 'matches', 'observations'],+ type: 'object',+ },+ type: 'array',+ },+ },+ required: ['domains'],+ type: 'object',+ },+};++interface ExpertiseCompletionInput {+ agentId: string;+ hadHumanInLoop?: boolean;+ ingestionKey?: string;+ operationId?: string;+ serializedContext?: string;+ topicId: string;+}++/**+ * Turns one completed topic turn into bounded expertise evidence.+ *+ * The completion event is the progress boundary: context is read up to the latest persisted+ * message, classified against every bound domain filter, then committed as one run per matching+ * domain. A non-matching conversation leaves no run behind.+ */+export class ExpertiseIngestionService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ /**+ * Runs expertise ingestion only after the existing self-review window has completed.+ * Nightly review batches every active topic in its window; fast self-reflection reuses its+ * single topic scope. Other self-iteration modes are deliberately ignored.+ */+ ingestSelfReview = async (input: CompletionCallbackParams) => {+ const marker = input.selfIteration?.marker;+ const agentId = marker?.agentId;+ if (!marker || !agentId) return { ingested: 0, reason: 'missing-review-agent' } as const;++ if (marker.kind === 'self-reflection' && marker.topicId) {+ return this.ingestCompletion({+ agentId,+ operationId: input.operationId,+ topicId: marker.topicId,+ });+ }++ if (marker.kind !== 'nightly-review' || !marker.reviewWindowStart || !marker.reviewWindowEnd) {+ return { ingested: 0, reason: 'not-review' } as const;+ }++ const reviewContext = new AgentSignalReviewContextModel(this.db, this.userId, this.workspaceId);+ const topics = await reviewContext.listTopicActivity({+ agentId,+ limit: 100,+ windowEnd: new Date(marker.reviewWindowEnd),+ windowStart: new Date(marker.reviewWindowStart),+ });+ const results = [];+ for (const topic of topics) {+ if (!topic.topicId) continue;+ results.push(+ await this.ingestCompletion({+ agentId,+ operationId: input.operationId,+ topicId: topic.topicId,+ }),+ );+ }+ return {+ ingested: results.reduce((sum, result) => sum + result.ingested, 0),+ reason: 'nightly-review',+ } as const;+ };++ /** Lists existing conversations owned by this agent for an explicit historical backfill. */+ listHistoricalTopics = async (+ agentId: string,+ options: { cursor?: { lastActivityAt: Date; topicId: string }; limit?: number } = {},+ ) => {+ const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;+ const scope = this.workspaceId+ ? eq(messages.workspaceId, this.workspaceId)+ : and(eq(messages.userId, this.userId), isNull(messages.workspaceId));++ const lastActivity = max(messages.createdAt);+ return this.db+ .select({+ lastActivityAt: max(messages.createdAt),+ topicId: sql<string>`${messages.topicId}`,+ })+ .from(messages)+ .leftJoin(topics, eq(topics.id, messages.topicId))+ .where(and(scope, eq(effectiveAgentId, agentId), isNotNull(messages.topicId)))+ .groupBy(messages.topicId)+ .having(+ options.cursor+ ? or(+ gt(lastActivity, options.cursor.lastActivityAt),+ and(+ eq(lastActivity, options.cursor.lastActivityAt),+ gt(messages.topicId, options.cursor.topicId),+ ),+ )+ : undefined,+ )+ .limit(options.limit ?? 50)+ .orderBy(asc(max(messages.createdAt)), asc(messages.topicId));+ };++ /** Counts historical topics so the UI can explain the scope before scheduling the backfill. */+ countHistoricalTopics = async (agentId: string) => {+ const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;+ const scope = this.workspaceId+ ? eq(messages.workspaceId, this.workspaceId)+ : and(eq(messages.userId, this.userId), isNull(messages.workspaceId));+ const [row] = await this.db+ .select({ count: countDistinct(messages.topicId) })+ .from(messages)+ .leftJoin(topics, eq(topics.id, messages.topicId))+ .where(and(scope, eq(effectiveAgentId, agentId), isNotNull(messages.topicId)));++ return row?.count ?? 0;+ };++ /** Imports one old topic with a stable key, so retrying the workflow cannot duplicate runs. */+ ingestHistoricalTopic = async (agentId: string, topicId: string) =>+ this.ingestCompletion({+ agentId,+ ingestionKey: `historical-v1:${topicId}`,+ topicId,+ });++ /** Local-runtime fallback for the durable workflow used in queue deployments. */+ ingestHistory = async (agentId: string) => {+ let ingested = 0;+ let scanned = 0;+ let cursor: { lastActivityAt: Date; topicId: string } | undefined;+ while (true) {+ const topicRows = await this.listHistoricalTopics(agentId, { cursor, limit: 50 });+ for (const topic of topicRows) {+ const result = await this.ingestHistoricalTopic(agentId, topic.topicId);+ ingested += result.ingested;+ scanned += 1;+ }+ const last = topicRows.at(-1);+ if (!last || topicRows.length < 50 || !last.lastActivityAt) break;+ cursor = { lastActivityAt: last.lastActivityAt, topicId: last.topicId };+ }+ return { ingested, scanned };+ };++ ingestCompletion = async (input: ExpertiseCompletionInput) => {+ const expertiseModel = new ExpertiseModel(this.db, this.userId, this.workspaceId);+ const bound = await expertiseModel.listDomainsForAgent(input.agentId);+ if (bound.length === 0) return { ingested: 0, reason: 'no-domains' } as const;++ const topicContext = input.serializedContext+ ? {+ hadHumanInLoop: input.hadHumanInLoop ?? /^\[user\]/m.test(input.serializedContext),+ serializedContext: input.serializedContext,+ }+ : await this.readTopicContext(input.topicId);+ const context = topicContext.serializedContext.slice(-MAX_CONTEXT_CHARS);+ if (!context.trim()) return { ingested: 0, reason: 'empty-context' } as const;++ const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);+ const modelConfig = await agentModel.getAgentModelConfig(input.agentId);+ if (!modelConfig) return { ingested: 0, reason: 'no-model' } as const;++ const domains = await Promise.all(+ bound.map(async ({ domain }) => ({+ canon: domain.canonEntries,+ domainFilter: domain.domainFilter,+ id: domain.id,+ layers: domain.layers,+ lessons: (await expertiseModel.listLessons(domain.id)).map((lesson) => ({+ code: lesson.code,+ title: lesson.title,+ })),+ outOfScope: domain.outOfScope,+ title: domain.title,+ })),+ );++ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const raw = await ai.generateObject(+ {+ messages: [+ {+ content:+ 'You maintain evidence-backed expertise from real conversations. First apply each domainFilter and outOfScope literally. If a conversation does not match, return matches=false and no observations. For a match, map concrete evidence to an existing lesson when its judgment is the same; otherwise propose one reusable lesson. Do not turn implementation trivia or a one-off fact into a lesson. Use only declared layer keys. Keep evidence short and grounded in the supplied conversation.',+ role: 'system',+ },+ {+ content: `DOMAINS\n${JSON.stringify(domains)}\n\nTOPIC CONTEXT (bounded at this completed turn)\n${context}`,+ role: 'user',+ },+ ],+ ...modelConfig,+ schema: ANALYSIS_JSON_SCHEMA,+ },+ {+ metadata: { trigger: 'expertise_topic_ingestion' },+ tracing: {+ agentId: input.agentId,+ promptVersion: PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicAutoSummary,+ schemaName: ANALYSIS_JSON_SCHEMA.name,+ topicId: input.topicId,+ },+ },+ );+ const analysis = AnalysisSchema.parse(raw);+ let ingested = 0;++ for (const result of analysis.domains) {+ const domain = domains.find((item) => item.id === result.domainId);+ if (!domain || !result.matches) continue;+ await this.persistDomainRun({+ ...input,+ domain,+ hadHumanInLoop: topicContext.hadHumanInLoop,+ observations: result.observations,+ });+ ingested += 1;+ }++ return { ingested, reason: ingested > 0 ? 'matched' : 'no-match' } as const;+ };++ private readTopicContext = async (topicId: string) => {+ const rows = await this.db.query.messages.findMany({+ columns: { content: true, createdAt: true, role: true },+ limit: MAX_CONTEXT_MESSAGES,+ orderBy: [desc(messages.createdAt)],+ where: and(+ this.workspaceId+ ? eq(messages.workspaceId, this.workspaceId)+ : and(eq(messages.userId, this.userId), isNull(messages.workspaceId)),+ eq(messages.topicId, topicId),+ isNull(messages.threadId),+ ),+ });+ return {+ hadHumanInLoop: rows.some((row) => row.role === 'user'),+ serializedContext: rows+ .reverse()+ .map((row) => `[${row.role}] ${row.content ?? ''}`)+ .join('\n\n'),+ };+ };++ private persistDomainRun = async (+ input: ExpertiseCompletionInput & {+ domain: { id: string; lessons: Array<{ code: string; title: string }> };+ observations: z.infer<typeof AnalysisSchema>['domains'][number]['observations'];+ },+ ) => {+ const reflectionKey = input.ingestionKey+ ? `topic:${input.topicId}:${input.ingestionKey}`+ : `topic:${input.topicId}:operation:${input.operationId}`;+ await this.db.transaction(async (tx) => {+ await tx+ .select({ id: expertiseDomains.id })+ .from(expertiseDomains)+ .where(eq(expertiseDomains.id, input.domain.id))+ .for('update');+ const [existingRun] = await tx+ .select({ id: expertiseRuns.id })+ .from(expertiseRuns)+ .where(+ and(+ eq(expertiseRuns.domainId, input.domain.id),+ eq(expertiseRuns.reflectionKey, reflectionKey),+ ),+ )+ .limit(1);+ if (existingRun) return;++ const [prior] = await tx+ .select({ value: max(expertiseRuns.runIndex) })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, input.domain.id));+ const runIndex = (prior?.value ?? 0) + 1;+ const runId = randomUUID();+ let newCount = 0;+ let instanceCount = 0;++ await tx.insert(expertiseRuns).values({+ actorId: input.agentId,+ actorType: 'agent',+ completedAt: new Date(),+ domainId: input.domain.id,+ hadHumanInLoop: input.hadHumanInLoop ?? false,+ id: runId,+ reflectionKey,+ runIndex,+ subjectId: input.topicId,+ subjectType: 'topic',+ userId: this.userId,+ workspaceId: this.workspaceId,+ });++ const persistedCodes = await tx+ .select({ code: expertiseLessons.code })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, input.domain.id));+ let nextCodeNumber =+ Math.max(0, ...persistedCodes.map(({ code }) => Number(/^P-(\d+)$/.exec(code)?.[1] ?? 0))) ++ 1;+ const countedLessonIds = new Set<string>();++ for (const observation of input.observations) {+ let lesson = observation.existingCode+ ? input.domain.lessons.find((item) => item.code === observation.existingCode)+ : undefined;+ if (!lesson) {+ newCount += 1;+ const lessonId = randomUUID();+ const code = `P-${String(nextCodeNumber++).padStart(2, '0')}`;+ await tx.insert(expertiseLessons).values({+ code,+ createdByUserId: this.userId,+ domainId: input.domain.id,+ id: lessonId,+ exampleCount: 1,+ hitCount: 1,+ hitRunCount: 1,+ layer: observation.layer,+ lastHitAt: new Date(),+ lastHitRunId: runId,+ originRunId: runId,+ polarity: 'rule',+ sections: [+ { body: observation.title, key: 'rule' },+ { body: observation.reasoning, key: 'why' },+ { body: observation.example, key: 'how' },+ ],+ title: observation.title,+ });+ lesson = { code, title: observation.title };+ countedLessonIds.add(lessonId);+ input.domain.lessons.push(lesson);+ await tx.insert(expertiseHits).values({+ domainId: input.domain.id,+ example: observation.example,+ lessonId,+ note: observation.reasoning,+ operationId: input.operationId,+ outcome: observation.outcome,+ runId,+ });+ } else {+ instanceCount += 1;+ const [row] = await tx+ .select({ id: expertiseLessons.id })+ .from(expertiseLessons)+ .where(+ and(+ eq(expertiseLessons.domainId, input.domain.id),+ eq(expertiseLessons.code, lesson.code),+ ),+ )+ .limit(1);+ if (!row) continue;+ await tx.insert(expertiseHits).values({+ domainId: input.domain.id,+ example: observation.example,+ lessonId: row.id,+ note: observation.reasoning,+ operationId: input.operationId,+ outcome: observation.outcome,+ runId,+ });+ const firstHitThisRun = !countedLessonIds.has(row.id);+ countedLessonIds.add(row.id);+ await tx+ .update(expertiseLessons)+ .set({+ exampleCount: sql`${expertiseLessons.exampleCount} + 1`,+ hitCount: sql`${expertiseLessons.hitCount} + 1`,+ hitRunCount: firstHitThisRun+ ? sql`${expertiseLessons.hitRunCount} + 1`+ : expertiseLessons.hitRunCount,+ lastHitAt: new Date(),+ lastHitRunId: runId,+ })+ .where(eq(expertiseLessons.id, row.id));+ }+ }++ await tx+ .update(expertiseRuns)+ .set({ instanceCount, newCount })+ .where(eq(expertiseRuns.id, runId));++ const [counts] = await tx+ .select({+ active: sql<number>`count(*) filter (where ${expertiseLessons.status} = 'active')::int`,+ compiled: sql<number>`count(*) filter (where ${expertiseLessons.compiledCriterionId} is not null)::int`,+ retired: sql<number>`count(*) filter (where ${expertiseLessons.status} = 'retired')::int`,+ })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, input.domain.id));+ const layerRows = await tx+ .select({ layer: expertiseLessons.layer, value: sql<number>`count(*)::int` })+ .from(expertiseLessons)+ .where(+ and(+ eq(expertiseLessons.domainId, input.domain.id),+ eq(expertiseLessons.status, 'active'),+ ),+ )+ .groupBy(expertiseLessons.layer)+ .orderBy(asc(expertiseLessons.layer));++ await tx.insert(expertiseDomainSnapshots).values({+ activeCount: counts?.active ?? 0,+ compiledCount: counts?.compiled ?? 0,+ domainId: input.domain.id,+ layerCounts: Object.fromEntries(+ layerRows.filter((row) => row.layer).map((row) => [row.layer!, row.value]),+ ),+ learnedTotal: (counts?.active ?? 0) + (counts?.retired ?? 0),+ retiredTotal: counts?.retired ?? 0,+ runId,+ runIndex,+ });+ });+ };+}diff --git a/apps/server/src/workflows/expertiseHistory/index.ts b/apps/server/src/workflows/expertiseHistory/index.tsnew file mode 100644index 00000000000..22ad62d5e68--- /dev/null+++ b/apps/server/src/workflows/expertiseHistory/index.ts@@ -0,0 +1,69 @@+import debug from 'debug';++import { appEnv } from '@/envs/app';++import { runExpertiseHistoryWorkflow } from './run';+import type {+ ExpertiseHistoryTopicWorkflowPayload,+ ExpertiseHistoryWorkflowPayload,+} from './types';++const log = debug('lobe-server:workflows:expertise-history');+const localRuns = new Map<string, Promise<void>>();++export class ExpertiseHistoryWorkflow {+ static async trigger(payload: ExpertiseHistoryWorkflowPayload) {+ const runId = `expertise-history-${payload.userId}-${payload.agentId}-${Date.now()}`;+ if (!appEnv.enableQueueAgentRuntime) {+ const key = `${payload.userId}:${payload.workspaceId ?? 'personal'}:${payload.agentId}`;+ const previous = localRuns.get(key) ?? Promise.resolve();+ const current = previous+ .catch(() => undefined)+ .then(() => new Promise<void>((resolve) => setTimeout(resolve, 0)))+ .then(async () => {+ try {+ const { getServerDB } = await import('@/database/server');+ const { ExpertiseIngestionService } =+ await import('@/server/services/expertise/ingestion');+ const db = await getServerDB();+ await new ExpertiseIngestionService(+ db,+ payload.userId,+ payload.workspaceId,+ ).ingestHistory(payload.agentId);+ } catch (error) {+ log('Local historical ingestion failed error=%O', error);+ }+ });+ localRuns.set(key, current);+ void current.finally(() => localRuns.get(key) === current && localRuns.delete(key));+ return { workflowRunId: `local-${runId}` };+ }++ const baseUrl = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;+ if (!baseUrl) throw new Error('INTERNAL_APP_URL or APP_URL is required');+ const { workflowClient } = await import('@/libs/qstash');+ return workflowClient.trigger({+ body: payload,+ flowControl: {+ key: `expertise-history.${payload.userId}.${payload.agentId}`,+ parallelism: 1,+ },+ url: new URL('/api/workflows/expertise-history/run', baseUrl).toString(),+ });+ }++ static async triggerTopic(payload: ExpertiseHistoryTopicWorkflowPayload) {+ const baseUrl = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;+ if (!baseUrl) throw new Error('INTERNAL_APP_URL or APP_URL is required');+ const { workflowClient } = await import('@/libs/qstash');+ return workflowClient.trigger({+ body: payload,+ flowControl: { key: 'expertise-history-topics', parallelism: 5 },+ url: new URL('/api/workflows/expertise-history/topic', baseUrl).toString(),+ });+ }+}++export { runExpertiseHistoryWorkflow };+export type { ExpertiseHistoryTopicWorkflowPayload, ExpertiseHistoryWorkflowPayload };diff --git a/apps/server/src/workflows/expertiseHistory/run.ts b/apps/server/src/workflows/expertiseHistory/run.tsnew file mode 100644index 00000000000..f7886b8acf8--- /dev/null+++ b/apps/server/src/workflows/expertiseHistory/run.ts@@ -0,0 +1,53 @@+import type { WorkflowContext } from '@upstash/workflow';++import { getServerDB } from '@/database/server';+import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import { runStep } from '@/server/workflows/step';++import { ExpertiseHistoryWorkflow } from '.';+import type { ExpertiseHistoryWorkflowPayload } from './types';++export const runExpertiseHistoryWorkflow = async (+ context: WorkflowContext<ExpertiseHistoryWorkflowPayload>,+) => {+ const payload = context.requestPayload;+ const topics = await runStep(context, 'expertise-history:list-topics', async () => {+ const db = await getServerDB();+ return new ExpertiseIngestionService(+ db,+ payload.userId,+ payload.workspaceId,+ ).listHistoricalTopics(payload.agentId, {+ cursor: payload.cursor+ ? {+ lastActivityAt: new Date(payload.cursor.lastActivityAt),+ topicId: payload.cursor.topicId,+ }+ : undefined,+ limit: 50,+ });+ });++ for (const topic of topics) {+ await runStep(context, `expertise-history:schedule:${topic.topicId}`, () =>+ ExpertiseHistoryWorkflow.triggerTopic({+ agentId: payload.agentId,+ topicId: topic.topicId,+ userId: payload.userId,+ workspaceId: payload.workspaceId,+ }),+ );+ }++ const last = topics.at(-1);+ if (topics.length === 50 && last?.lastActivityAt) {+ await runStep(context, `expertise-history:next:${last.topicId}`, () =>+ ExpertiseHistoryWorkflow.trigger({+ ...payload,+ cursor: { lastActivityAt: String(last.lastActivityAt), topicId: last.topicId },+ }),+ );+ }++ return { scanned: topics.length };+};diff --git a/apps/server/src/workflows/expertiseHistory/topic.ts b/apps/server/src/workflows/expertiseHistory/topic.tsnew file mode 100644index 00000000000..e8ccd03d2cc--- /dev/null+++ b/apps/server/src/workflows/expertiseHistory/topic.ts@@ -0,0 +1,21 @@+import type { WorkflowContext } from '@upstash/workflow';++import { getServerDB } from '@/database/server';+import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import { runStep } from '@/server/workflows/step';++import type { ExpertiseHistoryTopicWorkflowPayload } from './types';++export const runExpertiseHistoryTopicWorkflow = async (+ context: WorkflowContext<ExpertiseHistoryTopicWorkflowPayload>,+) => {+ const payload = context.requestPayload;+ return runStep(context, `expertise-history:topic:${payload.topicId}`, async () => {+ const db = await getServerDB();+ return new ExpertiseIngestionService(+ db,+ payload.userId,+ payload.workspaceId,+ ).ingestHistoricalTopic(payload.agentId, payload.topicId);+ });+};diff --git a/apps/server/src/workflows/expertiseHistory/types.ts b/apps/server/src/workflows/expertiseHistory/types.tsnew file mode 100644index 00000000000..af0c0c83662--- /dev/null+++ b/apps/server/src/workflows/expertiseHistory/types.ts@@ -0,0 +1,13 @@+export interface ExpertiseHistoryWorkflowPayload {+ agentId: string;+ cursor?: { lastActivityAt: string; topicId: string };+ userId: string;+ workspaceId?: string;+}++export interface ExpertiseHistoryTopicWorkflowPayload {+ agentId: string;+ topicId: string;+ userId: string;+ workspaceId?: string;+}diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 15b2336d72c..a0759be8a7b 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -200,6 +200,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleconnector: 'blocked',device: 'blocked',document: rw('knowledge:read', 'knowledge:write'),+ expertise: rw('agent:read', 'agent:write'),// whole-account backup dump (settings incl. market tokens, providers, agents)exporter: 'blocked',file: rw('file:read', 'file:write'),diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.tsnew file mode 100644index 00000000000..f74cb1027d2--- /dev/null+++ b/packages/database/src/models/__tests__/expertise.test.ts@@ -0,0 +1,205 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ agents,+ expertiseBindings,+ expertiseDomains,+ expertiseHits,+ expertiseInsights,+ expertiseLessons,+ expertiseRuns,+ topics,+ users,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ExpertiseModel } from '../expertise';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'expertise-model-test-user';+const runId = '6432288d-281b-4ffa-839f-8e8f45502f57';+const lessonId = '7e21f858-688d-4a20-9866-51a256f2154a';+const hitId = 'f72c127c-9fc5-4122-8824-8955c6520c03';++describe('ExpertiseModel', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('returns the source topic title for a lesson hit', async () => {+ await serverDB.insert(topics).values({+ id: 'expertise-source-topic',+ title: 'æŽ’æŸ¥ç”Ÿäº§çŽ¯å¢ƒè¿žæŽ¥æ± è¶…æ—¶',+ userId,+ });+ await serverDB.insert(expertiseDomains).values({+ domainFilter: '生产故障排查',+ id: 'expertise-test-domain',+ slug: 'expertise-test-domain',+ title: '生产故障排查',+ userId,+ });+ await serverDB.insert(expertiseRuns).values({+ actorId: 'agent-1',+ actorType: 'agent',+ domainId: 'expertise-test-domain',+ id: runId,+ runIndex: 1,+ subjectId: 'expertise-source-topic',+ subjectType: 'topic',+ userId,+ });+ await serverDB.insert(expertiseLessons).values({+ code: 'P-01',+ domainId: 'expertise-test-domain',+ id: lessonId,+ polarity: 'rule',+ sections: [{ body: 'å…ˆçœ‹è¿žæŽ¥æ± æŒ‡æ ‡', key: 'rule' }],+ title: 'å…ˆçœ‹è¿žæŽ¥æ± æŒ‡æ ‡',+ });+ await serverDB.insert(expertiseHits).values({+ domainId: 'expertise-test-domain',+ id: hitId,+ lessonId,+ outcome: 'pass',+ runId,+ });++ const [hit] = await new ExpertiseModel(serverDB, userId).listLessonHits(lessonId);++ expect(hit.runTitle).toBe('æŽ’æŸ¥ç”Ÿäº§çŽ¯å¢ƒè¿žæŽ¥æ± è¶…æ—¶');+ expect(hit.subjectId).toBe('expertise-source-topic');+ });++ it('does not resolve domains through an agent owned by another user', async () => {+ const foreignUserId = 'expertise-foreign-user';+ await serverDB.insert(users).values({ id: foreignUserId });+ await serverDB.insert(agents).values({ id: 'foreign-agent', userId: foreignUserId });+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: 'Foreign domain',+ id: 'foreign-domain',+ slug: 'foreign-domain',+ title: 'Foreign domain',+ userId: foreignUserId,+ });+ await serverDB.insert(expertiseBindings).values({+ agentId: 'foreign-agent',+ domainId: 'foreign-domain',+ });++ await expect(+ new ExpertiseModel(serverDB, userId).listDomainsForAgent('foreign-agent'),+ ).resolves.toEqual([]);+ });++ it('does not expose lesson detail or evidence from another user domain', async () => {+ const foreignUserId = 'expertise-foreign-lesson-user';+ const foreignLessonId = '5c661584-9ee7-49d4-8623-573243f3c51a';+ await serverDB.insert(users).values({ id: foreignUserId });+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: 'Foreign domain',+ id: 'foreign-lesson-domain',+ slug: 'foreign-lesson-domain',+ title: 'Foreign domain',+ userId: foreignUserId,+ });+ await serverDB.insert(expertiseLessons).values({+ code: 'P-01',+ domainId: 'foreign-lesson-domain',+ id: foreignLessonId,+ polarity: 'rule',+ sections: [],+ title: 'Foreign lesson',+ });++ const model = new ExpertiseModel(serverDB, userId);+ await expect(model.findLesson(foreignLessonId)).resolves.toBeUndefined();+ await expect(model.listLessons('foreign-lesson-domain')).resolves.toEqual([]);+ await expect(model.listLessonHits(foreignLessonId)).resolves.toEqual([]);+ });++ it('persists a generated domain definition and resolves its agent binding', async () => {+ await serverDB.insert(agents).values({ id: 'owned-agent', userId });+ const model = new ExpertiseModel(serverDB, userId);++ const domainId = await model.createDomain({+ agentId: 'owned-agent',+ brief: 'Improve production incident diagnosis, excluding general design discussions.',+ domainFilter: 'Include production incident diagnosis and remediation.',+ outOfScope: 'Exclude general design discussions without an incident.',+ title: 'Production incident response',+ });++ const [binding] = await serverDB+ .select()+ .from(expertiseBindings)+ .where(eq(expertiseBindings.domainId, domainId));+ const [resolved] = await model.listDomainsForAgent('owned-agent');++ expect(binding.agentId).toBe('owned-agent');+ expect(resolved.domain).toMatchObject({+ description: 'Improve production incident diagnosis, excluding general design discussions.',+ domainFilter: 'Include production incident diagnosis and remediation.',+ id: domainId,+ outOfScope: 'Exclude general design discussions without an incident.',+ title: 'Production incident response',+ });+ });++ it('keeps cross-domain insights isolated to the active workspace', async () => {+ await serverDB.insert(workspaces).values([+ { id: 'expertise-workspace-1', name: 'Workspace 1', primaryOwnerId: userId, slug: 'ws-1' },+ { id: 'expertise-workspace-2', name: 'Workspace 2', primaryOwnerId: userId, slug: 'ws-2' },+ ]);+ await serverDB.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ domainFilter: 'Workspace domain',+ id: 'workspace-domain-1',+ slug: 'workspace-domain-1',+ title: 'Workspace domain',+ userId,+ workspaceId: 'expertise-workspace-1',+ });+ const workspaceOneInsightId = 'b77316f6-c807-47f0-b3b8-ab9220aca7fb';+ const workspaceTwoInsightId = 'f5976e3b-d445-4359-98c3-92a64bbd0553';+ await serverDB.insert(expertiseInsights).values([+ {+ body: 'Visible in workspace one',+ headline: 'Workspace one insight',+ id: workspaceOneInsightId,+ kind: 'repeated-mistake',+ userId,+ workspaceId: 'expertise-workspace-1',+ },+ {+ body: 'Hidden in workspace one',+ headline: 'Workspace two insight',+ id: workspaceTwoInsightId,+ kind: 'repeated-mistake',+ userId,+ workspaceId: 'expertise-workspace-2',+ },+ ]);++ const model = new ExpertiseModel(serverDB, userId, 'expertise-workspace-1');+ const insights = await model.listInsights(['workspace-domain-1']);+ await model.dismissInsight(workspaceTwoInsightId, 'must remain untouched');+ const [foreignInsight] = await serverDB+ .select({ status: expertiseInsights.status })+ .from(expertiseInsights)+ .where(eq(expertiseInsights.id, workspaceTwoInsightId));++ expect(insights.map(({ id }) => id)).toEqual([workspaceOneInsightId]);+ expect(foreignInsight.status).toBe('active');+ });+});diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.tsnew file mode 100644index 00000000000..969046366cd--- /dev/null+++ b/packages/database/src/models/expertise.ts@@ -0,0 +1,349 @@+import { and, asc, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';++import {+ agents,+ expertiseBindings,+ expertiseDomains,+ expertiseDomainSnapshots,+ expertiseHits,+ expertiseInsights,+ expertiseLessons,+ expertiseRuns,+ topics,+} from '../schemas';+import type { LobeChatDatabase } from '../type';+import { idGenerator } from '../utils/idGenerator';+import { buildWorkspaceWhere } from '../utils/workspace';++/** The core tier starts at 40% of the domain's maximum hit count, with a floor of two. */+const CORE_CUT_RATIO = 0.4;+const CORE_CUT_MIN = 2;++export type ExpertiseTier = 'core' | 'niche' | 'unused';++export class ExpertiseModel {+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private scopeWhere = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, expertiseDomains);++ private insightScopeWhere = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, expertiseInsights);++ // Binding resolution++ /** Lists the agent-level and workspace-level expertise available to one authorized agent. */+ listDomainsForAgent = async (agentId: string) => {+ const [agent] = await this.db+ .select({ id: agents.id })+ .from(agents)+ .where(+ and(+ eq(agents.id, agentId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),+ ),+ )+ .limit(1);+ if (!agent) return [];++ const rows = await this.db+ .select({+ binding: {+ contributionMode: expertiseBindings.contributionMode,+ enabled: expertiseBindings.enabled,+ id: expertiseBindings.id,+ sortOrder: expertiseBindings.sortOrder,+ },+ domain: expertiseDomains,+ })+ .from(expertiseBindings)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseBindings.domainId))+ .where(+ and(+ eq(expertiseBindings.enabled, true),+ isNotNull(expertiseDomains.anchorChosenAt),+ this.scopeWhere(),+ or(+ eq(expertiseBindings.agentId, agentId),+ this.workspaceId+ ? eq(expertiseBindings.boundWorkspaceId, this.workspaceId)+ : eq(expertiseBindings.boundUserId, this.userId),+ ),+ ),+ )+ .orderBy(asc(expertiseBindings.sortOrder));++ // One domain may be bound at multiple levels; retain the first binding by sort order.+ const seen = new Set<string>();+ return rows.filter((r) => {+ if (seen.has(r.domain.id)) return false;+ seen.add(r.domain.id);+ return true;+ });+ };++ // L0: overview++ /** Returns the latest snapshot for every requested domain. */+ latestSnapshots = async (domainIds: string[]) => {+ if (domainIds.length === 0) return [];+ return this.db+ .selectDistinctOn([expertiseDomainSnapshots.domainId])+ .from(expertiseDomainSnapshots)+ .where(inArray(expertiseDomainSnapshots.domainId, domainIds))+ .orderBy(desc(expertiseDomainSnapshots.domainId), desc(expertiseDomainSnapshots.runIndex));+ };++ /** Loads the complete active-lesson series for all requested domains in one query. */+ seriesForDomains = async (domainIds: string[]) => {+ if (domainIds.length === 0) return [];+ return this.db+ .select({+ activeCount: expertiseDomainSnapshots.activeCount,+ domainId: expertiseDomainSnapshots.domainId,+ runIndex: expertiseDomainSnapshots.runIndex,+ })+ .from(expertiseDomainSnapshots)+ .where(inArray(expertiseDomainSnapshots.domainId, domainIds))+ .orderBy(asc(expertiseDomainSnapshots.domainId), asc(expertiseDomainSnapshots.runIndex));+ };++ /** Lists the agents that have practiced each domain. */+ actorsByDomain = async (domainIds: string[]) => {+ if (domainIds.length === 0) return [];+ return this.db+ .selectDistinct({ actorId: expertiseRuns.actorId, domainId: expertiseRuns.domainId })+ .from(expertiseRuns)+ .where(and(inArray(expertiseRuns.domainId, domainIds), eq(expertiseRuns.actorType, 'agent')));+ };++ // L1: domain detail++ findDomain = async (domainId: string) => {+ const [row] = await this.db+ .select()+ .from(expertiseDomains)+ .where(+ and(+ eq(expertiseDomains.id, domainId),+ isNotNull(expertiseDomains.anchorChosenAt),+ this.scopeWhere(),+ ),+ )+ .limit(1);+ return row;+ };++ /** Returns the complete snapshot series for a domain. */+ listSnapshots = async (domainId: string) =>+ this.db+ .select()+ .from(expertiseDomainSnapshots)+ .where(eq(expertiseDomainSnapshots.domainId, domainId))+ .orderBy(asc(expertiseDomainSnapshots.runIndex));++ listRuns = async (domainId: string, limit = 50) =>+ this.db+ .select()+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, domainId))+ .orderBy(desc(expertiseRuns.runIndex))+ .limit(limit);++ /** Counts all runs independently of the paginated run list. */+ countRuns = async (domainId: string) => {+ const [row] = await this.db+ .select({ n: sql<number>`count(*)::int` })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, domainId));+ return row?.n ?? 0;+ };++ /** Returns whether a human participated in each practice run. */+ runHumanFlags = async (domainId: string) =>+ this.db+ .select({+ hadHumanInLoop: expertiseRuns.hadHumanInLoop,+ runIndex: expertiseRuns.runIndex,+ })+ .from(expertiseRuns)+ .where(eq(expertiseRuns.domainId, domainId))+ .orderBy(asc(expertiseRuns.runIndex));++ /** Summarizes active lesson count, hits, and unused lessons. */+ lessonStats = async (domainId: string) => {+ const [row] = await this.db+ .select({+ hits: sql<number>`coalesce(sum(${expertiseLessons.hitCount}), 0)::int`,+ total: sql<number>`count(*)::int`,+ unused: sql<number>`count(*) filter (where ${expertiseLessons.hitCount} = 0)::int`,+ })+ .from(expertiseLessons)+ .where(and(eq(expertiseLessons.domainId, domainId), eq(expertiseLessons.status, 'active')));+ return row ?? { hits: 0, total: 0, unused: 0 };+ };++ // L2: lesson library++ /** Lists active lessons by hit count and assigns their usage tier. */+ listLessons = async (domainId: string, opts?: { layer?: string; search?: string }) => {+ const conditions = [+ eq(expertiseLessons.domainId, domainId),+ eq(expertiseLessons.status, 'active'),+ ];+ if (opts?.layer) conditions.push(eq(expertiseLessons.layer, opts.layer));+ if (opts?.search) {+ conditions.push(sql`${expertiseLessons.title} ILIKE ${`%${opts.search}%`}`);+ }++ const rows = await this.db+ .select({ lesson: expertiseLessons })+ .from(expertiseLessons)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))+ .where(and(...conditions, this.scopeWhere()))+ .orderBy(desc(expertiseLessons.hitCount), asc(expertiseLessons.code));++ const lessons = rows.map(({ lesson }) => lesson);++ const maxHit = lessons.reduce((a, r) => Math.max(a, r.hitCount), 0);+ const cut = Math.max(CORE_CUT_MIN, Math.round(maxHit * CORE_CUT_RATIO));++ return lessons.map((r) => ({+ ...r,+ tier: (r.hitCount >= cut ? 'core' : r.hitCount > 0 ? 'niche' : 'unused') as ExpertiseTier,+ }));+ };++ /** Counts active lessons by declared layer. */+ layerCounts = async (domainId: string) => {+ const rows = await this.db+ .select({ layer: expertiseLessons.layer, n: sql<number>`count(*)::int` })+ .from(expertiseLessons)+ .where(and(eq(expertiseLessons.domainId, domainId), eq(expertiseLessons.status, 'active')))+ .groupBy(expertiseLessons.layer);+ return Object.fromEntries(rows.filter((r) => r.layer).map((r) => [r.layer!, r.n]));+ };++ /** Counts active lessons by canon anchor, including unanchored lessons. */+ canonAnchorCounts = async (domainId: string) => {+ const rows = await this.db+ .select({ anchor: expertiseLessons.canonAnchor, n: sql<number>`count(*)::int` })+ .from(expertiseLessons)+ .where(and(eq(expertiseLessons.domainId, domainId), eq(expertiseLessons.status, 'active')))+ .groupBy(expertiseLessons.canonAnchor);+ return {+ byKey: Object.fromEntries(rows.filter((r) => r.anchor).map((r) => [r.anchor!, r.n])),+ unanchored: rows.find((r) => !r.anchor)?.n ?? 0,+ };+ };++ // L3: lesson detail++ findLesson = async (lessonId: string) => {+ const [row] = await this.db+ .select({ lesson: expertiseLessons })+ .from(expertiseLessons)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseLessons.domainId))+ .where(and(eq(expertiseLessons.id, lessonId), this.scopeWhere()))+ .limit(1);+ return row?.lesson;+ };++ /** Lists lesson evidence together with its source run and topic. */+ listLessonHits = async (lessonId: string, limit = 20) =>+ this.db+ .select({+ createdAt: expertiseHits.createdAt,+ example: expertiseHits.example,+ note: expertiseHits.note,+ outcome: expertiseHits.outcome,+ runIndex: expertiseRuns.runIndex,+ runTitle: sql<string>`coalesce(${topics.title}, ${expertiseRuns.subjectId})`,+ severity: expertiseHits.severity,+ subjectId: expertiseRuns.subjectId,+ subjectType: expertiseRuns.subjectType,+ where: expertiseHits.where,+ })+ .from(expertiseHits)+ .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseHits.domainId))+ .leftJoin(+ topics,+ and(eq(expertiseRuns.subjectType, 'topic'), eq(topics.id, expertiseRuns.subjectId)),+ )+ .where(and(eq(expertiseHits.lessonId, lessonId), this.scopeWhere()))+ .orderBy(desc(expertiseHits.createdAt))+ .limit(limit);++ // Writes++ /** Persists a model-generated domain definition and binds it to the selected agent. */+ createDomain = async (params: {+ agentId: string;+ brief: string;+ domainFilter: string;+ outOfScope?: string;+ title: string;+ }) => {+ const brief = params.brief.trim();+ const id = idGenerator('expertiseDomains');+ const title = params.title.trim();+ const domainFilter = params.domainFilter.trim();+ const slug = `${title.slice(0, 40).replaceAll(/\s+/g, '-').toLowerCase()}-${id.slice(-6)}`;++ await this.db.transaction(async (tx) => {+ await tx.insert(expertiseDomains).values({+ anchorChosenAt: new Date(),+ anchorChosenByUserId: this.userId,+ description: brief,+ domainFilter,+ outOfScope: params.outOfScope?.trim() || null,+ id,+ seedState: 'seeded',+ slug,+ title,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ await tx.insert(expertiseBindings).values({+ addedByUserId: this.userId,+ agentId: params.agentId,+ domainId: id,+ workspaceId: this.workspaceId,+ });+ });+ return id;+ };++ // Insights++ listInsights = async (domainIds: string[]) => {+ if (domainIds.length === 0) return [];+ return this.db+ .select()+ .from(expertiseInsights)+ .where(+ and(+ or(inArray(expertiseInsights.domainId, domainIds), isNull(expertiseInsights.domainId)),+ eq(expertiseInsights.status, 'active'),+ this.insightScopeWhere(),+ ),+ )+ .orderBy(desc(expertiseInsights.confidence))+ .limit(10);+ };++ dismissInsight = async (insightId: string, reason?: string) =>+ this.db+ .update(expertiseInsights)+ .set({ dismissReason: reason, status: 'dismissed', updatedAt: new Date() })+ .where(and(eq(expertiseInsights.id, insightId), this.insightScopeWhere()));+}