🤯 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
test(database): raise coverage back to 100% (#21748)
Arvin Xu5a7ba848756a
diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex 919b52da762..2e8b9284d3f 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -581,3 +581,113 @@ describe('GoalGraphModel.removeDraftEdges', () => {expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(2);});});++describe('GoalGraphModel guard branches', () => {+ const seedGoal = async (title: string) => goalModel.create({ subjectType: 'standalone', title });++ it('refuses every goal-scoped write on another user goal', async () => {+ const goal = await seedGoal('Owned elsewhere');+ const sibling = new GoalGraphModel(serverDB, otherUserId);++ expect(+ await sibling.createNode(goal.id, { kind: 'task', title: 'Intruder task' }),+ ).toBeUndefined();+ expect(+ await sibling.createNodeOnce(goal.id, { kind: 'task', title: 'Intruder task' }),+ ).toBeUndefined();+ expect(+ await sibling.createEdge(goal.id, 'source-node', 'target-node', 'leads_to'),+ ).toBeUndefined();+ expect(await sibling.bindTask(goal.id, 'node', 'task')).toBeUndefined();+ expect(await sibling.claimTaskNode(goal.id, 'node', new Date())).toBeUndefined();+ expect(await sibling.updateNodeDescription(goal.id, 'node', 'desc')).toBeUndefined();+ expect(+ await sibling.createDecision(goal.id, 'node', { authority: 'user', question: 'why?' }),+ ).toBeUndefined();+ expect(await sibling.resolveDecision(goal.id, 'decision', 'option')).toBeUndefined();+ expect(await sibling.cancelDecision(goal.id, 'decision', 'never asked')).toBeUndefined();+ expect(await sibling.attachWorkVersion(goal.id, 'node', 'version', 'produced')).toBeUndefined();++ // Nothing leaked through: the goal graph is still empty for its owner.+ const graph = await graphModel.getGraph(goal.id);+ expect(graph?.nodes).toHaveLength(0);+ expect(graph?.edges).toHaveLength(0);+ });++ it('rejects an experiment that answers no question', async () => {+ const goal = await seedGoal('Experiment without a question');++ await expect(+ graphModel.createNode(goal.id, { kind: 'experiment', title: 'Try it' }),+ ).rejects.toThrow('An experiment must answer a question');+ });++ it('rejects a non-experiment that claims to answer a question', async () => {+ const goal = await seedGoal('Task answering a question');++ await expect(+ graphModel.createNode(goal.id, {+ kind: 'task',+ questionId: '00000000-0000-0000-0000-000000000000',+ title: 'Not an experiment',+ }),+ ).rejects.toThrow('Only experiments can answer questions');+ });++ it('returns undefined when the node to attach a Work version to is missing', async () => {+ const goal = await seedGoal('No such node');++ expect(+ await graphModel.attachWorkVersion(+ goal.id,+ '00000000-0000-0000-0000-000000000000',+ '00000000-0000-0000-0000-000000000001',+ 'produced',+ ),+ ).toBeUndefined();+ });++ it('returns undefined when a decision is opened on a non-decision node', async () => {+ const goal = await seedGoal('Decision on a task');+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });++ expect(+ await graphModel.createDecision(goal.id, node!.id, {+ authority: 'user',+ question: 'not a gate',+ }),+ ).toBeUndefined();+ });++ it('returns undefined when resolving an already resolved decision', async () => {+ const goal = await seedGoal('Resolve twice');+ const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });+ const decision = await graphModel.createDecision(goal.id, gate!.id, {+ authority: 'user',+ options: [{ id: 'yes', label: 'Yes' }],+ question: 'ship?',+ });++ expect(await graphModel.resolveDecision(goal.id, decision!.id, 'yes')).toBeDefined();+ expect(await graphModel.resolveDecision(goal.id, decision!.id, 'yes')).toBeUndefined();+ });++ it('returns undefined when cancelling an already resolved decision', async () => {+ const goal = await seedGoal('Cancel after resolve');+ const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });+ const decision = await graphModel.createDecision(goal.id, gate!.id, {+ authority: 'user',+ options: [{ id: 'yes', label: 'Yes' }],+ question: 'ship?',+ });+ await graphModel.resolveDecision(goal.id, decision!.id, 'yes');++ expect(await graphModel.cancelDecision(goal.id, decision!.id, 'too late')).toBeUndefined();+ });++ it('returns undefined when no goal carries the task', async () => {+ expect(+ await graphModel.findGoalByTaskId('00000000-0000-0000-0000-000000000000'),+ ).toBeUndefined();+ });+});diff --git a/packages/database/src/models/__tests__/rbac.test.ts b/packages/database/src/models/__tests__/rbac.test.tsindex c5aa644b0fc..92e12e32463 100644--- a/packages/database/src/models/__tests__/rbac.test.ts+++ b/packages/database/src/models/__tests__/rbac.test.ts@@ -435,3 +435,101 @@ describe('RbacModel — personal mode implicit baseline', () => {expect(codes).toContain(dbCode);});});++describe('RbacModel — role assignment writes', () => {+ const createRole = async (name: string) => {+ const [role] = await serverDB+ .insert(roles)+ .values({ displayName: name, isActive: true, isSystem: true, name })+ .returning({ id: roles.id });++ return role.id;+ };++ const assignedRoleIds = async (targetUserId: string) => {+ const rows = await serverDB.select().from(userRoles).where(eq(userRoles.userId, targetUserId));++ return rows.map((row) => row.roleId).sort();+ };++ it('replaces the previous assignments in one transaction', async () => {+ const first = await createRole('assignment_first');+ const second = await createRole('assignment_second');+ const rbac = new RbacModel(serverDB, userId);++ await rbac.updateUserRoles(userId, [first]);+ expect(await assignedRoleIds(userId)).toEqual([first]);++ await rbac.updateUserRoles(userId, [first, second]);+ expect(await assignedRoleIds(userId)).toEqual([first, second].sort());+ });++ it('clears every assignment when no role is given', async () => {+ const only = await createRole('assignment_only');+ const rbac = new RbacModel(serverDB, userId);+ await rbac.updateUserRoles(userId, [only]);++ await rbac.updateUserRoles(userId, []);++ expect(await assignedRoleIds(userId)).toEqual([]);+ });++ it('rejects unknown role ids before touching the existing assignments', async () => {+ const known = await createRole('assignment_known');+ const rbac = new RbacModel(serverDB, userId);+ await rbac.updateUserRoles(userId, [known]);++ await expect(rbac.updateUserRoles(userId, [known, 'missing-role-id'])).rejects.toThrow(+ 'Roles missing-role-id do not exist',+ );+ expect(await assignedRoleIds(userId)).toEqual([known]);+ });+});++describe('RbacModel.getWorkspaceUsersPermissions — edge inputs', () => {+ it('returns an empty map without querying when no user ids are given', async () => {+ const permissionsByUserId = await RbacModel.getWorkspaceUsersPermissions({+ db: serverDB,+ userIds: [],+ workspaceId: workspaceAId,+ });++ expect(permissionsByUserId.size).toBe(0);+ });++ it('demotes an owner membership whose user is not the primary owner', async () => {+ // beforeEach binds workspaceAId's primary owner to otherUserId, so a+ // `owner` row for userId is stale data that must not grant owner-only codes.+ await addMembership(userId, workspaceAId, 'owner');++ const permissionsByUserId = await RbacModel.getWorkspaceUsersPermissions({+ db: serverDB,+ requireMembership: true,+ userIds: [userId],+ workspaceId: workspaceAId,+ });++ const codes = permissionsByUserId.get(userId) ?? [];+ expect(codes).toContain(`${PERMISSION_ACTIONS.WORKSPACE_UPDATE}:all`);+ expect(codes).not.toContain(`${PERMISSION_ACTIONS.WORKSPACE_BILLING_MANAGE}:all`);+ });++ it('keeps owner-only codes for the real primary owner', async () => {+ await serverDB+ .update(workspaces)+ .set({ primaryOwnerId: userId })+ .where(eq(workspaces.id, workspaceAId));+ await addMembership(userId, workspaceAId, 'owner');++ const permissionsByUserId = await RbacModel.getWorkspaceUsersPermissions({+ db: serverDB,+ requireMembership: true,+ userIds: [userId],+ workspaceId: workspaceAId,+ });++ expect(permissionsByUserId.get(userId)).toContain(+ `${PERMISSION_ACTIONS.WORKSPACE_BILLING_MANAGE}:all`,+ );+ });+});diff --git a/packages/database/src/models/userMemory/__tests__/query.hybrid.test.ts b/packages/database/src/models/userMemory/__tests__/query.hybrid.test.tsnew file mode 100644index 00000000000..db17afa680b--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/query.hybrid.test.ts@@ -0,0 +1,266 @@+// @vitest-environment node+import type { SearchMemoryParams } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import type { UserMemoryQueryContext } from '../query/context';+import {+ searchHybridActivities,+ searchHybridContexts,+ searchHybridExperiences,+ searchHybridIdentities,+ searchHybridPreferences,+} from '../query/hybrid';++interface Candidate {+ id: string;+ title?: string;+}++const searchParams = {} as SearchMemoryParams;++const createContext = (+ options: {+ filters?: boolean;+ limit?: number;+ lexical?: Candidate[];+ runSemantic?: boolean;+ semantic?: Candidate[];+ } = {},+) => {+ const { filters = false, lexical = [], limit = 20, runSemantic = true, semantic = [] } = options;++ const context = {+ getSearchOverfetchLimit: vi.fn(() => limit),+ hasSearchFilters: vi.fn(() => filters),+ loadBaseSignals: vi.fn(async () => new Map()),+ searchActivitiesLexical: vi.fn(async () => lexical),+ searchActivitiesSemantic: vi.fn(async () => semantic),+ searchContextsLexical: vi.fn(async () => lexical),+ searchContextsSemantic: vi.fn(async () => semantic),+ searchExperiencesLexical: vi.fn(async () => lexical),+ searchExperiencesSemantic: vi.fn(async () => semantic),+ searchIdentitiesLexical: vi.fn(async () => lexical),+ searchIdentitiesSemantic: vi.fn(async () => semantic),+ searchPreferencesLexical: vi.fn(async () => lexical),+ searchPreferencesSemantic: vi.fn(async () => semantic),+ shouldRunSemanticSearch: vi.fn(() => runSemantic),+ };++ return { context: context as unknown as UserMemoryQueryContext, spies: context };+};++const ids = (results: { item: Candidate }[]) => results.map(({ item }) => item.id);++describe('userMemory hybrid retrieval', () => {+ describe('early exit when the overfetch limit is exhausted', () => {+ it.each([+ ['activities', searchHybridActivities, 'searchActivitiesSemantic'],+ ['contexts', searchHybridContexts, 'searchContextsSemantic'],+ ['experiences', searchHybridExperiences, 'searchExperiencesSemantic'],+ ['identities', searchHybridIdentities, 'searchIdentitiesSemantic'],+ ['preferences', searchHybridPreferences, 'searchPreferencesSemantic'],+ ] as const)('returns [] for %s without touching the retrievers', async (_, search, spyName) => {+ const { context, spies } = createContext({ limit: 0 });++ const result = await search(context, {+ embeddings: [[0.1, 0.2]],+ lexicalSearch: true,+ params: searchParams,+ queries: ['anything'],+ });++ expect(result).toEqual([]);+ expect(spies[spyName]).not.toHaveBeenCalled();+ expect(spies.searchActivitiesLexical).not.toHaveBeenCalled();+ });+ });++ describe('searchHybridExperiences', () => {+ it('merges semantic and lexical candidates, deduping by id', async () => {+ const { context, spies } = createContext({+ lexical: [{ id: 'b', title: 'lexical-b' }, { id: 'c' }],+ semantic: [{ id: 'a' }, { id: 'b', title: 'semantic-b' }],+ });++ const result = await searchHybridExperiences(context, {+ embeddings: [[0.1, 0.2]],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(ids(result).sort()).toEqual(['a', 'b', 'c']);+ // The map keeps first-seen order but the lexical copy lands last, so it wins the dedupe.+ expect(result.find(({ item }) => item.id === 'b')?.item.title).toBe('lexical-b');+ expect(spies.searchExperiencesSemantic).toHaveBeenCalledWith([0.1, 0.2], 20, searchParams);+ expect(spies.searchExperiencesLexical).toHaveBeenCalledWith('alpha', 20, searchParams);+ expect(spies.loadBaseSignals).toHaveBeenCalledWith([+ { id: 'a' },+ { id: 'b', title: 'lexical-b' },+ { id: 'c' },+ ]);+ });++ it('averages multiple query embeddings before the semantic search', async () => {+ const { context, spies } = createContext({ semantic: [{ id: 'a' }] });++ await searchHybridExperiences(context, {+ embeddings: [+ [0.5, 0.5],+ [0.25, 0.75],+ ],+ lexicalSearch: false,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchExperiencesSemantic).toHaveBeenCalledWith(+ [0.375, 0.625],+ 20,+ searchParams,+ );+ });++ it('skips semantic retrieval when no embeddings are provided', async () => {+ const { context, spies } = createContext({ lexical: [{ id: 'lex' }] });++ const result = await searchHybridExperiences(context, {+ embeddings: [],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchExperiencesSemantic).not.toHaveBeenCalled();+ expect(spies.searchExperiencesLexical).toHaveBeenCalledTimes(1);+ expect(ids(result)).toEqual(['lex']);+ });++ it('skips semantic retrieval when the semantic gate declines', async () => {+ const { context, spies } = createContext({ lexical: [{ id: 'lex' }], runSemantic: false });++ const result = await searchHybridExperiences(context, {+ embeddings: [[0.1]],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchExperiencesSemantic).not.toHaveBeenCalled();+ expect(spies.shouldRunSemanticSearch).toHaveBeenCalledWith(1, 1);+ expect(ids(result)).toEqual(['lex']);+ });++ it('skips lexical retrieval when there is neither a query nor a filter', async () => {+ const { context, spies } = createContext({ semantic: [{ id: 'sem' }] });++ const result = await searchHybridExperiences(context, {+ embeddings: [[0.1]],+ lexicalSearch: true,+ params: searchParams,+ queries: [],+ });++ expect(spies.searchExperiencesLexical).not.toHaveBeenCalled();+ expect(ids(result)).toEqual(['sem']);+ });++ it('runs lexical retrieval on filters alone and passes no retrieval query', async () => {+ const { context, spies } = createContext({ filters: true, lexical: [{ id: 'filtered' }] });++ const result = await searchHybridExperiences(context, {+ embeddings: [],+ lexicalSearch: true,+ params: searchParams,+ queries: [],+ });++ expect(spies.hasSearchFilters).toHaveBeenCalled();+ expect(spies.searchExperiencesLexical).toHaveBeenCalledWith(undefined, 20, searchParams);+ expect(ids(result)).toEqual(['filtered']);+ expect(spies.shouldRunSemanticSearch).not.toHaveBeenCalled();+ });++ it('honours lexicalSearch=false even when a query is present', async () => {+ const { context, spies } = createContext({ semantic: [{ id: 'sem' }] });++ const result = await searchHybridExperiences(context, {+ embeddings: [[0.1]],+ lexicalSearch: false,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchExperiencesLexical).not.toHaveBeenCalled();+ expect(ids(result)).toEqual(['sem']);+ });++ it('returns [] when both retrievers come back empty', async () => {+ const { context } = createContext();++ const result = await searchHybridExperiences(context, {+ embeddings: [[0.1]],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(result).toEqual([]);+ });+ });++ describe('identities and preferences delegates', () => {+ it('routes identities retrieval through the identity retrievers', async () => {+ const { context, spies } = createContext({ semantic: [{ id: 'identity' }] });++ const result = await searchHybridIdentities(context, {+ embeddings: [[0.1]],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchIdentitiesSemantic).toHaveBeenCalledTimes(1);+ expect(spies.searchIdentitiesLexical).toHaveBeenCalledTimes(1);+ expect(spies.searchActivitiesSemantic).not.toHaveBeenCalled();+ expect(ids(result)).toEqual(['identity']);+ });++ it('routes preferences retrieval through the preference retrievers', async () => {+ const { context, spies } = createContext({ lexical: [{ id: 'preference' }] });++ const result = await searchHybridPreferences(context, {+ embeddings: [],+ lexicalSearch: true,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchPreferencesSemantic).not.toHaveBeenCalled();+ expect(spies.searchPreferencesLexical).toHaveBeenCalledTimes(1);+ expect(ids(result)).toEqual(['preference']);+ });++ it('routes activities and contexts retrieval through their own retrievers', async () => {+ const { context, spies } = createContext({ semantic: [{ id: 'row' }] });++ const activities = await searchHybridActivities(context, {+ embeddings: [[0.1]],+ lexicalSearch: false,+ params: searchParams,+ queries: ['alpha'],+ });+ const contexts = await searchHybridContexts(context, {+ embeddings: [[0.1]],+ lexicalSearch: false,+ params: searchParams,+ queries: ['alpha'],+ });++ expect(spies.searchActivitiesSemantic).toHaveBeenCalledTimes(1);+ expect(spies.searchContextsSemantic).toHaveBeenCalledTimes(1);+ expect(ids(activities)).toEqual(['row']);+ expect(ids(contexts)).toEqual(['row']);+ });+ });+});diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.tsindex bdba266d1bc..afb8bde0c29 100644--- a/packages/database/src/models/work/__tests__/queries.test.ts+++ b/packages/database/src/models/work/__tests__/queries.test.ts@@ -464,3 +464,36 @@ describe('WorkModel · queries', () => {expect(types(optedWorkspace.items)).toEqual(['file', 'task']);});});++describe('WorkModel · queries guard branches', () => {+ it('returns [] for a root operation lookup without an id', async () => {+ const workModel = new WorkModel(serverDB, userId);++ expect(await workModel.listByRootOperation({ rootOperationId: null })).toEqual([]);+ expect(await workModel.listByRootOperation({})).toEqual([]);+ });++ it('returns an empty map when no root operation ids are requested', async () => {+ const workModel = new WorkModel(serverDB, userId);++ expect(await workModel.listByRootOperations({ rootOperationIds: [] })).toEqual({});+ // null entries are filtered out before the query runs+ expect(await workModel.listByRootOperations({ rootOperationIds: [null, null] })).toEqual({});+ expect(await workModel.listByRootOperations({})).toEqual({});+ });++ it('returns empty lists per requested root operation when nothing matches', async () => {+ const workModel = new WorkModel(serverDB, userId);++ expect(+ await workModel.listSummariesByRootOperations({ rootOperationIds: ['op-unknown'] }),+ ).toEqual({ 'op-unknown': [] });+ expect(await workModel.listSummariesByRootOperations({ rootOperationIds: [] })).toEqual({});+ });++ it('returns [] for a conversation lookup without a topic id', async () => {+ const workModel = new WorkModel(serverDB, userId);++ expect(await workModel.listByConversation({ topicId: null })).toEqual([]);+ });+});