π€― 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(metric): add MetricModel and the metric TRPC router (#19071)
Arvin Xu3a9527be398c
diff --git a/apps/server/src/routers/lambda/__tests__/metric.test.ts b/apps/server/src/routers/lambda/__tests__/metric.test.tsnew file mode 100644index 00000000000..aefeb05f3ce--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/metric.test.ts@@ -0,0 +1,196 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ return { wsCompatProcedure: authedProcedure };+});++const mockModel = {+ addPoint: vi.fn(),+ delete: vi.fn(),+ ensure: vi.fn(),+ findById: vi.fn(),+ findBySubject: vi.fn(),+ latestPoint: vi.fn(),+ listPoints: vi.fn(),+ update: vi.fn(),+};++vi.mock('@/database/models/metric', () => ({+ MetricModel: vi.fn(() => mockModel),+}));++const mockGoalFindById = vi.fn();+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({ findById: mockGoalFindById })),+}));+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(() => ({ existsById: vi.fn().mockResolvedValue(false) })),+}));+vi.mock('@/database/models/project', () => ({+ ProjectModel: vi.fn(() => ({ findById: vi.fn().mockResolvedValue(null) })),+}));+vi.mock('@/database/models/task', () => ({+ TaskModel: vi.fn(() => ({ findById: vi.fn().mockResolvedValue(null) })),+}));++const { metricRouter } = await import('../metric');++describe('metricRouter', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' };+ const caller = metricRouter.createCaller(ctx);++ const visibleSeries = { id: 'mtr_1', subjectId: 'goal_1', subjectType: 'goal', userId: 'user-1' };++ beforeEach(() => {+ vi.clearAllMocks();+ // A metric is exactly as visible as its subject, so every by-id path+ // resolves the series and then re-checks the subject.+ mockModel.findById.mockResolvedValue(visibleSeries);+ mockGoalFindById.mockResolvedValue({ id: 'goal_1' });+ });++ describe('addPoint', () => {+ it('stamps user attribution server-side and defaults observedAt to now', async () => {+ mockModel.addPoint.mockResolvedValue({ id: 'p1' });++ await caller.addPoint({ id: 'mtr_1', value: 42 });++ expect(mockModel.addPoint).toHaveBeenCalledWith('mtr_1', {+ actorId: 'user-1',+ actorType: 'user',+ metadata: undefined,+ observedAt: expect.any(Date),+ sourceType: 'manual',+ value: 42,+ });+ });++ it('maps an unknown series to NOT_FOUND', async () => {+ mockModel.findById.mockResolvedValue(undefined);+ await expect(caller.addPoint({ id: 'mtr_missing', value: 1 })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockModel.addPoint).not.toHaveBeenCalled();+ });+ });++ describe('listPoints', () => {+ it('composes the chart contract from the series definition', async () => {+ mockModel.listPoints.mockResolvedValue({+ points: [{ observedAt: new Date('2026-09-01'), value: 10 }],+ series: {+ config: { target: 100 },+ id: 'mtr_1',+ kind: 'counter',+ title: 'Posts',+ unit: 'count',+ },+ });++ const result = await caller.listPoints({ bucket: 'day', id: 'mtr_1' });++ expect(mockModel.listPoints).toHaveBeenCalledWith('mtr_1', {+ bucket: 'day',+ from: undefined,+ limit: undefined,+ to: undefined,+ });+ expect(result.data).toEqual({+ config: { target: 100 },+ kind: 'counter',+ points: [{ observedAt: new Date('2026-09-01'), value: 10 }],+ title: 'Posts',+ unit: 'count',+ });+ });+ });++ describe('upsertSeries', () => {+ it('rejects a subject the caller cannot see before touching the slot', async () => {+ mockGoalFindById.mockResolvedValue(undefined);++ await expect(+ caller.upsertSeries({ key: 'k', subjectId: 'goal_foreign', subjectType: 'goal' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockModel.ensure).not.toHaveBeenCalled();+ });++ it('maps a foreign-owned slot to CONFLICT', async () => {+ mockGoalFindById.mockResolvedValue({ id: 'goal_1' });+ mockModel.ensure.mockResolvedValue(undefined);+ await expect(+ caller.upsertSeries({ key: 'k', subjectId: 'goal_1', subjectType: 'goal' }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });+ });++ describe('subject visibility on read paths', () => {+ // `metrics` has no visibility column, so in workspace mode the model's+ // ownership filter degrades to a bare workspace_id match β a member could+ // otherwise read the series of a coworker's private agent/task/project.+ it.each([+ ['getSeries', () => caller.getSeries({ id: 'mtr_1' })],+ ['listPoints', () => caller.listPoints({ id: 'mtr_1' })],+ ['addPoint', () => caller.addPoint({ id: 'mtr_1', value: 1 })],+ ['listSeries', () => caller.listSeries({ subjectId: 'goal_1', subjectType: 'goal' })],+ ])('%s refuses a series whose subject the caller cannot see', async (_name, run) => {+ mockGoalFindById.mockResolvedValue(undefined);++ await expect(run()).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockModel.findBySubject).not.toHaveBeenCalled();+ expect(mockModel.listPoints).not.toHaveBeenCalled();+ expect(mockModel.addPoint).not.toHaveBeenCalled();+ });+ });++ describe('updateSeries', () => {+ it('clears nullable definition fields when passed null', async () => {+ // Dropping a target back to "no target" is an edit, not an omission.+ mockModel.update.mockResolvedValue({ ...visibleSeries, config: null });++ await caller.updateSeries({ config: null, id: 'mtr_1', title: null });++ expect(mockModel.update).toHaveBeenCalledWith('mtr_1', { config: null, title: null });+ });++ it('rejects a declared precision the numeric(20, 6) column cannot hold', async () => {+ await expect(+ caller.updateSeries({ config: { precision: 8 }, id: 'mtr_1' }),+ ).rejects.toThrow();+ expect(mockModel.update).not.toHaveBeenCalled();+ });+ });++ describe('workspace creator scope', () => {+ it.each([+ ['updateSeries', () => caller.updateSeries({ id: 'mtr_1', title: 'hijack' })],+ ['deleteSeries', () => caller.deleteSeries({ id: 'mtr_1' })],+ ])('%s refuses a non-owner member mutating a coworker series', async (_name, run) => {+ // Workspace visibility lets the member *read* the series; mutating a row+ // another member created stays FORBIDDEN without the owner role.+ mockModel.findById.mockResolvedValue({ ...visibleSeries, userId: 'coworker' });++ await expect(run()).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockModel.update).not.toHaveBeenCalled();+ expect(mockModel.delete).not.toHaveBeenCalled();+ });++ it('deleteSeries surfaces NOT_FOUND when nothing was deleted', async () => {+ mockModel.delete.mockResolvedValue(undefined);++ await expect(caller.deleteSeries({ id: 'mtr_1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+ });+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex b5d821083a9..5ab8e409e36 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -70,6 +70,7 @@ import { llmGenerationTracingRouter } from './llmGenerationTracing';import { marketRouter } from './market';import { messageRouter } from './message';import { messengerRouter } from './messenger';+import { metricRouter } from './metric';import { notebookRouter } from './notebook';import { notificationRouter } from './notification';import { oauthAppRouter } from './oauthApp';@@ -154,6 +155,7 @@ export const lambdaRouter = router({market: marketRouter,message: messageRouter,messenger: messengerRouter,+ metric: metricRouter,notebook: notebookRouter,notification: notificationRouter,oauthApp: oauthAppRouter,diff --git a/apps/server/src/routers/lambda/metric.ts b/apps/server/src/routers/lambda/metric.tsnew file mode 100644index 00000000000..3a863f625bc--- /dev/null+++ b/apps/server/src/routers/lambda/metric.ts@@ -0,0 +1,284 @@+import type { MetricSubjectType } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { AgentModel } from '@/database/models/agent';+import { GoalModel } from '@/database/models/goal';+import { MetricModel } from '@/database/models/metric';+import { ProjectModel } from '@/database/models/project';+import { TaskModel } from '@/database/models/task';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';++const metricProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>+ opts.next({+ ctx: {+ metricModel: new MetricModel(+ opts.ctx.serverDB,+ opts.ctx.userId,+ opts.ctx.workspaceId ?? undefined,+ ),+ },+ }),+);+const metricWriteProcedure = metricProcedure.use(withScopedPermission('agent:update'));++const idInput = z.object({ id: z.string() });+const subjectInput = z.object({+ subjectId: z.string(),+ subjectType: z.enum(['goal', 'task', 'agent', 'project', 'workspace']),+});+const configSchema = z.object({+ direction: z.enum(['higher_is_better', 'lower_is_better']).optional(),+ // Values persist in numeric(20, 6); a higher declared precision would be+ // a promise the column silently rounds away.+ precision: z.number().int().min(0).max(6).optional(),+ sampleIntervalHint: z.string().optional(),+ target: z.number().optional(),+});+const definitionFields = {+ config: configSchema.optional(),+ metadata: z.record(z.string(), z.unknown()).optional(),+ title: z.string().optional(),+ unit: z.string().optional(),+};+// These columns are nullable, so a patch must be able to clear them β dropping+// a target back to "no target" is an edit, not an omission. Omitted still+// means "leave as is"; explicit null means "unset".+const patchableDefinitionFields = {+ config: configSchema.nullable().optional(),+ metadata: z.record(z.string(), z.unknown()).nullable().optional(),+ title: z.string().nullable().optional(),+ unit: z.string().nullable().optional(),+};++function mapMetricError(error: unknown, operation: string): never {+ if (error instanceof TRPCError) throw error;+ console.error(`[metric:${operation}]`, error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: `Failed to ${operation} metric`,+ });+}++const notFound = () => new TRPCError({ code: 'NOT_FOUND', message: 'Metric series not found' });++/**+ * A metric is telemetry *about* its subject, so it is exactly as visible as+ * that subject β the invariant every path here enforces.+ *+ * It has to be enforced here because the link is polymorphic with no FK and+ * `metrics` carries no `visibility` column of its own: in workspace mode+ * `buildWorkspaceWhere` degrades to a bare `workspace_id` match, which would+ * otherwise let any member read (or write) the series of a coworker's private+ * agent, task or project. On the write side it additionally stops a caller+ * minting series against arbitrary ids β durable dangling rows, and because+ * (subject_type, subject_id, key) is globally unique, a reserved slot the+ * legitimate owner could never claim.+ */+const assertSubjectVisible = async (+ db: LobeChatDatabase,+ ctx: { userId: string; workspaceId?: string | null },+ subjectType: MetricSubjectType,+ subjectId: string,+): Promise<void> => {+ const workspaceId = ctx.workspaceId ?? undefined;+ const visible = await (() => {+ switch (subjectType) {+ case 'agent': {+ return new AgentModel(db, ctx.userId, workspaceId).existsById(subjectId);+ }+ case 'goal': {+ return new GoalModel(db, ctx.userId, workspaceId).findById(subjectId);+ }+ case 'project': {+ return new ProjectModel(db, ctx.userId, workspaceId).findById(subjectId);+ }+ case 'task': {+ return new TaskModel(db, ctx.userId, workspaceId).findById(subjectId);+ }+ case 'workspace': {+ return workspaceId === subjectId;+ }+ }+ })();+ if (!visible)+ throw new TRPCError({ code: 'NOT_FOUND', message: `Metric subject not found: ${subjectType}` });+};++/**+ * Load a series for a by-id path and re-check its subject: the series row+ * alone proves only workspace membership, not that the caller may see what it+ * measures. Doubles as orphan protection β a series whose subject was deleted+ * stops resolving instead of lingering as readable, writable telemetry.+ */+const requireVisibleSeries = async (+ db: LobeChatDatabase,+ ctx: { metricModel: MetricModel; userId: string; workspaceId?: string | null },+ id: string,+) => {+ const series = await ctx.metricModel.findById(id);+ if (!series) throw notFound();+ await assertSubjectVisible(db, ctx, series.subjectType, series.subjectId);+ return series;+};++export const metricRouter = router({+ /**+ * Append one observation. Actor attribution is server-set β a TRPC caller is+ * always the authenticated user; probe runs write through their own service+ * path with `system` attribution.+ */+ addPoint: metricWriteProcedure+ .input(+ idInput.extend({+ metadata: z.record(z.string(), z.unknown()).optional(),+ observedAt: z.coerce.date().optional(),+ sourceType: z.enum(['manual', 'api']).default('manual'),+ value: z.number(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ const point = await ctx.metricModel.addPoint(input.id, {+ actorId: ctx.userId,+ actorType: 'user',+ metadata: input.metadata,+ observedAt: input.observedAt ?? new Date(),+ sourceType: input.sourceType,+ value: input.value,+ });+ if (!point) throw notFound();+ return { data: point, message: 'Point recorded', success: true };+ } catch (error) {+ mapMetricError(error, 'addPoint');+ }+ }),++ deleteSeries: metricWriteProcedure.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ const series = await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ // Workspace visibility lets any member read the series; deleting it (and+ // cascading every observation) stays with the creator or an owner.+ assertWorkspaceRowManageable(ctx, series.userId, 'metric series');+ const deleted = await ctx.metricModel.delete(input.id);+ if (!deleted) throw notFound();+ return { message: 'Series deleted', success: true };+ } catch (error) {+ mapMetricError(error, 'deleteSeries');+ }+ }),++ /** Series definition plus its latest observation β the "current value" read. */+ getSeries: metricProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const series = await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ const latest = await ctx.metricModel.latestPoint(series.id);+ return { data: { ...series, latestPoint: latest ?? null }, success: true };+ } catch (error) {+ mapMetricError(error, 'getSeries');+ }+ }),++ /**+ * The chart read: raw or bucket-aggregated points together with the render+ * contract (kind / unit / config / title), so one call feeds a chart.+ */+ listPoints: metricProcedure+ .input(+ idInput.extend({+ bucket: z.enum(['hour', 'day', 'week', 'month']).optional(),+ from: z.coerce.date().optional(),+ limit: z.number().int().min(1).max(10_000).optional(),+ to: z.coerce.date().optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ try {+ await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ const result = await ctx.metricModel.listPoints(input.id, {+ bucket: input.bucket,+ from: input.from,+ limit: input.limit,+ to: input.to,+ });+ if (!result) throw notFound();+ const { points, series } = result;+ return {+ data: {+ config: series.config,+ kind: series.kind,+ points,+ title: series.title,+ unit: series.unit,+ },+ success: true,+ };+ } catch (error) {+ mapMetricError(error, 'listPoints');+ }+ }),++ listSeries: metricProcedure.input(subjectInput).query(async ({ input, ctx }) => {+ try {+ await assertSubjectVisible(ctx.serverDB, ctx, input.subjectType, input.subjectId);+ const data = await ctx.metricModel.findBySubject(input.subjectType, input.subjectId);+ return { data, success: true };+ } catch (error) {+ mapMetricError(error, 'listSeries');+ }+ }),++ updateSeries: metricWriteProcedure+ .input(+ idInput.extend({+ ...patchableDefinitionFields,+ kind: z.enum(['gauge', 'counter']).optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const { id, ...patch } = input;+ const existing = await requireVisibleSeries(ctx.serverDB, ctx, id);+ // Definition edits rewrite the render/evaluation contract for everyone+ // reading the series β creator or workspace owner only.+ assertWorkspaceRowManageable(ctx, existing.userId, 'metric series');+ const series = await ctx.metricModel.update(id, patch);+ if (!series) throw notFound();+ return { data: series, message: 'Series updated', success: true };+ } catch (error) {+ mapMetricError(error, 'updateSeries');+ }+ }),++ /** Idempotent create β existing definition fields are never overwritten. */+ upsertSeries: metricWriteProcedure+ .input(+ subjectInput.extend({+ ...definitionFields,+ key: z.string().min(1).max(255),+ kind: z.enum(['gauge', 'counter']).optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ await assertSubjectVisible(ctx.serverDB, ctx, input.subjectType, input.subjectId);+ const series = await ctx.metricModel.ensure(input);+ if (!series)+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'Metric series slot is owned by another scope',+ });+ return { data: series, message: 'Series ready', success: true };+ } catch (error) {+ mapMetricError(error, 'upsertSeries');+ }+ }),+});diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 96fed949b27..d9a8bb7dd60 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -238,6 +238,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRulemessage: rw('chat:read', 'chat:write'),// IM channel management carries channel credentialsmessenger: 'blocked',+ // numeric telemetry attached to a goal / agent / task / project β same+ // domain as the subjects that own it+ metric: rw('agent:read', 'agent:write'),notebook: rw('knowledge:read', 'knowledge:write'),notification: rw('user:read', 'user:write'),oauthApp: 'blocked',diff --git a/packages/database/src/models/__tests__/metric.test.ts b/packages/database/src/models/__tests__/metric.test.tsnew file mode 100644index 00000000000..10c3cac8206--- /dev/null+++ b/packages/database/src/models/__tests__/metric.test.ts@@ -0,0 +1,213 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { MetricModel } from '../metric';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'metric-model-test-user';+const otherUserId = 'metric-model-other-user';+const model = new MetricModel(serverDB, userId);+const otherModel = new MetricModel(serverDB, otherUserId);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++const seed = (key = 'twitter.followers') =>+ model.ensure({ key, subjectId: 'goal_metric_test', subjectType: 'goal' });++describe('MetricModel', () => {+ describe('ensure', () => {+ it('creates the series once and returns the existing row on repeat', async () => {+ const first = await seed();+ const again = await model.ensure({+ key: 'twitter.followers',+ subjectId: 'goal_metric_test',+ subjectType: 'goal',+ // Racing probe passes a different title β ensure must not overwrite.+ title: 'Should not stick',+ });++ expect(first?.id).toMatch(/^mtr_/);+ expect(again?.id).toBe(first?.id);+ expect(again?.title).toBeNull();+ });++ it('does not surface a slot owned by another user', async () => {+ await seed();+ const stolen = await otherModel.ensure({+ key: 'twitter.followers',+ subjectId: 'goal_metric_test',+ subjectType: 'goal',+ });+ expect(stolen).toBeUndefined();+ });+ });++ describe('series reads and writes', () => {+ it('lists a subject ordered by key and scopes reads to the owner', async () => {+ await seed('b.metric');+ await seed('a.metric');++ const listed = await model.findBySubject('goal', 'goal_metric_test');+ expect(listed.map((s) => s.key)).toEqual(['a.metric', 'b.metric']);+ expect(await otherModel.findBySubject('goal', 'goal_metric_test')).toEqual([]);+ });++ it('updates definition fields under ownership only', async () => {+ const series = (await seed())!;++ const patched = await model.update(series.id, { title: 'Followers', unit: 'count' });+ expect(patched).toMatchObject({ title: 'Followers', unit: 'count' });++ expect(await otherModel.update(series.id, { title: 'hijack' })).toBeUndefined();+ expect((await model.findById(series.id))?.title).toBe('Followers');+ });+ });++ describe('points', () => {+ it('appends through the owned series and refuses foreign or missing series', async () => {+ const series = (await seed())!;++ const point = await model.addPoint(series.id, {+ actorType: 'system',+ observedAt: new Date('2026-09-01T00:00:00Z'),+ sourceType: 'probe',+ value: 42,+ });+ expect(point).toMatchObject({ metricId: series.id, userId, value: 42 });++ expect(+ await otherModel.addPoint(series.id, {+ actorType: 'user',+ observedAt: new Date(),+ sourceType: 'manual',+ value: 1,+ }),+ ).toBeUndefined();+ expect(+ await model.addPoint('mtr_missing', {+ actorType: 'user',+ observedAt: new Date(),+ sourceType: 'manual',+ value: 1,+ }),+ ).toBeUndefined();+ });++ it('reads the latest observation by observed time, not insert order', async () => {+ const series = (await seed())!;+ // Backfill arrives after the fresher sample β observedAt must win.+ await model.addPoint(series.id, {+ actorType: 'system',+ observedAt: new Date('2026-09-02T00:00:00Z'),+ sourceType: 'probe',+ value: 200,+ });+ await model.addPoint(series.id, {+ actorType: 'user',+ observedAt: new Date('2026-09-01T00:00:00Z'),+ sourceType: 'manual',+ value: 100,+ });++ expect((await model.latestPoint(series.id))?.value).toBe(200);+ });+ });++ describe('listPoints', () => {+ const day = (d: number, h = 0) => new Date(Date.UTC(2026, 8, d, h));++ const seedWeek = async (kind: 'gauge' | 'counter') => {+ const series = (await model.ensure({+ key: `series.${kind}`,+ kind,+ subjectId: 'goal_metric_test',+ subjectType: 'goal',+ }))!;+ // Two samples on Sep 1, one on Sep 2.+ for (const [at, value] of [+ [day(1, 0), 10],+ [day(1, 12), 30],+ [day(2, 0), 20],+ ] as const) {+ await model.addPoint(series.id, {+ actorType: 'system',+ observedAt: at,+ sourceType: 'probe',+ value,+ });+ }+ return series;+ };++ it('returns raw points ascending within the requested range', async () => {+ const series = await seedWeek('gauge');++ const result = await model.listPoints(series.id, { from: day(1, 6), to: day(2, 6) });+ expect(result?.points.map((p) => p.value)).toEqual([30, 20]);+ expect(result?.series.kind).toBe('gauge');+ });++ it('aggregates buckets by the series kind: gauge averages, counter takes max', async () => {+ const gauge = await seedWeek('gauge');+ const counter = await seedWeek('counter');++ const gaugeDays = await model.listPoints(gauge.id, { bucket: 'day' });+ expect(gaugeDays?.points.map((p) => p.value)).toEqual([20, 20]); // avg(10,30), avg(20)++ const counterDays = await model.listPoints(counter.id, { bucket: 'day' });+ expect(counterDays?.points.map((p) => p.value)).toEqual([30, 20]); // max(10,30), max(20)+ expect(counterDays?.points[0]?.observedAt).toEqual(day(1));+ });++ it('returns undefined for a series outside the owner scope', async () => {+ const series = await seedWeek('gauge');+ expect(await otherModel.listPoints(series.id)).toBeUndefined();+ });++ it('keeps the newest window when the limit truncates, still ascending', async () => {+ const series = await seedWeek('gauge');++ const raw = await model.listPoints(series.id, { limit: 2 });+ expect(raw?.points.map((p) => p.value)).toEqual([30, 20]);++ const bucketed = await model.listPoints(series.id, { bucket: 'day', limit: 1 });+ expect(bucketed?.points.map((p) => p.observedAt)).toEqual([day(2)]);+ });+ });++ describe('delete', () => {+ it('cascades points with the series', async () => {+ const series = (await seed())!;+ await model.addPoint(series.id, {+ actorType: 'user',+ observedAt: new Date(),+ sourceType: 'manual',+ value: 1,+ });++ const deleted = await model.delete(series.id);++ expect(deleted?.id).toBe(series.id);+ expect(await model.findById(series.id)).toBeUndefined();+ expect(await model.latestPoint(series.id)).toBeUndefined();+ });++ it('reports nothing deleted for a foreign or missing series', async () => {+ const series = (await seed())!;+ expect(await otherModel.delete(series.id)).toBeUndefined();+ expect(await model.findById(series.id)).toBeDefined();+ expect(await model.delete('mtr_missing')).toBeUndefined();+ });+ });+});diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex ebcbdfcae5e..e783d7c9514 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -65,7 +65,12 @@ export class GoalModel {};findById = async (id: string): Promise<GoalItem | undefined> => {- return this.db.query.goals.findFirst({ where: and(eq(goals.id, id), this.ownership()) });+ const [row] = await this.db+ .select()+ .from(goals)+ .where(and(eq(goals.id, id), this.ownership()))+ .limit(1);+ return row;};/** The Goal Graph that owns this Task, or undefined when the task is not graph-managed. */diff --git a/packages/database/src/models/metric.ts b/packages/database/src/models/metric.tsnew file mode 100644index 00000000000..aeebddd6595--- /dev/null+++ b/packages/database/src/models/metric.ts@@ -0,0 +1,259 @@+import type { MetricConfig, MetricKind, MetricSubjectType } from '@lobechat/types';+import { and, asc, desc, eq, gte, lte, sql } from 'drizzle-orm';++import type { MetricItem, MetricPointItem, NewMetricPoint } from '../schemas/metric';+import { metricPoints, metrics } from '../schemas/metric';+import type { LobeChatDatabase } from '../type';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++export interface EnsureMetricParams {+ config?: MetricConfig;+ key: string;+ kind?: MetricKind;+ metadata?: unknown;+ subjectId: string;+ subjectType: MetricSubjectType;+ title?: string;+ unit?: string;+}++export type MetricPatch = Partial<+ Pick<MetricItem, 'title' | 'unit' | 'kind' | 'config' | 'metadata'>+>;++export type AddMetricPointParams = Omit<+ NewMetricPoint,+ 'id' | 'metricId' | 'userId' | 'workspaceId' | 'createdAt'+>;++/** Time bucket widths `listPoints` can aggregate into β `date_trunc` fields. */+export type MetricBucket = 'hour' | 'day' | 'week' | 'month';++export interface ListMetricPointsOptions {+ bucket?: MetricBucket;+ from?: Date;+ limit?: number;+ to?: Date;+}++/** One chartable observation, raw or bucket-aggregated. */+export interface MetricChartPoint {+ observedAt: Date;+ value: number;+}++/** Bounded so an unbounded series cannot flood a chart read. */+const DEFAULT_POINT_LIMIT = 2000;++/**+ * Owns the `metrics` / `metric_points` tables: generic numeric time series+ * split into series definition and append-only data.+ *+ * The model knows nothing about any subject domain β a series is addressed by+ * its polymorphic (subjectType, subjectId, key) triple or by id, and consumers+ * (goal criteria, agent dashboards) attach their own meaning. Points always+ * enter through a series the caller owns; reads on points still filter by the+ * denormalized ownership columns so they never need the join.+ */+export class MetricModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private seriesOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, metrics);++ private pointOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, metricPoints);++ // ββ Series ββββββββββββββββββββββββββββββββββββββββββββββ++ /**+ * Idempotent "make sure this series exists" for write paths (probes retry,+ * and two samplers may race on first write). On conflict the insert is a+ * no-op and the existing row is returned β definition fields are NOT+ * overwritten, that is `update`'s job.+ *+ * Returns undefined when the (subject, key) slot is taken by a row outside+ * this owner scope β possible only if subject ids collide across owners,+ * but the ownership filter must not be widened to "fix" it.+ */+ ensure = async (params: EnsureMetricParams): Promise<MetricItem | undefined> => {+ const [inserted] = await this.db+ .insert(metrics)+ .values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, params))+ .onConflictDoNothing()+ .returning();+ if (inserted) return inserted;++ return this.findByKey(params.subjectType, params.subjectId, params.key);+ };++ findById = async (id: string): Promise<MetricItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(metrics)+ .where(and(eq(metrics.id, id), this.seriesOwnership()))+ .limit(1);+ return row;+ };++ findByKey = async (+ subjectType: MetricSubjectType,+ subjectId: string,+ key: string,+ ): Promise<MetricItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(metrics)+ .where(+ and(+ eq(metrics.subjectType, subjectType),+ eq(metrics.subjectId, subjectId),+ eq(metrics.key, key),+ this.seriesOwnership(),+ ),+ )+ .limit(1);+ return row;+ };++ findBySubject = async (+ subjectType: MetricSubjectType,+ subjectId: string,+ ): Promise<MetricItem[]> => {+ return this.db+ .select()+ .from(metrics)+ .where(+ and(+ eq(metrics.subjectType, subjectType),+ eq(metrics.subjectId, subjectId),+ this.seriesOwnership(),+ ),+ )+ .orderBy(asc(metrics.key));+ };++ update = async (id: string, patch: MetricPatch): Promise<MetricItem | undefined> => {+ const [row] = await this.db+ .update(metrics)+ .set(patch)+ .where(and(eq(metrics.id, id), this.seriesOwnership()))+ .returning();+ return row;+ };++ /**+ * Hard delete; points cascade with the series. Returns the deleted row so+ * the caller can tell a completed deletion from a stale or foreign id.+ */+ delete = async (id: string): Promise<MetricItem | undefined> => {+ const [row] = await this.db+ .delete(metrics)+ .where(and(eq(metrics.id, id), this.seriesOwnership()))+ .returning();+ return row;+ };++ // ββ Points ββββββββββββββββββββββββββββββββββββββββββββββ++ /**+ * Append one observation. The series is resolved under the caller's+ * ownership first β a point can never be attached to somebody else's series,+ * and the returned undefined tells the caller the series id was bad.+ */+ addPoint = async (+ metricId: string,+ point: AddMetricPointParams,+ ): Promise<MetricPointItem | undefined> => {+ const series = await this.findById(metricId);+ if (!series) return undefined;++ const [row] = await this.db+ .insert(metricPoints)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ { ...point, metricId },+ ),+ )+ .returning();+ return row;+ };++ /** The most recent observation β what numeric acceptance criteria read. */+ latestPoint = async (metricId: string): Promise<MetricPointItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(metricPoints)+ .where(and(eq(metricPoints.metricId, metricId), this.pointOwnership()))+ .orderBy(desc(metricPoints.observedAt))+ .limit(1);+ return row;+ };++ /**+ * Range read for charts. Without `bucket`, raw points in ascending time.+ * With `bucket`, points are `date_trunc`-grouped and aggregated by the+ * series' own semantics β `counter` takes max (a monotone total must never+ * average down), `gauge` takes avg. Returns undefined when the series is+ * not visible to this owner, so callers can distinguish "no data" from+ * "no series".+ *+ * When the range holds more rows than `limit`, the *newest* window is kept+ * (fetched descending, then reversed for rendering) β a chart that silently+ * drops its current tail goes stale, while a truncated history is visibly+ * incomplete on the left edge.+ */+ listPoints = async (+ metricId: string,+ options: ListMetricPointsOptions = {},+ ): Promise<{ points: MetricChartPoint[]; series: MetricItem } | undefined> => {+ const series = await this.findById(metricId);+ if (!series) return undefined;++ const { bucket, from, limit = DEFAULT_POINT_LIMIT, to } = options;++ const where = and(+ eq(metricPoints.metricId, metricId),+ from ? gte(metricPoints.observedAt, from) : undefined,+ to ? lte(metricPoints.observedAt, to) : undefined,+ this.pointOwnership(),+ );++ if (!bucket) {+ const rows = await this.db+ .select({ observedAt: metricPoints.observedAt, value: metricPoints.value })+ .from(metricPoints)+ .where(where)+ .orderBy(desc(metricPoints.observedAt))+ .limit(limit);+ return { points: rows.reverse(), series };+ }++ const bucketExpr = sql`date_trunc(${bucket}, ${metricPoints.observedAt})`;+ const aggExpr =+ series.kind === 'counter' ? sql`max(${metricPoints.value})` : sql`avg(${metricPoints.value})`;+ const rows = await this.db+ .select({+ observedAt: bucketExpr.mapWith((v: string | Date) => new Date(v)),+ value: aggExpr.mapWith(Number),+ })+ .from(metricPoints)+ .where(where)+ // Positional, not repeated expressions: the bucket rides in as a bind+ // parameter, and Postgres will not match two date_trunc($n, β¦) calls+ // with different parameter slots as the same grouping expression.+ .groupBy(sql`1`)+ .orderBy(sql`1 desc`)+ .limit(limit);+ return { points: rows.reverse(), series };+ };+}