Skip to content

🤯 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.

test(database): raise coverage back to 100% (#21030)

Arvin Xuab449d1e4460
diff --git a/packages/database/src/models/__tests__/acceptanceFlow.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
index bc690124a3a..7ee23e48e8d 100644
--- a/packages/database/src/models/__tests__/acceptanceFlow.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
@@ -664,3 +664,111 @@ describe('check assets and round snapshots', () => {
expect(() => validateFlow({ ...definition, edges: [] })).toThrow('Unreachable');
});
});
+
+describe('validation and terminal guards', () => {
+ it('rejects duplicate node ids, duplicate edge ids and unknown edge endpoints', () => {
+ expect(() =>
+ validateFlow({ ...definition, nodes: [...definition.nodes, definition.nodes[0]] }),
+ ).toThrow('Duplicate node ids');
+
+ expect(() =>
+ validateFlow({ ...definition, edges: [...definition.edges, definition.edges[0]] }),
+ ).toThrow('Duplicate edge ids');
+
+ expect(() =>
+ validateFlow({
+ ...definition,
+ edges: [{ ...definition.edges[0], targetNodeId: 'not-a-node' }],
+ }),
+ ).toThrow('Unknown edge endpoint');
+
+ expect(() =>
+ validateFlow({
+ ...definition,
+ edges: [{ ...definition.edges[0], sourceNodeId: 'not-a-node' }],
+ }),
+ ).toThrow('Unknown edge endpoint');
+ });
+
+ it('requires exactly one of criterionId, check or subFlowId per node', () => {
+ expect(() =>
+ validateFlow({
+ ...definition,
+ // A node carrying both a check and a subflow is ambiguous.
+ nodes: [{ ...definition.nodes[0], subFlowId: randomUUID() }, definition.nodes[1]],
+ }),
+ ).toThrow('exactly one');
+
+ expect(() =>
+ validateFlow({
+ ...definition,
+ nodes: [{ id: definition.entryNodeId }, definition.nodes[1]],
+ }),
+ ).toThrow('exactly one');
+ });
+
+ it('refuses to publish into or edit a settled acceptance', async () => {
+ const { flowId } = await model.publish(acceptanceId, definition);
+ await db
+ .update(acceptances)
+ .set({ status: 'accepted' })
+ .where(eq(acceptances.id, acceptanceId));
+
+ await expect(model.publish(acceptanceId, definition)).rejects.toThrow('Reopen acceptance');
+ await expect(model.publish(acceptanceId, definition, flowId)).rejects.toThrow(
+ 'Reopen acceptance',
+ );
+ });
+
+ it('guards editing against unknown flows and stale hashes', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+
+ await expect(model.publish(acceptanceId, definition, randomUUID(), hash)).rejects.toThrow(
+ 'Flow not found',
+ );
+
+ await expect(model.publish(acceptanceId, definition, flowId, 'stale-hash')).rejects.toThrow(
+ 'Flow changed',
+ );
+ // Editing an existing flow without the hash it was read at is rejected too.
+ await expect(model.publish(acceptanceId, definition, flowId)).rejects.toThrow('Flow changed');
+ // Editing with the current hash succeeds and keeps the flow id.
+ await expect(model.publish(acceptanceId, definition, flowId, hash)).resolves.toMatchObject({
+ flowId,
+ });
+ });
+
+ it('guards complete() against unknown, reviewed and unfinished rounds', async () => {
+ await expect(model.complete(acceptanceId, randomUUID())).rejects.toThrow(
+ 'Flow round not found',
+ );
+
+ const { flowId } = await model.publish(acceptanceId, definition);
+ const run = await model.start(acceptanceId, flowId);
+
+ await expect(model.complete(acceptanceId, run.id)).rejects.toThrow(
+ 'Required flow branches have not passed',
+ );
+
+ await db.update(verifyRuns).set({ userDecision: 'accepted' }).where(eq(verifyRuns.id, run.id));
+ await expect(model.complete(acceptanceId, run.id)).rejects.toThrow('Round already reviewed');
+ });
+
+ it('refuses to review a result outside the acceptance', async () => {
+ await expect(
+ model.review(acceptanceId, randomUUID(), 'accepted', 'Looks right', owner),
+ ).rejects.toThrow('Result not found');
+ });
+
+ it('reports an unknown flow when deleting', async () => {
+ await expect(model.delete(acceptanceId, randomUUID())).rejects.toThrow('Flow not found');
+ });
+
+ it('refuses to delete a flow from a settled acceptance', async () => {
+ const { flowId } = await model.publish(acceptanceId, definition);
+ await db.update(acceptances).set({ status: 'closed' }).where(eq(acceptances.id, acceptanceId));
+
+ await expect(model.delete(acceptanceId, flowId)).rejects.toThrow('Reopen acceptance');
+ expect(await model.list(acceptanceId)).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentOperation.recovery.test.ts b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
new file mode 100644
index 00000000000..46ee1ce6f59
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
@@ -0,0 +1,274 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentOperations, tasks, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentOperationModel } from '../agentOperation';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-operation-recovery-user';
+const otherUserId = 'agent-operation-recovery-other';
+const topicId = 'agent-operation-recovery-topic';
+const otherTopicId = 'agent-operation-recovery-topic-other';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: topicId, userId },
+ { id: otherTopicId, userId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentOperations);
+ await serverDB.delete(tasks);
+ await serverDB.delete(topics);
+ await serverDB.delete(users);
+});
+
+const model = (owner = userId) => new AgentOperationModel(serverDB, owner);
+
+/** Start a run and park it, which is how a live operation reaches a wait state. */
+const park = async (
+ operationId: string,
+ status: 'waiting_for_async_tool' | 'waiting_for_client' | 'waiting_for_human',
+ options: { topicId?: string; owner?: string } = {},
+) => {
+ const owner = options.owner ?? userId;
+ await model(owner).recordStart({ operationId, topicId: options.topicId ?? topicId });
+ await model(owner).recordCompletion(operationId, { completionReason: status, status });
+};
+
+const setCreatedAt = async (operationId: string, at: string) => {
+ await serverDB
+ .update(agentOperations)
+ .set({ createdAt: new Date(at) })
+ .where(eq(agentOperations.id, operationId));
+};
+
+describe('AgentOperationModel recovery lookups', () => {
+ describe('findLatestParkedOperationId', () => {
+ it('resolves the newest human wait in the topic, ignoring other states, topics and owners', async () => {
+ await park('park-old', 'waiting_for_human');
+ await setCreatedAt('park-old', '2026-01-01T00:00:00Z');
+ await park('park-new', 'waiting_for_human');
+ await setCreatedAt('park-new', '2026-01-02T00:00:00Z');
+
+ // Same topic, but the run is not parked on a person.
+ await model().recordStart({ operationId: 'park-running', topicId });
+ await setCreatedAt('park-running', '2026-01-03T00:00:00Z');
+
+ // Another topic and another user both park on a person, but are not ours.
+ await park('park-other-topic', 'waiting_for_human', { topicId: otherTopicId });
+ await setCreatedAt('park-other-topic', '2026-01-04T00:00:00Z');
+ await park('park-foreign', 'waiting_for_human', { owner: otherUserId });
+ await setCreatedAt('park-foreign', '2026-01-05T00:00:00Z');
+
+ expect(await model().findLatestParkedOperationId(topicId)).toBe('park-new');
+ expect(await model().findLatestParkedOperationId('topic-with-nothing')).toBeUndefined();
+ });
+ });
+
+ describe('findByIds', () => {
+ it('batch-loads owned operations and short-circuits an empty request', async () => {
+ await model().recordStart({ operationId: 'batch-a' });
+ await model().recordStart({ operationId: 'batch-b' });
+ await model(otherUserId).recordStart({ operationId: 'batch-foreign' });
+
+ expect(await model().findByIds([])).toEqual([]);
+
+ const rows = await model().findByIds([
+ 'batch-a',
+ 'batch-b',
+ 'batch-foreign',
+ 'batch-missing',
+ ]);
+ expect(rows.map((row) => row.id).sort()).toEqual(['batch-a', 'batch-b']);
+ });
+ });
+
+ describe('recordCompletion model provenance', () => {
+ it('stores the model and provider that produced the run', async () => {
+ await model().recordStart({ operationId: 'op-provenance' });
+
+ expect(
+ await model().recordCompletion('op-provenance', {
+ completionReason: 'done',
+ model: 'gpt-5',
+ provider: 'openai',
+ status: 'done',
+ }),
+ ).toBe(true);
+ expect(await model().findById('op-provenance')).toMatchObject({
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ });
+ });
+
+ describe('sumCostByTask', () => {
+ it('sums the cost bound to a task, and reports zero when none is bound', async () => {
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: 'task-cost',
+ identifier: 'T-COST',
+ instruction: 'x',
+ seq: 1,
+ });
+
+ await model().recordStart({ operationId: 'cost-a', taskId: 'task-cost' });
+ await model().recordCompletion('cost-a', {
+ completionReason: 'done',
+ status: 'done',
+ totalCost: 1.5,
+ });
+ await model().recordStart({ operationId: 'cost-b', taskId: 'task-cost' });
+ await model().recordCompletion('cost-b', {
+ completionReason: 'done',
+ status: 'done',
+ totalCost: 2.25,
+ });
+ await model().recordStart({ operationId: 'cost-unbound' });
+ await model().recordCompletion('cost-unbound', {
+ completionReason: 'done',
+ status: 'done',
+ totalCost: 99,
+ });
+
+ expect(await model().sumCostByTask('task-cost')).toBeCloseTo(3.75);
+ // `sum()` over zero rows is NULL — the meter must read 0, not NaN.
+ expect(await model().sumCostByTask('task-with-no-runs')).toBe(0);
+ expect(await model(otherUserId).sumCostByTask('task-cost')).toBe(0);
+ });
+ });
+
+ describe('findUsageByOperations', () => {
+ it('deduplicates the requested ids and reports per-operation usage', async () => {
+ await model().recordStart({ operationId: 'usage-a' });
+ await model().recordCompletion('usage-a', {
+ completionReason: 'done',
+ status: 'done',
+ totalCost: 0.5,
+ totalTokens: 120,
+ });
+ // Never settled: both scalars stay NULL.
+ await model().recordStart({ operationId: 'usage-null' });
+
+ expect(await model().findUsageByOperations([])).toEqual(new Map());
+
+ const usage = await model().findUsageByOperations([
+ 'usage-a',
+ 'usage-a',
+ 'usage-null',
+ 'usage-missing',
+ ]);
+
+ expect(usage.get('usage-a')).toEqual({ cost: 0.5, tokens: 120 });
+ expect(usage.get('usage-null')).toEqual({ cost: 0, tokens: 0 });
+ expect(usage.has('usage-missing')).toBe(false);
+ expect(usage.size).toBe(2);
+ });
+ });
+
+ describe('async tool resume claim', () => {
+ it('resumes a parked async wait exactly once, within the owner', async () => {
+ await park('op-async', 'waiting_for_async_tool');
+ await park('op-async-foreign', 'waiting_for_async_tool');
+ await park('op-human', 'waiting_for_human');
+
+ const first = await model().tryResumeFromAsyncTool('op-async');
+ expect(first).toBe(true);
+ expect((await model().findById('op-async'))?.status).toBe('running');
+ // Losing the race (or a second sub-op completing) must not resume twice.
+ expect(await model().tryResumeFromAsyncTool('op-async')).toBe(false);
+ // A person's wait is not an async tool wait.
+ expect(await model().tryResumeFromAsyncTool('op-human')).toBe(false);
+ // Owner isolation: another owner must not claim a genuinely resumable wait,
+ // and the row has to stay parked for its real owner afterwards.
+ expect(await model(otherUserId).tryResumeFromAsyncTool('op-async-foreign')).toBe(false);
+ expect((await model().findById('op-async-foreign'))?.status).toBe('waiting_for_async_tool');
+ expect(await model().tryResumeFromAsyncTool('op-never-started')).toBe(false);
+ });
+ });
+
+ describe('settleClientWait', () => {
+ it('retires a client wait with the default outcome', async () => {
+ await park('wait-default', 'waiting_for_client');
+
+ expect(await model().settleClientWait('wait-default')).toBe(true);
+ expect(await model().findById('wait-default')).toMatchObject({
+ completionReason: 'error',
+ status: 'error',
+ });
+ });
+
+ it('retires a client wait with the interrupted outcome when asked', async () => {
+ await park('wait-interrupted', 'waiting_for_client');
+
+ expect(await model().settleClientWait('wait-interrupted', 'interrupted')).toBe(true);
+ expect(await model().findById('wait-interrupted')).toMatchObject({
+ completionReason: 'interrupted',
+ status: 'interrupted',
+ });
+ });
+
+ it('never settles a run a client already resumed', async () => {
+ await park('wait-resumed', 'waiting_for_client');
+ expect(await model().tryResumeFromClientWait('wait-resumed')).toBe(true);
+
+ expect(await model().settleClientWait('wait-resumed')).toBe(false);
+ expect((await model().findById('wait-resumed'))?.status).toBe('running');
+ });
+ });
+
+ describe('findLiveByTopic', () => {
+ it('lists the resumable operations of a topic, independent of the UI marker', async () => {
+ await model().recordStart({ operationId: 'live-running', topicId });
+ await park('live-human', 'waiting_for_human');
+ // A finished run is not resumable, so it stays out.
+ await model().recordStart({ operationId: 'live-done', topicId });
+ await model().settleRunning('live-done', 'done');
+ // Other topics and other owners stay out as well.
+ await model().recordStart({ operationId: 'live-other-topic', topicId: otherTopicId });
+ await park('live-foreign', 'waiting_for_human', { owner: otherUserId });
+
+ const rows = await model().findLiveByTopic(topicId);
+ expect(rows.map((row) => row.id).sort()).toEqual(['live-human', 'live-running']);
+
+ // The other owner's parked run is in the same topic, and only they see it.
+ expect((await model(otherUserId).findLiveByTopic(topicId)).map((row) => row.id)).toEqual([
+ 'live-foreign',
+ ]);
+ });
+ });
+
+ describe('listWaitingForClient', () => {
+ it('lists every parked wait when the caller names no providers', async () => {
+ await park('wait-all-a', 'waiting_for_client');
+ await park('wait-all-b', 'waiting_for_client');
+ await serverDB
+ .update(agentOperations)
+ .set({ provider: 'ollama' })
+ .where(eq(agentOperations.id, 'wait-all-b'));
+
+ const rows = await model().listWaitingForClient();
+ expect(rows.map((row) => row.id).sort()).toEqual(['wait-all-a', 'wait-all-b']);
+ });
+ });
+
+ describe('settleRunning outcome', () => {
+ it('stamps the interrupted reason when a live run is interrupted', async () => {
+ await model().recordStart({ operationId: 'op-still-running' });
+
+ expect(await model().settleRunning('op-still-running', 'interrupted')).toBe(true);
+ expect(await model().findById('op-still-running')).toMatchObject({
+ completionReason: 'interrupted',
+ status: 'interrupted',
+ });
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/chatGroup.visibility.test.ts b/packages/database/src/models/__tests__/chatGroup.visibility.test.ts
new file mode 100644
index 00000000000..a3122a751f9
--- /dev/null
+++ b/packages/database/src/models/__tests__/chatGroup.visibility.test.ts
@@ -0,0 +1,481 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents as agentsTable,
+ chatGroups,
+ chatGroupsAgents,
+ sessionGroups,
+ users,
+ workspaces,
+} from '../../schemas';
+import { ChatGroupModel } from '../chatGroup';
+
+const userId = 'cg-vis-user';
+const otherUserId = 'cg-vis-other';
+const workspaceId = 'cg-vis-workspace';
+const foreignWorkspaceId = 'cg-vis-foreign-workspace';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const personalModel = new ChatGroupModel(serverDB, userId);
+const workspaceModel = new ChatGroupModel(serverDB, userId, workspaceId);
+const foreignWorkspaceModel = new ChatGroupModel(serverDB, userId, foreignWorkspaceId);
+/** A second member of the same workspace — used to prove what is *not* ownership-scoped. */
+const otherMemberModel = new ChatGroupModel(serverDB, otherUserId, workspaceId);
+
+const readAgentVisibility = async (agentId: string) => {
+ const [row] = await serverDB
+ .select({ visibility: agentsTable.visibility })
+ .from(agentsTable)
+ .where(eq(agentsTable.id, agentId));
+
+ return row?.visibility;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(workspaces).values([
+ { id: workspaceId, name: 'Chat Group Visibility', primaryOwnerId: userId, slug: workspaceId },
+ {
+ id: foreignWorkspaceId,
+ name: 'Foreign Workspace',
+ primaryOwnerId: userId,
+ slug: foreignWorkspaceId,
+ },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('ChatGroupModel visibility scope', () => {
+ describe('getSupervisorAgentId', () => {
+ it('resolves the personal supervisor and hides it from workspace scope', async () => {
+ await serverDB.insert(chatGroups).values({ id: 'cg-personal', title: 'Personal', userId });
+ await serverDB
+ .insert(agentsTable)
+ .values({ id: 'agt-personal-sup', title: 'Supervisor', userId, virtual: true });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-personal-sup',
+ chatGroupId: 'cg-personal',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ });
+
+ await expect(personalModel.getSupervisorAgentId('cg-personal')).resolves.toBe(
+ 'agt-personal-sup',
+ );
+ // A personal junction row carries no workspace id, so a workspace-scoped
+ // caller must not resolve it.
+ await expect(workspaceModel.getSupervisorAgentId('cg-personal')).resolves.toBeNull();
+ });
+
+ it('returns null when no supervisor row exists', async () => {
+ await serverDB
+ .insert(chatGroups)
+ .values({ id: 'cg-no-supervisor', title: 'Members only', userId });
+ await serverDB
+ .insert(agentsTable)
+ .values({ id: 'agt-plain-member', title: 'Member', userId });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-plain-member',
+ chatGroupId: 'cg-no-supervisor',
+ order: 0,
+ role: 'participant',
+ userId,
+ });
+
+ await expect(personalModel.getSupervisorAgentId('cg-no-supervisor')).resolves.toBeNull();
+ });
+
+ it('scopes workspace supervisors by workspace rather than by ownership', async () => {
+ await serverDB
+ .insert(chatGroups)
+ .values({ id: 'cg-workspace', title: 'Workspace group', userId, workspaceId });
+ await serverDB.insert(agentsTable).values({
+ id: 'agt-workspace-sup',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-workspace-sup',
+ chatGroupId: 'cg-workspace',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ });
+
+ await expect(workspaceModel.getSupervisorAgentId('cg-workspace')).resolves.toBe(
+ 'agt-workspace-sup',
+ );
+ // Deliberate: the supervisor's permission policies must resolve for any
+ // member of the workspace, including one who cannot see the group row.
+ await expect(otherMemberModel.getSupervisorAgentId('cg-workspace')).resolves.toBe(
+ 'agt-workspace-sup',
+ );
+ // A different workspace must not resolve it.
+ await expect(foreignWorkspaceModel.getSupervisorAgentId('cg-workspace')).resolves.toBeNull();
+ });
+ });
+
+ describe('update with a sidebar folder', () => {
+ it("assigns a personal group to the caller's own folder", async () => {
+ await serverDB
+ .insert(sessionGroups)
+ .values({ id: 'folder-personal', name: 'Personal folder', userId });
+ await serverDB.insert(chatGroups).values({ id: 'cg-folder', title: 'Group', userId });
+
+ const updated = await personalModel.update('cg-folder', { groupId: 'folder-personal' });
+
+ expect(updated.groupId).toBe('folder-personal');
+ });
+
+ it("refuses a folder outside the caller's scope", async () => {
+ await serverDB
+ .insert(sessionGroups)
+ .values({ id: 'folder-foreign', name: 'Foreign folder', userId: otherUserId });
+ await serverDB.insert(chatGroups).values({ id: 'cg-foreign-folder', title: 'Group', userId });
+
+ await expect(
+ personalModel.update('cg-foreign-folder', { groupId: 'folder-foreign' }),
+ ).rejects.toThrow('Session group folder-foreign not found in current scope');
+ });
+
+ it('refuses mixing folder and group visibilities inside a workspace', async () => {
+ await serverDB.insert(sessionGroups).values([
+ {
+ id: 'folder-ws-private',
+ name: 'Private folder',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'folder-ws-public',
+ name: 'Public folder',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-ws-public',
+ title: 'Public group',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ await expect(
+ workspaceModel.update('cg-ws-public', { groupId: 'folder-ws-private' }),
+ ).rejects.toThrow('A public chat group cannot be moved into a private folder');
+
+ const moved = await workspaceModel.update('cg-ws-public', { groupId: 'folder-ws-public' });
+
+ expect(moved.groupId).toBe('folder-ws-public');
+ });
+
+ it('lets a personal model move a group without checking folder visibility', async () => {
+ await serverDB
+ .insert(sessionGroups)
+ .values({ id: 'folder-personal-public', name: 'Personal folder', userId });
+ await serverDB
+ .insert(chatGroups)
+ .values({ id: 'cg-personal-move', title: 'Group', userId, visibility: 'private' });
+
+ const updated = await personalModel.update('cg-personal-move', {
+ groupId: 'folder-personal-public',
+ });
+
+ expect(updated.groupId).toBe('folder-personal-public');
+ });
+ });
+
+ describe('publishToWorkspace guards', () => {
+ it('refuses an already shared group and another member private group', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-already-shared',
+ title: 'Shared',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await expect(workspaceModel.publishToWorkspace('cg-already-shared')).rejects.toThrow(
+ 'Chat group not found, already published, or access denied',
+ );
+
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-other-private',
+ title: 'Other member group',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await expect(workspaceModel.publishToWorkspace('cg-other-private')).rejects.toThrow(
+ 'Chat group not found, already published, or access denied',
+ );
+ });
+
+ it('releases a non-public folder and mirrors the supervisor on publish', async () => {
+ await serverDB.insert(sessionGroups).values({
+ id: 'folder-ws-private-publish',
+ name: 'Private folder',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-publish',
+ title: 'Private in private folder',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ groupId: 'folder-ws-private-publish',
+ });
+ await serverDB.insert(agentsTable).values({
+ id: 'agt-publish-sup',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-publish-sup',
+ chatGroupId: 'cg-publish',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ });
+
+ const published = await workspaceModel.publishToWorkspace('cg-publish');
+
+ expect(published.visibility).toBe('public');
+ expect(published.groupId).toBeNull();
+ await expect(readAgentVisibility('agt-publish-sup')).resolves.toBe('public');
+ });
+ });
+
+ describe('setVisibility', () => {
+ it('promotes the group and mirrors the synthetic supervisor', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-promote',
+ title: 'Private group',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(agentsTable).values({
+ id: 'agt-promote-sup',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-promote-sup',
+ chatGroupId: 'cg-promote',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ });
+
+ const updated = await workspaceModel.setVisibility('cg-promote', 'public');
+
+ expect(updated?.visibility).toBe('public');
+ await expect(readAgentVisibility('agt-promote-sup')).resolves.toBe('public');
+ });
+
+ it('releases the folder when the new visibility no longer matches it', async () => {
+ await serverDB.insert(sessionGroups).values({
+ id: 'folder-ws-public-demote',
+ name: 'Public folder',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-demote',
+ title: 'Public in public folder',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ groupId: 'folder-ws-public-demote',
+ });
+
+ const updated = await workspaceModel.setVisibility('cg-demote', 'private');
+
+ expect(updated?.visibility).toBe('private');
+ expect(updated?.groupId).toBeNull();
+ });
+
+ it('keeps the folder when its visibility still matches', async () => {
+ await serverDB.insert(sessionGroups).values({
+ id: 'folder-ws-private-keep',
+ name: 'Private folder',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-keep-folder',
+ title: 'Private in private folder',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ groupId: 'folder-ws-private-keep',
+ });
+
+ const updated = await workspaceModel.setVisibility('cg-keep-folder', 'private');
+
+ expect(updated?.groupId).toBe('folder-ws-private-keep');
+ });
+
+ it('returns null when the group is outside the caller scope', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-out-of-scope',
+ title: 'Other member private group',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ });
+
+ await expect(workspaceModel.setVisibility('cg-out-of-scope', 'public')).resolves.toBeNull();
+ });
+ });
+
+ describe('getGroupAgentsByGroupIds', () => {
+ it('returns an empty list for no group ids', async () => {
+ await expect(personalModel.getGroupAgentsByGroupIds([])).resolves.toEqual([]);
+ });
+
+ it('reads rosters across the requested groups and drops invisible members', async () => {
+ await serverDB.insert(chatGroups).values([
+ { id: 'cg-roster-1', title: 'Roster one', userId, workspaceId },
+ { id: 'cg-roster-2', title: 'Roster two', userId, workspaceId },
+ ]);
+ await serverDB.insert(agentsTable).values([
+ { id: 'agt-roster-shared', title: 'Shared', userId, visibility: 'public', workspaceId },
+ {
+ id: 'agt-roster-foreign-private',
+ title: 'Foreign private',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ {
+ agentId: 'agt-roster-shared',
+ chatGroupId: 'cg-roster-1',
+ order: 0,
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'agt-roster-foreign-private',
+ chatGroupId: 'cg-roster-1',
+ order: 1,
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'agt-roster-shared',
+ chatGroupId: 'cg-roster-2',
+ order: 0,
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ const rows = await workspaceModel.getGroupAgentsByGroupIds(['cg-roster-1', 'cg-roster-2']);
+
+ // Another member's private agent never leaks into the roster.
+ expect(rows.map((row) => `${row.chatGroupId}:${row.agentId}`)).toEqual([
+ 'cg-roster-1:agt-roster-shared',
+ 'cg-roster-2:agt-roster-shared',
+ ]);
+ });
+ });
+
+ describe('countPrivateGroupAgents', () => {
+ it('counts private member agents but never the synthetic supervisor', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'cg-count',
+ title: 'Private group',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(agentsTable).values([
+ {
+ id: 'agt-count-sup',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'agt-count-private',
+ title: 'Private member',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'agt-count-public',
+ title: 'Public member',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ {
+ agentId: 'agt-count-sup',
+ chatGroupId: 'cg-count',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'agt-count-private',
+ chatGroupId: 'cg-count',
+ order: 0,
+ role: 'participant',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'agt-count-public',
+ chatGroupId: 'cg-count',
+ order: 1,
+ role: 'participant',
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ await expect(workspaceModel.countPrivateGroupAgents('cg-count')).resolves.toBe(1);
+ // Workspace rows are invisible to a personal-scoped caller.
+ await expect(personalModel.countPrivateGroupAgents('cg-count')).resolves.toBe(0);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/expertise.rollup.test.ts b/packages/database/src/models/__tests__/expertise.rollup.test.ts
new file mode 100644
index 00000000000..4feebf189f3
--- /dev/null
+++ b/packages/database/src/models/__tests__/expertise.rollup.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ expertiseDomains,
+ expertiseDomainSnapshots,
+ expertiseLessons,
+ expertiseRuns,
+ users,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ExpertiseModel } from '../expertise';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'expertise-rollup-user';
+const otherUserId = 'expertise-rollup-other';
+
+const domainA = 'expertise-rollup-domain-a';
+const domainB = 'expertise-rollup-domain-b';
+
+const model = () => new ExpertiseModel(serverDB, userId);
+
+const seedDomain = async (id: string, owner = userId, slug = id) => {
+ await serverDB
+ .insert(expertiseDomains)
+ .values({ domainFilter: `${slug} filter`, id, slug, title: `${slug} title`, userId: owner });
+};
+
+const seedRun = async (
+ domainId: string,
+ runIndex: number,
+ overrides: Partial<typeof expertiseRuns.$inferInsert> = {},
+) => {
+ const [run] = await serverDB
+ .insert(expertiseRuns)
+ .values({
+ actorId: 'agent-1',
+ actorType: 'agent',
+ domainId,
+ runIndex,
+ subjectId: `topic-${runIndex}`,
+ subjectType: 'topic',
+ userId,
+ ...overrides,
+ })
+ .returning();
+ return run;
+};
+
+const seedLesson = async (
+ domainId: string,
+ overrides: Partial<typeof expertiseLessons.$inferInsert> & { code: string },
+) => {
+ const [lesson] = await serverDB
+ .insert(expertiseLessons)
+ .values({ domainId, polarity: 'rule', sections: [], title: overrides.code, ...overrides })
+ .returning();
+ return lesson;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await seedDomain(domainA);
+ await seedDomain(domainB);
+});
+
+describe('ExpertiseModel.latestSnapshots', () => {
+ it('keeps only the highest run of each domain', async () => {
+ await serverDB.insert(expertiseDomainSnapshots).values([
+ { activeCount: 1, domainId: domainA, learnedTotal: 1, runIndex: 1 },
+ { activeCount: 5, domainId: domainA, learnedTotal: 5, runIndex: 2 },
+ { activeCount: 3, domainId: domainB, learnedTotal: 3, runIndex: 1 },
+ ]);
+
+ const snapshots = await model().latestSnapshots([domainA, domainB]);
+
+ expect(snapshots).toHaveLength(2);
+ expect(snapshots.find((row) => row.domainId === domainA)?.activeCount).toBe(5);
+ expect(snapshots.find((row) => row.domainId === domainB)?.activeCount).toBe(3);
+ });
+
+ it('returns nothing for an empty request', async () => {
+ await expect(model().latestSnapshots([])).resolves.toEqual([]);
+ });
+
+ it('returns the full series in domain then run order', async () => {
+ await serverDB.insert(expertiseDomainSnapshots).values([
+ { activeCount: 1, domainId: domainB, learnedTotal: 1, runIndex: 2 },
+ { activeCount: 1, domainId: domainA, learnedTotal: 1, runIndex: 2 },
+ { activeCount: 1, domainId: domainA, learnedTotal: 1, runIndex: 1 },
+ ]);
+
+ const series = await model().seriesForDomains([domainA, domainB]);
+
+ expect(series.map((row) => [row.domainId, row.runIndex])).toEqual([
+ [domainA, 1],
+ [domainA, 2],
+ [domainB, 2],
+ ]);
+ await expect(model().seriesForDomains([])).resolves.toEqual([]);
+ });
+});
+
+describe('ExpertiseModel domain detail reads', () => {
+ it('lists one domain’s snapshot series and newest runs first', async () => {
+ await serverDB.insert(expertiseDomainSnapshots).values([
+ { activeCount: 1, domainId: domainA, learnedTotal: 1, runIndex: 2 },
+ { activeCount: 1, domainId: domainA, learnedTotal: 1, runIndex: 1 },
+ { activeCount: 9, domainId: domainB, learnedTotal: 9, runIndex: 1 },
+ ]);
+ await seedRun(domainA, 1);
+ await seedRun(domainA, 2);
+ await seedRun(domainA, 3);
+
+ const snapshots = await model().listSnapshots(domainA);
+ const runs = await model().listRuns(domainA, 2);
+
+ expect(snapshots.map((row) => row.runIndex)).toEqual([1, 2]);
+ expect(runs.map((row) => row.runIndex)).toEqual([3, 2]);
+ });
+
+ it('counts every run, independently of the page limit', async () => {
+ await seedRun(domainA, 1);
+ await seedRun(domainA, 2);
+ await seedRun(domainB, 1);
+
+ await expect(model().countRuns(domainA)).resolves.toBe(2);
+ await expect(model().countRuns('expertise-rollup-domain-none')).resolves.toBe(0);
+ });
+
+ it('reports human participation per run in run order', async () => {
+ await seedRun(domainA, 2, { hadHumanInLoop: true });
+ await seedRun(domainA, 1);
+
+ const flags = await model().runHumanFlags(domainA);
+
+ expect(flags).toEqual([
+ { hadHumanInLoop: false, runIndex: 1 },
+ { hadHumanInLoop: true, runIndex: 2 },
+ ]);
+ });
+
+ it('lists the agents that practised each domain, skipping human actors', async () => {
+ await seedRun(domainA, 1, { actorId: 'agent-1' });
+ await seedRun(domainA, 2, { actorId: 'agent-1' });
+ await seedRun(domainA, 3, { actorId: 'user-actor', actorType: 'user' });
+ await seedRun(domainB, 1, { actorId: 'agent-2' });
+
+ const actors = await model().actorsByDomain([domainA, domainB]);
+
+ expect(actors).toHaveLength(2);
+ expect(actors).toEqual(
+ expect.arrayContaining([
+ { actorId: 'agent-1', domainId: domainA },
+ { actorId: 'agent-2', domainId: domainB },
+ ]),
+ );
+ await expect(model().actorsByDomain([])).resolves.toEqual([]);
+ });
+
+ it('summarizes active lessons only', async () => {
+ await seedLesson(domainA, { code: 'L-1', hitCount: 3 });
+ await seedLesson(domainA, { code: 'L-2' });
+ await seedLesson(domainA, { code: 'L-3', hitCount: 100, status: 'rejected' });
+
+ await expect(model().lessonStats(domainA)).resolves.toEqual({ hits: 3, total: 2, unused: 1 });
+ });
+});
+
+describe('ExpertiseModel lesson library reads', () => {
+ const tiers: Record<string, number> = { 'L-core': 10, 'L-tied': 4, 'L-niche': 3, 'L-unused': 0 };
+
+ beforeEach(async () => {
+ for (const [code, hitCount] of Object.entries(tiers)) {
+ await seedLesson(domainA, { code, hitCount, layer: code === 'L-niche' ? 'L2' : 'L1' });
+ }
+ });
+
+ it('assigns core / niche / unused tiers from the domain’s hit distribution', async () => {
+ const lessons = await model().listLessons(domainA);
+
+ expect(Object.fromEntries(lessons.map((row) => [row.code, row.tier]))).toEqual({
+ 'L-core': 'core',
+ 'L-niche': 'niche',
+ 'L-tied': 'core',
+ 'L-unused': 'unused',
+ });
+ });
+
+ it('filters by layer and by a case-insensitive title search', async () => {
+ const byLayer = await model().listLessons(domainA, { layer: 'L2' });
+ await seedLesson(domainA, { code: 'L-cache', hitCount: 1, title: 'Cache the PAT' });
+ const bySearch = await model().listLessons(domainA, { search: 'pat' });
+
+ expect(byLayer.map((row) => row.code)).toEqual(['L-niche']);
+ expect(bySearch.map((row) => row.code)).toEqual(['L-cache']);
+ });
+
+ it('counts lessons per declared layer, ignoring unlayered ones', async () => {
+ await seedLesson(domainA, { code: 'L-null', hitCount: 1 });
+
+ await expect(model().layerCounts(domainA)).resolves.toEqual({ L1: 3, L2: 1 });
+ });
+
+ it('counts lessons per canon anchor and reports the unanchored bucket', async () => {
+ await seedLesson(domainA, { canonAnchor: 'rule:cache', code: 'L-anchored-1', hitCount: 1 });
+ await seedLesson(domainA, { canonAnchor: 'rule:cache', code: 'L-anchored-2', hitCount: 1 });
+
+ const counts = await model().canonAnchorCounts(domainA);
+
+ expect(counts.byKey).toEqual({ 'rule:cache': 2 });
+ expect(counts.unanchored).toBe(4);
+ });
+});
+
+describe('ExpertiseModel domain scoping', () => {
+ it('never reads the lesson library of another owner’s domain', async () => {
+ await seedDomain('expertise-rollup-domain-theirs', otherUserId);
+ await seedLesson('expertise-rollup-domain-theirs', { code: 'L-theirs', hitCount: 3 });
+
+ await expect(model().listLessons('expertise-rollup-domain-theirs')).resolves.toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/__tests__/goal.config.test.ts b/packages/database/src/models/__tests__/goal.config.test.ts
new file mode 100644
index 00000000000..760a9814b6b
--- /dev/null
+++ b/packages/database/src/models/__tests__/goal.config.test.ts
@@ -0,0 +1,420 @@
+// @vitest-environment node
+import { GOAL_CLARIFICATION_TITLE } from '@lobechat/const/goal';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ goalNodes,
+ projects,
+ tasks,
+ taskTopics,
+ topics,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'goal-config-test-user-id';
+const otherUserId = 'goal-config-test-user-2';
+const goalModel = new GoalModel(serverDB, userId);
+const graphModel = new GoalGraphModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+describe('GoalModel coordinator config', () => {
+ describe('config patches', () => {
+ it('patches only the task agent id, and clears it again with null', async () => {
+ const goal = await goalModel.create({
+ config: { acceptance: { criteriaIds: ['c1'] } },
+ subjectType: 'standalone',
+ title: 'Agent bound',
+ });
+
+ const bound = await goalModel.updateTaskAgentId(goal.id, 'task-agent-1');
+ expect(bound?.config).toMatchObject({
+ acceptance: { criteriaIds: ['c1'] },
+ taskAgentId: 'task-agent-1',
+ });
+
+ const cleared = await goalModel.updateTaskAgentId(goal.id, null);
+ expect(cleared?.config?.taskAgentId).toBeUndefined();
+ // The clear is a patch, not a whole-config write: the budget survives.
+ expect(cleared?.config).toMatchObject({ acceptance: { criteriaIds: ['c1'] } });
+
+ expect(
+ await new GoalModel(serverDB, otherUserId).updateTaskAgentId(goal.id, 'stolen'),
+ ).toBeUndefined();
+ });
+
+ it('arms a quota retry wake only when it is the earliest one', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Quota wake' });
+ const at = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString();
+
+ // Nothing armed yet, so the first tick takes it.
+ expect(await goalModel.armQuotaRetryWake(goal.id, at(60))).toBe(true);
+ // A later tick cannot push the wake already queued further out.
+ expect(await goalModel.armQuotaRetryWake(goal.id, at(120))).toBe(false);
+ // An earlier one takes over — it fires before the callback already queued.
+ expect(await goalModel.armQuotaRetryWake(goal.id, at(30))).toBe(true);
+ // A wake already in the past is spent, so the next tick may arm again.
+ expect(await goalModel.armQuotaRetryWake(goal.id, at(-10))).toBe(true);
+ expect(await goalModel.armQuotaRetryWake(goal.id, at(45))).toBe(true);
+ // Another scope never arms it.
+ expect(await new GoalModel(serverDB, otherUserId).armQuotaRetryWake(goal.id, at(1))).toBe(
+ false,
+ );
+ });
+
+ it('patches understanding and rollout state without touching the rest of config', async () => {
+ const goal = await goalModel.create({
+ config: { pausedBy: 'user' },
+ subjectType: 'standalone',
+ title: 'Coordinator-owned config',
+ });
+ const understanding = {
+ assumptions: ['the repository is public'],
+ level: 'medium' as const,
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ };
+ const rolloutState = {
+ batchNodeId: 'batch-1',
+ phase: 'probe' as const,
+ probeNodeIds: ['probe-1'],
+ templateRevision: 1,
+ waveIndex: 0,
+ };
+
+ await goalModel.updateUnderstanding(goal.id, understanding);
+ expect((await goalModel.findById(goal.id))?.config).toMatchObject({
+ pausedBy: 'user',
+ understanding,
+ });
+
+ await goalModel.updateRolloutState(goal.id, rolloutState);
+ expect((await goalModel.findById(goal.id))?.config?.rolloutState).toEqual(rolloutState);
+
+ // Passing null clears the batch, and nothing else goes with it.
+ await goalModel.updateRolloutState(goal.id, null);
+ const cleared = (await goalModel.findById(goal.id))?.config;
+ expect(cleared?.rolloutState).toBeUndefined();
+ expect(cleared).toMatchObject({ pausedBy: 'user', understanding });
+ });
+
+ it('opens a manager policy only when none is set, and closes only its own hand-over', async () => {
+ const goal = await goalModel.create({
+ config: { pausedBy: 'user' },
+ subjectType: 'standalone',
+ title: 'Hand-over',
+ });
+
+ await goalModel.openManagerPolicy(goal.id, { openedForHandoff: 'handoff-1' });
+ expect((await goalModel.findById(goal.id))?.config?.manager).toEqual({
+ openedForHandoff: 'handoff-1',
+ });
+
+ // A policy already there — the person's, or a newer hand-over's — stays.
+ await goalModel.openManagerPolicy(goal.id, { instruction: 'take over' });
+ expect((await goalModel.findById(goal.id))?.config?.manager).toEqual({
+ openedForHandoff: 'handoff-1',
+ });
+
+ // A token that did not open it cannot remove it either.
+ await goalModel.closeHandoffManagerPolicy(goal.id, 'handoff-2');
+ expect((await goalModel.findById(goal.id))?.config?.manager).toEqual({
+ openedForHandoff: 'handoff-1',
+ });
+
+ await goalModel.closeHandoffManagerPolicy(goal.id, 'handoff-1');
+ const closed = (await goalModel.findById(goal.id))?.config;
+ expect(closed?.manager).toBeUndefined();
+ expect(closed).toMatchObject({ pausedBy: 'user' });
+ });
+
+ it('patches one model slot at a time, and clears only that slot with null', async () => {
+ const goal = await goalModel.create({
+ config: { acceptance: { criteriaIds: ['c1'] } },
+ subjectType: 'standalone',
+ title: 'Model slots',
+ });
+
+ // No slot named: the planning turn is the default.
+ await goalModel.updateModelConfig(goal.id, { model: 'gpt-5', provider: 'openai' });
+ let config = (await goalModel.findById(goal.id))?.config;
+ expect(config).toMatchObject({ model: 'gpt-5', provider: 'openai' });
+ expect(config?.taskModel).toBeUndefined();
+
+ // The Task slot is written beside the planning one, not over it.
+ await goalModel.updateModelConfig(
+ goal.id,
+ { model: 'claude', provider: 'anthropic' },
+ 'task',
+ );
+ config = (await goalModel.findById(goal.id))?.config;
+ expect(config).toMatchObject({
+ model: 'gpt-5',
+ provider: 'openai',
+ taskModel: 'claude',
+ taskProvider: 'anthropic',
+ });
+
+ // Clearing the planning slot leaves the Task slot and the budget alone.
+ await goalModel.updateModelConfig(goal.id, null);
+ config = (await goalModel.findById(goal.id))?.config;
+ expect(config?.model).toBeUndefined();
+ expect(config?.provider).toBeUndefined();
+ expect(config?.taskModel).toBe('claude');
+ expect(config).toMatchObject({ acceptance: { criteriaIds: ['c1'] } });
+
+ await goalModel.updateModelConfig(goal.id, null, 'task');
+ config = (await goalModel.findById(goal.id))?.config;
+ expect(config?.taskModel).toBeUndefined();
+ expect(config?.taskProvider).toBeUndefined();
+ expect(config).toMatchObject({ acceptance: { criteriaIds: ['c1'] } });
+
+ expect(
+ await new GoalModel(serverDB, otherUserId).updateModelConfig(goal.id, {
+ model: 'stolen',
+ provider: 'stolen',
+ }),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('node lookups', () => {
+ it('resolves the goal that owns a graph node, inside the owner scope', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Node owner' });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });
+
+ expect((await goalModel.findByNode(node!.id))?.id).toBe(goal.id);
+ expect(await new GoalModel(serverDB, otherUserId).findByNode(node!.id)).toBeUndefined();
+ expect(await goalModel.findByNode('00000000-0000-0000-0000-000000000000')).toBeUndefined();
+ });
+ });
+
+ describe('planning lease gating', () => {
+ it('refuses a lease once the graph already has a task', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Decomposed' });
+ await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });
+
+ expect(await goalModel.claimPlanning(goal.id)).toBeUndefined();
+ });
+ });
+
+ describe('pending gates', () => {
+ it('lists the clarification rounds a goal is still waiting on', async () => {
+ const waiting = await goalModel.create({ subjectType: 'standalone', title: 'Waiting' });
+ const round = await graphModel.createNode(waiting.id, {
+ kind: 'decision',
+ title: GOAL_CLARIFICATION_TITLE,
+ });
+ await graphModel.createDecision(waiting.id, round!.id, {
+ authority: 'user',
+ question: 'which one?',
+ });
+
+ // A goal the user paused keeps its open questions without nagging.
+ const paused = await goalModel.create({ subjectType: 'standalone', title: 'Paused' });
+ const pausedRound = await graphModel.createNode(paused.id, {
+ kind: 'decision',
+ title: GOAL_CLARIFICATION_TITLE,
+ });
+ await graphModel.createDecision(paused.id, pausedRound!.id, {
+ authority: 'user',
+ question: 'still asked?',
+ });
+ await goalModel.updateStatus(paused.id, 'paused');
+
+ const asks = await goalModel.listPendingClarifications();
+
+ expect(asks.map((row) => row.goalId)).toEqual([waiting.id]);
+ expect(asks[0]).toMatchObject({ question: 'which one?' });
+ });
+
+ it('lists the gates waiting on a person, and leaves clarification to the form', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Gated' });
+ const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship it?' });
+ await graphModel.createDecision(goal.id, gate!.id, {
+ authority: 'user',
+ question: 'ship?',
+ });
+ // The Task the gate was opened for is what the question is about.
+ const work = await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });
+ await graphModel.createEdge(goal.id, work!.id, gate!.id, 'leads_to');
+
+ const clarification = await graphModel.createNode(goal.id, {
+ kind: 'decision',
+ title: GOAL_CLARIFICATION_TITLE,
+ });
+ await graphModel.createDecision(goal.id, clarification!.id, {
+ authority: 'user',
+ question: 'asked as one form',
+ });
+
+ // The coordinator's own gates are not the person's to answer.
+ const agentGate = await graphModel.createNode(goal.id, {
+ kind: 'decision',
+ title: 'Agent asked',
+ });
+ await graphModel.createDecision(goal.id, agentGate!.id, {
+ authority: 'agent',
+ question: 'agent?',
+ });
+
+ const rows = await goalModel.listPendingDecisions();
+
+ expect(rows.map((row) => row.nodeTitle)).toEqual(['Ship it?']);
+ expect(rows[0]).toMatchObject({ goalId: goal.id, sourceTitle: 'W1' });
+ });
+
+ it('hides a gate addressed to somebody else', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Shared goal' });
+ const mine = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Mine' });
+ await graphModel.createDecision(goal.id, mine!.id, { authority: 'user', question: 'yours?' });
+ const theirs = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Theirs' });
+ await graphModel.createDecision(goal.id, theirs!.id, {
+ authority: 'user',
+ question: 'theirs?',
+ requestedUserId: otherUserId,
+ });
+
+ expect((await goalModel.listPendingDecisions()).map((row) => row.nodeTitle)).toEqual([
+ 'Mine',
+ ]);
+ });
+ });
+
+ describe('list filters and run roll-up', () => {
+ it('scopes the list to a project or to the topic a goal came from', async () => {
+ const agentId = 'goal-list-project-agent';
+ await serverDB.insert(agents).values({ id: agentId, slug: agentId, userId });
+ await serverDB.insert(projects).values({
+ coordinatorAgentId: agentId,
+ id: 'goal-list-project',
+ identifier: 'PRJ',
+ name: 'Goal project',
+ userId,
+ });
+
+ const inProject = await goalModel.create({
+ projectId: 'goal-list-project',
+ subjectType: 'standalone',
+ title: 'In a project',
+ });
+ const fromTopic = await goalModel.create({
+ subjectId: 'goal-list-topic-1',
+ subjectType: 'topic',
+ title: 'From a topic',
+ });
+ const loose = await goalModel.create({ subjectType: 'standalone', title: 'Loose' });
+ for (const created of [inProject, fromTopic, loose]) {
+ await graphModel.createNode(created.id, { kind: 'task', title: 'W1' });
+ }
+
+ expect(
+ (await goalModel.list({ projectId: 'goal-list-project' })).goals.map((row) => row.goal.id),
+ ).toEqual([inProject.id]);
+ expect(
+ (await goalModel.list({ topicId: 'goal-list-topic-1' })).goals.map((row) => row.goal.id),
+ ).toEqual([fromTopic.id]);
+ });
+
+ it('rolls up the runs of the tasks the graph dispatched, and pages past the end', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Costly' });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: 'goal-run-task',
+ identifier: 'T-RUN',
+ instruction: 'do it',
+ seq: 1,
+ });
+ await serverDB
+ .update(goalNodes)
+ .set({ taskId: 'goal-run-task' })
+ .where(eq(goalNodes.id, node!.id));
+
+ await serverDB.insert(topics).values({ id: 'goal-run-topic', userId });
+ await serverDB.insert(taskTopics).values({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ seq: 1,
+ taskId: 'goal-run-task',
+ topicId: 'goal-run-topic',
+ userId,
+ });
+ await serverDB
+ .update(topics)
+ .set({ completedAt: new Date('2026-01-01T00:01:00Z'), totalCost: 3 })
+ .where(eq(topics.id, 'goal-run-topic'));
+
+ const { goals: items } = await goalModel.list();
+ expect(items[0]).toMatchObject({ totalRunCost: 3, totalRunDuration: 60_000 });
+
+ // Paging past the end still reports the total, with no rows to roll up.
+ const paged = await goalModel.list({ offset: 50 });
+ expect(paged.total).toBe(1);
+ expect(paged.goals).toEqual([]);
+ });
+
+ it('rolls up runs for a workspace-scoped goal too', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: 'goal-ws', name: 'goal-ws', primaryOwnerId: userId, slug: 'goal-ws' });
+ const workspaceModel = new GoalModel(serverDB, userId, 'goal-ws');
+ const goal = await workspaceModel.create({ subjectType: 'standalone', title: 'Workspace' });
+ const node = await new GoalGraphModel(serverDB, userId, 'goal-ws').createNode(goal.id, {
+ kind: 'task',
+ title: 'W1',
+ });
+
+ // Same shape as the personal roll-up above, but the task only reaches the
+ // graph through the workspace branch of the ownership predicate — and a
+ // workspace goal that rolled up nothing would still list a row.
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: 'goal-ws-run-task',
+ identifier: 'T-WSRUN',
+ instruction: 'do it',
+ seq: 1,
+ workspaceId: 'goal-ws',
+ });
+ await serverDB
+ .update(goalNodes)
+ .set({ taskId: 'goal-ws-run-task' })
+ .where(eq(goalNodes.id, node!.id));
+
+ await serverDB
+ .insert(topics)
+ .values({ id: 'goal-ws-run-topic', userId, workspaceId: 'goal-ws' });
+ await serverDB.insert(taskTopics).values({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ seq: 1,
+ taskId: 'goal-ws-run-task',
+ topicId: 'goal-ws-run-topic',
+ userId,
+ workspaceId: 'goal-ws',
+ });
+ await serverDB
+ .update(topics)
+ .set({ completedAt: new Date('2026-01-01T00:01:00Z'), totalCost: 7 })
+ .where(eq(topics.id, 'goal-ws-run-topic'));
+
+ const { goals: items } = await workspaceModel.list();
+
+ expect(items.map((row) => row.goal.id)).toEqual([goal.id]);
+ expect(items[0]).toMatchObject({ totalRunCost: 7, totalRunDuration: 60_000 });
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/goalGraph.trail.test.ts b/packages/database/src/models/__tests__/goalGraph.trail.test.ts
new file mode 100644
index 00000000000..efa90705547
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalGraph.trail.test.ts
@@ -0,0 +1,400 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ goalEvents,
+ goalNodeDecisions,
+ goalNodes,
+ goalNodeWorkVersions,
+ goals,
+ tasks,
+ users,
+ works,
+ workVersions,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'goal-trail-user';
+const otherUserId = 'goal-trail-other';
+
+const graphModel = new GoalGraphModel(serverDB, userId);
+
+const createGoal = async (title = 'Trail goal', owner = userId) =>
+ new GoalModel(serverDB, owner).create({ subjectType: 'standalone', title });
+
+/** Goals start in `planning`; only a `draft` may lose nodes. */
+const asDraft = async (goalId: string) => {
+ await serverDB.update(goals).set({ status: 'draft' }).where(eq(goals.id, goalId));
+};
+
+const seedEvent = async (
+ goalId: string,
+ overrides: Partial<typeof goalEvents.$inferInsert> = {},
+) => {
+ const [event] = await serverDB
+ .insert(goalEvents)
+ .values({
+ actorId: userId,
+ actorType: 'user',
+ entityId: 'entity-1',
+ entityType: 'node',
+ eventType: 'created',
+ goalId,
+ ...overrides,
+ })
+ .returning();
+ return event;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+describe('GoalGraphModel.listEvents', () => {
+ it('returns undefined for a goal the caller cannot see', async () => {
+ const theirs = await createGoal('Theirs', otherUserId);
+
+ await expect(graphModel.listEvents(theirs.id, { limit: 10 })).resolves.toBeUndefined();
+ await expect(
+ graphModel.listEvents('00000000-0000-4000-8000-0000000000ff', { limit: 10 }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('pages newest first across one-millisecond ties without dropping a row', async () => {
+ const goal = await createGoal();
+ const ids = [
+ '00000000-0000-4000-8000-00000000000a',
+ '00000000-0000-4000-8000-00000000000b',
+ '00000000-0000-4000-8000-00000000000c',
+ ];
+ // Same instant for all three: a cursor that compared the raw column against a
+ // millisecond cursor would leave the leftover row unreachable.
+ for (const id of ids) {
+ await seedEvent(goal.id, { createdAt: new Date('2026-04-01T00:00:00.000Z'), id });
+ }
+
+ const first = await graphModel.listEvents(goal.id, { limit: 2 });
+ const second = await graphModel.listEvents(goal.id, {
+ cursor: first!.nextCursor,
+ limit: 2,
+ });
+
+ expect(first!.events.map((event) => event.id)).toEqual([ids[2], ids[1]]);
+ expect(first!.nextCursor).toMatchObject({ id: ids[1] });
+ expect(second!.events.map((event) => event.id)).toEqual([ids[0]]);
+ expect(second!.nextCursor).toBeUndefined();
+ });
+
+ it('filters by entity and event type, and stops at an exact page', async () => {
+ const goal = await createGoal();
+ await seedEvent(goal.id, { entityType: 'node', eventType: 'created' });
+ await seedEvent(goal.id, { entityType: 'node', eventType: 'updated' });
+ await seedEvent(goal.id, { entityType: 'goal', eventType: 'created' });
+
+ const nodes = await graphModel.listEvents(goal.id, { entityType: 'node', limit: 10 });
+ const created = await graphModel.listEvents(goal.id, { eventType: 'created', limit: 10 });
+ const both = await graphModel.listEvents(goal.id, {
+ entityType: 'node',
+ eventType: 'created',
+ limit: 1,
+ });
+
+ expect(nodes!.events).toHaveLength(2);
+ expect(created!.events).toHaveLength(2);
+ expect(both!.events).toHaveLength(1);
+ expect(both!.nextCursor).toBeUndefined();
+ });
+});
+
+describe('GoalGraphModel.recordGoalUpdate', () => {
+ it('appends an updated event on the goal with its reason and operation', async () => {
+ const goal = await createGoal();
+
+ await graphModel.recordGoalUpdate(goal.id, {
+ operationId: 'op-bind',
+ reason: 'bound to topic',
+ });
+
+ const { events } = (await graphModel.listEvents(goal.id, { limit: 10 }))!;
+ expect(events[0]).toMatchObject({
+ actorId: userId,
+ actorType: 'user',
+ entityId: goal.id,
+ entityType: 'goal',
+ eventType: 'updated',
+ operationId: 'op-bind',
+ reason: 'bound to topic',
+ });
+ });
+});
+
+describe('GoalGraphModel.listProducedWorkIds', () => {
+ it('returns the Works declared as produced, ignoring other relations', async () => {
+ const goal = await createGoal();
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Deliver' });
+ const [producedWork] = await serverDB
+ .insert(works)
+ .values({
+ resourceType: 'task',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ type: 'task',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+ const [relatedWork] = await serverDB
+ .insert(works)
+ .values({
+ resourceType: 'task',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ type: 'task',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+ const versions = await serverDB
+ .insert(workVersions)
+ .values([
+ {
+ changeType: 'created',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ version: 1,
+ workId: producedWork.id,
+ },
+ {
+ changeType: 'created',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ version: 1,
+ workId: relatedWork.id,
+ },
+ ])
+ .returning();
+ await serverDB.insert(goalNodeWorkVersions).values([
+ { nodeId: node!.id, relation: 'produced', workVersionId: versions[0].id },
+ { nodeId: node!.id, relation: 'related', workVersionId: versions[1].id },
+ ]);
+
+ const produced = await graphModel.listProducedWorkIds(goal.id);
+
+ expect([...produced]).toEqual([producedWork.id]);
+ });
+});
+
+describe('GoalGraphModel.countRunningTasks', () => {
+ it('counts only live task nodes, not retired or untracked ones', async () => {
+ const goal = await createGoal();
+ const seedTask = async (id: string, status: string) => {
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id,
+ identifier: id,
+ instruction: 'run it',
+ seq: 1,
+ status,
+ });
+ return id;
+ };
+ await seedTask('task-running', 'running');
+ await seedTask('task-scheduled', 'scheduled');
+ await seedTask('task-done', 'completed');
+ await serverDB.insert(goalNodes).values([
+ { goalId: goal.id, kind: 'task', taskId: 'task-running', title: 'a' },
+ { goalId: goal.id, kind: 'task', taskId: 'task-scheduled', title: 'b' },
+ { goalId: goal.id, kind: 'task', taskId: 'task-done', title: 'c' },
+ { goalId: goal.id, kind: 'task', title: 'not dispatched' },
+ { goalId: goal.id, kind: 'problem', title: 'not a task' },
+ ]);
+
+ await expect(graphModel.countRunningTasks(goal.id)).resolves.toBe(2);
+ });
+});
+
+describe('GoalGraphModel.removeDraftNodes', () => {
+ it('removes unbound nodes of a draft and records one unlinked event each', async () => {
+ const goal = await createGoal();
+ await asDraft(goal.id);
+ const first = await graphModel.createNode(goal.id, { kind: 'finding', title: 'drop me' });
+ const second = await graphModel.createNode(goal.id, { kind: 'finding', title: 'keep me' });
+
+ const removed = await graphModel.removeDraftNodes(goal.id, [first!.id], 'planner re-scope');
+
+ expect(removed).toBe(1);
+ const { events } = (await graphModel.getGraph(goal.id))!;
+ expect(events[0]).toMatchObject({
+ entityId: first!.id,
+ eventType: 'unlinked',
+ reason: 'planner re-scope',
+ });
+ expect(
+ events.find((event) => event.entityId === second!.id && event.eventType === 'unlinked'),
+ ).toBeUndefined();
+ });
+
+ it('returns 0 for an empty list or a goal it cannot see', async () => {
+ const goal = await createGoal();
+ await asDraft(goal.id);
+ const theirs = await createGoal('Theirs', otherUserId);
+
+ await expect(graphModel.removeDraftNodes(goal.id, [], 'nothing')).resolves.toBe(0);
+ await expect(graphModel.removeDraftNodes(theirs.id, ['x'], 'nope')).resolves.toBe(0);
+ });
+
+ it('refuses nodes bound to a task and goals that already started', async () => {
+ const goal = await createGoal();
+ await asDraft(goal.id);
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: 'task-bound',
+ identifier: 'task-bound',
+ instruction: 'run it',
+ seq: 1,
+ status: 'backlog',
+ });
+ const bound = await graphModel.createNode(goal.id, { kind: 'task', title: 'bound' });
+ await serverDB
+ .update(goalNodes)
+ .set({ taskId: 'task-bound' })
+ .where(eq(goalNodes.id, bound!.id));
+
+ await expect(graphModel.removeDraftNodes(goal.id, [bound!.id], 'nope')).rejects.toThrow(
+ /Only unbound nodes/,
+ );
+
+ const started = await createGoal('Started');
+ await serverDB.update(goals).set({ status: 'active' }).where(eq(goals.id, started.id));
+ await expect(graphModel.removeDraftNodes(started.id, ['x'], 'nope')).rejects.toThrow(
+ /Only a draft Goal/,
+ );
+ });
+});
+
+describe('GoalGraphModel.updateNodeDescription', () => {
+ it('writes the description and the confidence when one is given', async () => {
+ const goal = await createGoal();
+ const node = await graphModel.createNode(goal.id, { kind: 'problem', title: 'Problem' });
+
+ const updated = await graphModel.updateNodeDescription(goal.id, node!.id, 'refined', 0.8);
+ const withoutConfidence = await graphModel.createNode(goal.id, {
+ kind: 'finding',
+ title: 'Finding',
+ });
+ await graphModel.updateNodeDescription(goal.id, withoutConfidence!.id, 'plain');
+
+ expect(updated).toMatchObject({ description: 'refined', confidence: '0.800' });
+ const plain = await serverDB.query.goalNodes.findFirst({
+ where: eq(goalNodes.id, withoutConfidence!.id),
+ });
+ expect(plain).toMatchObject({ confidence: null, description: 'plain' });
+ await expect(
+ graphModel.updateNodeDescription(goal.id, '00000000-0000-4000-8000-0000000000ff', 'x'),
+ ).resolves.toBeUndefined();
+ });
+});
+
+describe('GoalGraphModel decision maintenance', () => {
+ const options = [
+ { id: 'ship', label: 'Ship it' },
+ { id: 'hold', label: 'Hold' },
+ ];
+
+ const pendingDecision = async () => {
+ const goal = await createGoal('Decision goal');
+ const node = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });
+ const decision = await graphModel.createDecision(goal.id, node!.id, {
+ authority: 'user',
+ options,
+ question: 'Ship it?',
+ });
+ return { decision: decision!, goal, node: node! };
+ };
+
+ /**
+ * A pending decision filed under a goal the caller does not own.
+ *
+ * `pendingDecision` creates both halves as the caller, so the goal/decision
+ * pair itself is what a foreign call would be rejected by. Here the pair
+ * belongs together under `owner`, which leaves only the ownership check
+ * between the caller and the decision.
+ */
+ const foreignPendingDecision = async (owner: string) => {
+ const graph = new GoalGraphModel(serverDB, owner);
+ const goal = await createGoal('Decision goal', owner);
+ const node = await graph.createNode(goal.id, { kind: 'decision', title: 'Ship?' });
+ const decision = await graph.createDecision(goal.id, node!.id, {
+ authority: 'user',
+ options,
+ question: 'Ship it?',
+ });
+ return { decision: decision!, goal, node: node! };
+ };
+
+ it('rewrites the options while the decision is pending', async () => {
+ const { decision, goal } = await pendingDecision();
+
+ const updated = await graphModel.updatePendingDecisionOptions(goal.id, decision.id, [
+ { id: 'ship', label: 'Ship it now' },
+ ]);
+
+ expect(updated?.options).toEqual([{ id: 'ship', label: 'Ship it now' }]);
+ await expect(
+ graphModel.updatePendingDecisionOptions(goal.id, decision.id, options),
+ ).resolves.not.toBeUndefined();
+ });
+
+ it('leaves a settled decision on the options it was answered against', async () => {
+ const { decision, goal } = await pendingDecision();
+ await graphModel.resolveDecision(goal.id, decision.id, 'ship');
+
+ await expect(
+ graphModel.updatePendingDecisionOptions(goal.id, decision.id, options),
+ ).resolves.toBeUndefined();
+ });
+
+ it('cancels a pending decision and retires its node', async () => {
+ const { decision, goal, node } = await pendingDecision();
+
+ const canceled = await graphModel.cancelDecision(goal.id, decision.id, 'question went away');
+
+ expect(canceled).toMatchObject({ id: decision.id, status: 'canceled' });
+ const reloaded = await serverDB.query.goalNodes.findFirst({
+ where: eq(goalNodes.id, node.id),
+ });
+ expect(reloaded?.status).toBe('retired');
+ const { events } = (await graphModel.getGraph(goal.id))!;
+ expect(events[0]).toMatchObject({
+ entityId: decision.id,
+ eventType: 'retired',
+ reason: 'question went away',
+ });
+ // Nobody picked an option — a second cancel has nothing left to settle.
+ await expect(graphModel.cancelDecision(goal.id, decision.id, 'again')).resolves.toBeUndefined();
+ });
+
+ it('refuses decisions on a goal it cannot see', async () => {
+ const { decision, goal, node } = await foreignPendingDecision(otherUserId);
+
+ await expect(graphModel.cancelDecision(goal.id, decision.id, 'nope')).resolves.toBeUndefined();
+ await expect(
+ graphModel.updatePendingDecisionOptions(goal.id, decision.id, options),
+ ).resolves.toBeUndefined();
+
+ // The decision really does hang off the goal the call named — only the
+ // owner check stopped it, so a dropped `ownedGoal` would reach real rows.
+ const reloaded = await serverDB.query.goalNodeDecisions.findFirst({
+ where: eq(goalNodeDecisions.nodeId, node.id),
+ });
+ expect(reloaded).toMatchObject({ id: decision.id, status: 'pending' });
+ expect(reloaded?.canceledAt).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/knowledgeBase.usage.test.ts b/packages/database/src/models/__tests__/knowledgeBase.usage.test.ts
new file mode 100644
index 00000000000..a5f15d563b2
--- /dev/null
+++ b/packages/database/src/models/__tests__/knowledgeBase.usage.test.ts
@@ -0,0 +1,195 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ documents,
+ files,
+ globalFiles,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { KnowledgeBaseModel } from '../knowledgeBase';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'kb-usage-user';
+const otherUserId = 'kb-usage-other';
+
+const model = new KnowledgeBaseModel(serverDB, userId);
+
+const seedFile = async (id: string, size: number, ownerId = userId) => {
+ await serverDB.insert(globalFiles).values({
+ creator: ownerId,
+ fileType: 'application/pdf',
+ hashId: `hash-${id}`,
+ size,
+ url: `https://example.com/${id}.pdf`,
+ });
+ await serverDB.insert(files).values({
+ fileHash: `hash-${id}`,
+ fileType: 'application/pdf',
+ id,
+ name: `${id}.pdf`,
+ size,
+ url: `https://example.com/${id}.pdf`,
+ userId: ownerId,
+ });
+};
+
+const linkFile = async (
+ knowledgeBaseId: string,
+ fileId: string,
+ ownerId = userId,
+ workspaceId?: string,
+) => {
+ await serverDB
+ .insert(knowledgeBaseFiles)
+ .values({ fileId, knowledgeBaseId, userId: ownerId, workspaceId });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(globalFiles);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(globalFiles);
+});
+
+describe('KnowledgeBaseModel.countFileUsage', () => {
+ it('sums the size of every file linked to the knowledge base', async () => {
+ const { id: kbId } = await model.create({ name: 'Usage' });
+ await seedFile('usage-a', 120);
+ await seedFile('usage-b', 80);
+ await linkFile(kbId, 'usage-a');
+ await linkFile(kbId, 'usage-b');
+
+ await expect(model.countFileUsage(kbId)).resolves.toBe(200);
+ });
+
+ it('returns 0 when the knowledge base has no files', async () => {
+ const { id: kbId } = await model.create({ name: 'Empty' });
+
+ await expect(model.countFileUsage(kbId)).resolves.toBe(0);
+ });
+
+ it("does not count another user's links for the same knowledge base", async () => {
+ const { id: kbId } = await model.create({ name: 'Mixed links' });
+ await seedFile('usage-mine', 50);
+ await seedFile('usage-theirs', 500, otherUserId);
+ await linkFile(kbId, 'usage-mine');
+ await linkFile(kbId, 'usage-theirs', otherUserId);
+
+ await expect(model.countFileUsage(kbId)).resolves.toBe(50);
+ });
+});
+
+describe('KnowledgeBaseModel.hasForeignLinkedRows', () => {
+ it('returns false when every linked row belongs to the caller', async () => {
+ const { id: kbId } = await model.create({ name: 'Owned' });
+ await seedFile('foreign-none', 10);
+ await linkFile(kbId, 'foreign-none');
+
+ await expect(model.hasForeignLinkedRows(kbId)).resolves.toBe(false);
+ });
+
+ it('returns true when a linked file belongs to someone else', async () => {
+ const { id: kbId } = await model.create({ name: 'Shared file' });
+ await seedFile('foreign-file', 10, otherUserId);
+ await linkFile(kbId, 'foreign-file');
+
+ await expect(model.hasForeignLinkedRows(kbId)).resolves.toBe(true);
+ });
+
+ it('returns true when a derived document belongs to someone else', async () => {
+ const { id: kbId } = await model.create({ name: 'Foreign doc' });
+ await serverDB.insert(documents).values({
+ content: 'teammate content',
+ fileType: 'text/plain',
+ id: 'docs_foreign_doc',
+ knowledgeBaseId: kbId,
+ source: 'note.txt',
+ sourceType: 'file',
+ title: 'Teammate note',
+ totalCharCount: 16,
+ totalLineCount: 1,
+ userId: otherUserId,
+ });
+
+ await expect(model.hasForeignLinkedRows(kbId)).resolves.toBe(true);
+ });
+
+ it('checks documents by linked file when the caller owns the files', async () => {
+ const { id: kbId } = await model.create({ name: 'Derived' });
+ await seedFile('foreign-derived', 10);
+ await linkFile(kbId, 'foreign-derived');
+ await serverDB.insert(documents).values({
+ content: 'mine',
+ fileId: 'foreign-derived',
+ fileType: 'application/pdf',
+ id: 'docs_mine',
+ source: 'foreign-derived.pdf',
+ sourceType: 'file',
+ title: 'Mine',
+ totalCharCount: 4,
+ totalLineCount: 1,
+ userId,
+ });
+
+ await expect(model.hasForeignLinkedRows(kbId)).resolves.toBe(false);
+ });
+});
+
+describe('KnowledgeBaseModel.deleteAllWithFiles creator scope', () => {
+ it('keeps a file alive while a surviving member knowledge base still links to it', async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'kb-usage-ws', primaryOwnerId: otherUserId, slug: 'kb-usage-ws' })
+ .returning();
+ const scoped = new KnowledgeBaseModel(serverDB, userId, workspace.id);
+
+ const mine = await scoped.create({ name: 'Mine' });
+ // A teammate's library in the same workspace survives a narrowed clear-all.
+ const [theirs] = await serverDB
+ .insert(knowledgeBases)
+ .values({ name: "Teammate's", userId: otherUserId, workspaceId: workspace.id })
+ .returning();
+
+ await serverDB.insert(globalFiles).values({
+ creator: userId,
+ fileType: 'application/pdf',
+ hashId: 'hash-shared-link',
+ size: 30,
+ url: 'https://example.com/shared-link.pdf',
+ });
+ await serverDB.insert(files).values({
+ fileHash: 'hash-shared-link',
+ fileType: 'application/pdf',
+ id: 'shared-link',
+ name: 'shared-link.pdf',
+ size: 30,
+ url: 'https://example.com/shared-link.pdf',
+ userId,
+ workspaceId: workspace.id,
+ });
+ // The links carry the workspace scope the clear-all reads them back with.
+ // Seeded without it they would be invisible to `deleteAllWithFiles`, which
+ // would then never even try to delete the file — leaving the assertion
+ // green with the surviving-KB rule removed.
+ await linkFile(mine.id, 'shared-link', userId, workspace.id);
+ await linkFile(theirs.id, 'shared-link', userId, workspace.id);
+
+ await scoped.deleteAllWithFiles(true, { restrictToCreator: true });
+
+ const remainingKbs = await serverDB.select().from(knowledgeBases);
+ expect(remainingKbs.map((kb) => kb.id)).toEqual([theirs.id]);
+ const remainingFiles = await serverDB.select().from(files);
+ expect(remainingFiles.map((file) => file.id)).toEqual(['shared-link']);
+ });
+});
diff --git a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts
new file mode 100644
index 00000000000..3ea32eb3520
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts
@@ -0,0 +1,374 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messagePlugins, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'plugin-lookup-user';
+const otherUserId = 'plugin-lookup-other-user';
+
+const messageModel = new MessageModel(serverDB, userId);
+
+interface SeedArgs {
+ content?: string;
+ createdAt?: Date;
+ id: string;
+ identifier?: string | null;
+ metadata?: Record<string, unknown>;
+ ownerId?: string;
+ parentId?: string;
+ plugin?: boolean;
+ /** Owner of the plugin row only, so the two ownership guards can be probed apart. */
+ pluginOwnerId?: string;
+ state?: Record<string, unknown>;
+ toolCallId?: string | null;
+ topicId?: string | null;
+ type?: string | null;
+}
+
+const seedAssistantMessage = async (id: string) => {
+ await serverDB.insert(messages).values({
+ content: 'assistant',
+ id,
+ role: 'assistant',
+ topicId: 'plugin-topic',
+ userId,
+ });
+};
+
+const seedToolMessage = async (args: SeedArgs) => {
+ const owner = args.ownerId ?? userId;
+
+ await serverDB.insert(messages).values({
+ content: args.content ?? 'tool output',
+ createdAt: args.createdAt ?? new Date('2026-10-01T00:00:00Z'),
+ id: args.id,
+ metadata: args.metadata,
+ parentId: args.parentId,
+ role: 'tool',
+ topicId: args.topicId === undefined ? 'plugin-topic' : args.topicId,
+ userId: owner,
+ });
+
+ if (args.plugin === false) return;
+
+ await serverDB.insert(messagePlugins).values({
+ apiName: args.id,
+ id: args.id,
+ identifier: args.identifier === undefined ? 'lobe-tool' : args.identifier,
+ state: args.state,
+ toolCallId: args.toolCallId === undefined ? `tc-${args.id}` : args.toolCallId,
+ type: args.type === undefined ? undefined : args.type,
+ userId: args.pluginOwnerId ?? owner,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'plugin-topic', userId },
+ { id: 'plugin-topic-2', userId },
+ { id: 'plugin-other-topic', userId: otherUserId },
+ // Agent-share visitor topic: owned by the creator, authored by a visitor.
+ { id: 'plugin-visitor-topic', senderId: 'visitor-1', userId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.findMessagePlugin', () => {
+ it('returns undefined when the message has no plugin row', async () => {
+ await seedToolMessage({ id: 'plug-missing', plugin: false });
+
+ expect(await messageModel.findMessagePlugin('plug-missing')).toBeUndefined();
+ });
+
+ it('normalizes nullable columns into optional fields', async () => {
+ await seedToolMessage({
+ id: 'plug-nullable',
+ identifier: null,
+ toolCallId: null,
+ type: null,
+ });
+
+ await expect(messageModel.findMessagePlugin('plug-nullable')).resolves.toEqual({
+ apiName: 'plug-nullable',
+ arguments: undefined,
+ clientId: undefined,
+ error: undefined,
+ id: 'plug-nullable',
+ identifier: undefined,
+ intervention: undefined,
+ state: undefined,
+ toolCallId: undefined,
+ // A null `type` column falls back to the model's default label.
+ type: 'default',
+ userId,
+ });
+ });
+
+ it('returns the stored tool-call metadata', async () => {
+ await seedToolMessage({
+ id: 'plug-full',
+ state: { running: true },
+ toolCallId: 'tc-full',
+ type: 'default',
+ });
+
+ await expect(messageModel.findMessagePlugin('plug-full')).resolves.toEqual({
+ apiName: 'plug-full',
+ arguments: undefined,
+ clientId: undefined,
+ error: undefined,
+ id: 'plug-full',
+ identifier: 'lobe-tool',
+ intervention: undefined,
+ state: { running: true },
+ toolCallId: 'tc-full',
+ type: 'default',
+ userId,
+ });
+ });
+
+ it("ignores another user's plugin row", async () => {
+ await seedToolMessage({
+ id: 'plug-other',
+ ownerId: otherUserId,
+ topicId: 'plugin-other-topic',
+ });
+
+ expect(await messageModel.findMessagePlugin('plug-other')).toBeUndefined();
+ });
+});
+
+describe('MessageModel.listMessagePluginsByTopic', () => {
+ it('returns the topic rows in first-seen order with metadata', async () => {
+ await seedToolMessage({
+ createdAt: new Date('2026-10-01T00:00:02Z'),
+ id: 'plug-b',
+ metadata: { phase: 'second' },
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ createdAt: new Date('2026-10-01T00:00:01Z'),
+ id: 'plug-a',
+ metadata: { phase: 'first' },
+ topicId: 'plugin-topic',
+ });
+ // No plugin row: the inner join must skip it.
+ await seedToolMessage({
+ createdAt: new Date('2026-10-01T00:00:03Z'),
+ id: 'plug-no-plugin',
+ plugin: false,
+ topicId: 'plugin-topic',
+ });
+
+ const rows = await messageModel.listMessagePluginsByTopic('plugin-topic');
+
+ expect(rows.map((row) => row.id)).toEqual(['plug-a', 'plug-b']);
+ expect(rows[0].metadata).toEqual({ phase: 'first' });
+ expect(rows[0]).toMatchObject({ identifier: 'lobe-tool', type: 'default', userId });
+ });
+
+ it('breaks createdAt ties by id', async () => {
+ const createdAt = new Date('2026-10-01T00:00:00Z');
+ await seedToolMessage({ createdAt, id: 'plug-tie-b', topicId: 'plugin-topic' });
+ await seedToolMessage({ createdAt, id: 'plug-tie-a', topicId: 'plugin-topic' });
+
+ const rows = await messageModel.listMessagePluginsByTopic('plugin-topic');
+
+ expect(rows.map((row) => row.id)).toEqual(['plug-tie-a', 'plug-tie-b']);
+ });
+
+ it('excludes rows from other topics, other users and visitor topics', async () => {
+ await seedToolMessage({ id: 'plug-in-scope', topicId: 'plugin-topic' });
+ await seedToolMessage({ id: 'plug-other-topic', topicId: 'plugin-topic-2' });
+ // Inside the requested topic, so the topic pin cannot reject them: only the
+ // ownership guards can. One row breaks each guard on its own.
+ await seedToolMessage({
+ id: 'plug-topic-other-user',
+ ownerId: otherUserId,
+ pluginOwnerId: otherUserId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ id: 'plug-topic-other-message',
+ ownerId: otherUserId,
+ pluginOwnerId: userId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ id: 'plug-topic-other-plugin',
+ pluginOwnerId: otherUserId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({ id: 'plug-visitor', topicId: 'plugin-visitor-topic' });
+
+ const rows = await messageModel.listMessagePluginsByTopic('plugin-topic');
+
+ expect(rows.map((row) => row.id)).toEqual(['plug-in-scope']);
+
+ // The visitor topic has to be queried on its own, so the topic pin cannot
+ // stand in for the visitor guard.
+ await expect(messageModel.listMessagePluginsByTopic('plugin-visitor-topic')).resolves.toEqual(
+ [],
+ );
+ });
+
+ it('returns an empty list for an unknown topic', async () => {
+ await seedToolMessage({ id: 'plug-known', topicId: 'plugin-topic' });
+
+ await expect(messageModel.listMessagePluginsByTopic('plugin-unknown')).resolves.toEqual([]);
+ });
+});
+
+describe('MessageModel.listMessagePluginsByIds', () => {
+ it('returns an empty list without querying when ids are empty', async () => {
+ await expect(
+ messageModel.listMessagePluginsByIds({ ids: [], topicId: 'plugin-topic' }),
+ ).resolves.toEqual([]);
+ });
+
+ it('returns requested rows ordered by createdAt then id', async () => {
+ await seedToolMessage({
+ content: 'stdout of b',
+ createdAt: new Date('2026-10-01T00:00:02Z'),
+ id: 'plug-ids-b',
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ content: 'stdout of a',
+ createdAt: new Date('2026-10-01T00:00:01Z'),
+ id: 'plug-ids-a',
+ state: { done: true },
+ topicId: 'plugin-topic',
+ });
+
+ const rows = await messageModel.listMessagePluginsByIds({
+ ids: ['plug-ids-b', 'plug-ids-a'],
+ topicId: 'plugin-topic',
+ });
+
+ expect(rows.map((row) => row.id)).toEqual(['plug-ids-a', 'plug-ids-b']);
+ expect(rows[0]).toMatchObject({
+ content: 'stdout of a',
+ createdAt: new Date('2026-10-01T00:00:01Z'),
+ identifier: 'lobe-tool',
+ state: { done: true },
+ type: 'default',
+ userId,
+ });
+ });
+
+ it('pins the result to the given topic', async () => {
+ await seedToolMessage({ id: 'plug-pin', topicId: 'plugin-topic-2' });
+
+ await expect(
+ messageModel.listMessagePluginsByIds({ ids: ['plug-pin'], topicId: 'plugin-topic' }),
+ ).resolves.toEqual([]);
+ });
+
+ it('excludes other users and visitor-topic rows', async () => {
+ await seedToolMessage({ id: 'plug-mine', topicId: 'plugin-topic' });
+ // Seeded inside the requested topic, so the topic pin cannot reject them:
+ // the ownership guards are the only thing standing between these rows and
+ // the result. One row breaks each guard on its own, so dropping either
+ // predicate alone turns this test red.
+ await seedToolMessage({
+ id: 'plug-theirs',
+ ownerId: otherUserId,
+ pluginOwnerId: otherUserId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ id: 'plug-theirs-message',
+ ownerId: otherUserId,
+ pluginOwnerId: userId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ id: 'plug-theirs-plugin',
+ pluginOwnerId: otherUserId,
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({ id: 'plug-visitor-call', topicId: 'plugin-visitor-topic' });
+
+ const rows = await messageModel.listMessagePluginsByIds({
+ ids: ['plug-mine', 'plug-theirs', 'plug-theirs-message', 'plug-theirs-plugin'],
+ topicId: 'plugin-topic',
+ });
+
+ expect(rows.map((row) => row.id)).toEqual(['plug-mine']);
+
+ // The visitor topic has to be queried on its own: the topic pin hides these
+ // rows from the topic above, so only a direct query proves the visitor
+ // guard is load-bearing.
+ await expect(
+ messageModel.listMessagePluginsByIds({
+ ids: ['plug-visitor-call', 'plug-mine'],
+ topicId: 'plugin-visitor-topic',
+ }),
+ ).resolves.toEqual([]);
+ });
+});
+
+describe('MessageModel.findToolMessageIdByToolCallId', () => {
+ it('resolves the message id for a tool call id', async () => {
+ await seedToolMessage({ id: 'plug-tc-a', toolCallId: 'call-1', topicId: 'plugin-topic' });
+
+ await expect(messageModel.findToolMessageIdByToolCallId('call-1')).resolves.toBe('plug-tc-a');
+ });
+
+ it('returns null when nothing matches', async () => {
+ await seedToolMessage({ id: 'plug-tc-b', toolCallId: 'call-2', topicId: 'plugin-topic' });
+
+ await expect(messageModel.findToolMessageIdByToolCallId('call-unknown')).resolves.toBeNull();
+ });
+
+ it('restricts the match to one assistant parent when parentId is given', async () => {
+ await seedAssistantMessage('assistant-a');
+ await seedAssistantMessage('assistant-b');
+
+ await seedToolMessage({
+ id: 'plug-tc-parent-a',
+ parentId: 'assistant-a',
+ toolCallId: 'call-reused',
+ topicId: 'plugin-topic',
+ });
+ await seedToolMessage({
+ id: 'plug-tc-parent-b',
+ parentId: 'assistant-b',
+ toolCallId: 'call-reused',
+ topicId: 'plugin-topic',
+ });
+
+ await expect(
+ messageModel.findToolMessageIdByToolCallId('call-reused', 'assistant-b'),
+ ).resolves.toBe('plug-tc-parent-b');
+ await expect(
+ messageModel.findToolMessageIdByToolCallId('call-reused', 'assistant-unknown'),
+ ).resolves.toBeNull();
+ });
+
+ it("ignores another user's tool call", async () => {
+ await seedToolMessage({
+ id: 'plug-tc-other',
+ ownerId: otherUserId,
+ toolCallId: 'call-other',
+ topicId: 'plugin-other-topic',
+ });
+
+ await expect(messageModel.findToolMessageIdByToolCallId('call-other')).resolves.toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/messages/message.trash.test.ts b/packages/database/src/models/__tests__/messages/message.trash.test.ts
new file mode 100644
index 00000000000..50445a22147
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.trash.test.ts
@@ -0,0 +1,517 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, messagePlugins, messages, sessions, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'message-trash-user';
+const otherUserId = 'message-trash-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const deletedAt = new Date('2026-10-19T00:00:00.000Z');
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values({ id: 'trash-topic', title: 'Trash topic', userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+const row = async (id: string) => {
+ const [result] = await serverDB.select().from(messages).where(eq(messages.id, id));
+ return result;
+};
+
+describe('MessageTrashMutations.softDeleteMessages', () => {
+ it('returns an empty list for an empty id list', async () => {
+ await expect(messageModel.softDeleteMessages([], { deletedAt })).resolves.toEqual([]);
+ });
+
+ it('ignores ids outside the caller scope', async () => {
+ await serverDB.insert(messages).values({
+ content: 'other',
+ id: 'other-msg',
+ role: 'user',
+ userId: otherUserId,
+ });
+
+ await expect(messageModel.softDeleteMessages(['other-msg'], { deletedAt })).resolves.toEqual(
+ [],
+ );
+ expect((await row('other-msg')).isDeleted).toBeNull();
+ });
+
+ it('stamps the row and returns the tree data a restore needs', async () => {
+ await serverDB.insert(messages).values({
+ content: 'hello',
+ id: 'basic-msg',
+ role: 'user',
+ topicId: 'trash-topic',
+ userId,
+ });
+
+ const result = await messageModel.softDeleteMessages(['basic-msg'], { deletedAt });
+
+ expect(result).toEqual([
+ {
+ childIds: [],
+ content: 'hello',
+ id: 'basic-msg',
+ isCompanion: false,
+ ownerId: null,
+ parentId: null,
+ projectId: null,
+ role: 'user',
+ topicId: 'trash-topic',
+ },
+ ]);
+ const trashed = await row('basic-msg');
+ expect(trashed.isDeleted).toBe(true);
+ expect(trashed.deletedAt).toEqual(deletedAt);
+ });
+
+ it('pulls the tool companions of a trashed assistant turn in with it', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'assistant',
+ id: 'assistant-msg',
+ role: 'assistant',
+ tools: [{ id: 'call-1' }],
+ userId,
+ },
+ { content: 'tool', id: 'tool-msg', role: 'tool', userId },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg',
+ identifier: 'plugin-1',
+ toolCallId: 'call-1',
+ userId,
+ });
+
+ const result = await messageModel.softDeleteMessages(['assistant-msg'], { deletedAt });
+
+ expect(result).toHaveLength(2);
+ expect(result.find((entry) => entry.id === 'assistant-msg')?.isCompanion).toBe(false);
+ expect(result.find((entry) => entry.id === 'tool-msg')).toMatchObject({
+ isCompanion: true,
+ ownerId: 'assistant-msg',
+ });
+ expect((await row('tool-msg')).isDeleted).toBe(true);
+ });
+
+ it('ignores tool payloads without an id when collecting companions', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'assistant',
+ id: 'assistant-msg',
+ role: 'assistant',
+ tools: [{}, { id: 'call-2' }],
+ userId,
+ },
+ { content: 'tool', id: 'tool-msg-2', role: 'tool', userId },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-2',
+ identifier: 'plugin-1',
+ toolCallId: 'call-2',
+ userId,
+ });
+
+ const result = await messageModel.softDeleteMessages(['assistant-msg'], { deletedAt });
+
+ expect(result.map((entry) => entry.id).sort()).toEqual(['assistant-msg', 'tool-msg-2']);
+ });
+
+ it('does not mark an explicitly requested companion row as a companion', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'assistant',
+ id: 'assistant-msg',
+ role: 'assistant',
+ tools: [{ id: 'call-1' }],
+ userId,
+ },
+ { content: 'tool', id: 'tool-msg', role: 'tool', userId },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg',
+ identifier: 'plugin-1',
+ toolCallId: 'call-1',
+ userId,
+ });
+
+ const result = await messageModel.softDeleteMessages(['assistant-msg', 'tool-msg'], {
+ deletedAt,
+ });
+
+ expect(result).toHaveLength(2);
+ expect(result.every((entry) => !entry.isCompanion)).toBe(true);
+ expect(result.every((entry) => entry.ownerId === null)).toBe(true);
+ });
+
+ it('re-parents live children onto the nearest surviving ancestor', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'p1', id: 'p1', role: 'user', userId },
+ { content: 'p2', id: 'p2', parentId: 'p1', role: 'assistant', userId },
+ { content: 'p3', id: 'p3', parentId: 'p2', role: 'user', userId },
+ { content: 'p4', id: 'p4', parentId: 'p3', role: 'assistant', userId },
+ ]);
+
+ const result = await messageModel.softDeleteMessages(['p2', 'p3'], { deletedAt });
+
+ expect((await row('p4')).parentId).toBe('p1');
+ expect(result.find((entry) => entry.id === 'p2')?.childIds).toEqual([]);
+ });
+
+ it('re-parents children of a trashed root to the top level', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'root', id: 'root', role: 'user', userId },
+ { content: 'child', id: 'child', parentId: 'root', role: 'assistant', userId },
+ ]);
+
+ const result = await messageModel.softDeleteMessages(['root'], { deletedAt });
+
+ expect((await row('child')).parentId).toBeNull();
+ expect(result[0].childIds).toEqual(['child']);
+ });
+
+ it('shifts the active branch index when an earlier sibling is trashed', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'parent',
+ id: 'bp',
+ metadata: { activeBranchIndex: 1, collapsed: true },
+ role: 'user',
+ userId,
+ },
+ {
+ content: 'a',
+ createdAt: new Date('2026-01-01T00:00:01Z'),
+ id: 'ba',
+ parentId: 'bp',
+ role: 'assistant',
+ userId,
+ },
+ {
+ content: 'b',
+ createdAt: new Date('2026-01-01T00:00:02Z'),
+ id: 'bb',
+ parentId: 'bp',
+ role: 'assistant',
+ userId,
+ },
+ ]);
+
+ await messageModel.softDeleteMessages(['ba'], { deletedAt });
+
+ expect((await row('bp')).metadata).toEqual({ activeBranchIndex: 0, collapsed: true });
+ });
+
+ it('clears the active branch index when the selected branch is trashed', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'bp', metadata: { activeBranchIndex: 1 }, role: 'user', userId },
+ { content: 'a', id: 'ba', parentId: 'bp', role: 'assistant', userId },
+ { content: 'b', id: 'bb', parentId: 'bp', role: 'assistant', userId },
+ ]);
+
+ await messageModel.softDeleteMessages(['bb'], { deletedAt });
+
+ expect((await row('bp')).metadata).toEqual({});
+ });
+
+ it('keeps the optimistic branch index at the new branch count', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'bp', metadata: { activeBranchIndex: 2 }, role: 'user', userId },
+ { content: 'a', id: 'ba', parentId: 'bp', role: 'assistant', userId },
+ { content: 'b', id: 'bb', parentId: 'bp', role: 'assistant', userId },
+ ]);
+
+ await messageModel.softDeleteMessages(['ba'], { deletedAt });
+
+ expect((await row('bp')).metadata).toEqual({ activeBranchIndex: 1 });
+ });
+
+ it('skips branch reconciliation for parents without an active branch index', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'bp', metadata: { foo: 'bar' }, role: 'user', userId },
+ { content: 'a', id: 'ba', parentId: 'bp', role: 'assistant', userId },
+ ]);
+
+ await messageModel.softDeleteMessages(['ba'], { deletedAt });
+
+ expect((await row('bp')).metadata).toEqual({ foo: 'bar' });
+ });
+});
+
+describe('MessageTrashMutations.restoreMessages', () => {
+ it('returns an empty list for an empty entry list', async () => {
+ await expect(messageModel.restoreMessages([])).resolves.toEqual([]);
+ });
+
+ it('ignores rows that are not in the recycle bin', async () => {
+ await serverDB
+ .insert(messages)
+ .values({ content: 'live', id: 'live-msg', role: 'user', userId });
+
+ await expect(messageModel.restoreMessages([{ id: 'live-msg' }])).resolves.toEqual([]);
+ expect((await row('live-msg')).isDeleted).toBeNull();
+ });
+
+ it('clears the trash stamp and returns the restored ids', async () => {
+ await serverDB.insert(messages).values({
+ content: 'trashed',
+ deletedAt,
+ id: 'restore-msg',
+ isDeleted: true,
+ role: 'user',
+ topicId: 'trash-topic',
+ userId,
+ });
+
+ await expect(messageModel.restoreMessages([{ id: 'restore-msg' }])).resolves.toEqual([
+ 'restore-msg',
+ ]);
+ const restored = await row('restore-msg');
+ expect(restored.isDeleted).toBeNull();
+ expect(restored.deletedAt).toBeNull();
+ });
+
+ it('re-parents the children recorded at trash time back onto the restored row', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'restore-parent', role: 'user', userId },
+ {
+ content: 'trashed',
+ deletedAt,
+ id: 'restore-msg',
+ isDeleted: true,
+ parentId: 'restore-parent',
+ role: 'assistant',
+ userId,
+ },
+ { content: 'child', id: 'restore-child', parentId: 'restore-parent', role: 'user', userId },
+ ]);
+
+ await messageModel.restoreMessages([
+ { childIds: ['restore-child'], id: 'restore-msg', parentId: 'restore-parent' },
+ ]);
+
+ expect((await row('restore-child')).parentId).toBe('restore-msg');
+ });
+
+ it('skips children of entries that were not restored', async () => {
+ await serverDB.insert(messages).values({
+ content: 'child',
+ id: 'orphan-child',
+ parentId: null,
+ role: 'user',
+ userId,
+ });
+
+ await expect(
+ messageModel.restoreMessages([{ childIds: ['orphan-child'], id: 'missing-msg' }]),
+ ).resolves.toEqual([]);
+ expect((await row('orphan-child')).parentId).toBeNull();
+ });
+
+ it('restores the reachable entries of a batch that also contains unknown ids', async () => {
+ await serverDB.insert(messages).values({
+ content: 'trashed',
+ deletedAt,
+ id: 'batch-msg',
+ isDeleted: true,
+ role: 'user',
+ userId,
+ });
+
+ await expect(
+ messageModel.restoreMessages([
+ { childIds: ['orphan-child'], id: 'missing-msg' },
+ { id: 'batch-msg' },
+ ]),
+ ).resolves.toEqual(['batch-msg']);
+ expect((await row('batch-msg')).isDeleted).toBeNull();
+ });
+
+ it('carries the branch selection of a re-parented child up to the restored row', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'rp', metadata: { activeBranchIndex: 0 }, role: 'user', userId },
+ { content: 'a', id: 'ra', parentId: 'rp', role: 'assistant', userId },
+ {
+ content: 'b',
+ createdAt: new Date('2026-01-01T00:00:05Z'),
+ deletedAt,
+ id: 'rm',
+ isDeleted: true,
+ parentId: 'rp',
+ role: 'assistant',
+ userId,
+ },
+ ]);
+
+ await messageModel.restoreMessages([{ childIds: ['ra'], id: 'rm', parentId: 'rp' }]);
+
+ expect((await row('rp')).metadata).toEqual({ activeBranchIndex: 0 });
+ });
+
+ it('leaves a branch selection that points at a sibling untouched', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'parent', id: 'rp2', metadata: { activeBranchIndex: 0 }, role: 'user', userId },
+ { content: 'sibling', id: 'rb', parentId: 'rp2', role: 'assistant', userId },
+ {
+ content: 'b',
+ deletedAt,
+ id: 'rm2',
+ isDeleted: true,
+ parentId: 'rp2',
+ role: 'assistant',
+ userId,
+ },
+ {
+ content: 'child',
+ deletedAt,
+ id: 'ra2',
+ isDeleted: true,
+ parentId: 'rp2',
+ role: 'user',
+ userId,
+ },
+ ]);
+
+ await messageModel.restoreMessages([{ childIds: ['ra2'], id: 'rm2', parentId: 'rp2' }]);
+
+ expect((await row('rp2')).metadata).toEqual({ activeBranchIndex: 0 });
+ expect((await row('ra2')).parentId).toBe('rm2');
+ });
+});
+
+describe('MessageTrashMutations.findTrashedByIds', () => {
+ it('returns an empty list for an empty id list', async () => {
+ await expect(messageModel.findTrashedByIds([])).resolves.toEqual([]);
+ });
+
+ it('only returns trashed rows inside the caller scope', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'trashed', deletedAt, id: 'ft-1', isDeleted: true, role: 'user', userId },
+ { content: 'live', id: 'ft-2', role: 'user', userId },
+ {
+ content: 'other',
+ deletedAt,
+ id: 'ft-3',
+ isDeleted: true,
+ role: 'user',
+ userId: otherUserId,
+ },
+ ]);
+
+ const result = await messageModel.findTrashedByIds(['ft-1', 'ft-2', 'ft-3']);
+
+ expect(result).toEqual([
+ { agentId: null, id: 'ft-1', parentId: null, sessionId: null, topicId: null },
+ ]);
+ });
+});
+
+describe('MessageTrashMutations.softDeleteTopicless', () => {
+ it('returns an empty list when no parent ids are given', async () => {
+ await expect(messageModel.softDeleteTopicless({}, { deletedAt })).resolves.toEqual([]);
+ });
+
+ it('stamps topic-less rows of the given agents and sessions only', async () => {
+ await serverDB.insert(agents).values([{ id: 'agent-a', title: 'Agent A', userId }]);
+ await serverDB.insert(sessions).values([{ id: 'sess-a', userId }]);
+ await serverDB.insert(messages).values([
+ {
+ agentId: 'agent-a',
+ content: 'agentless',
+ id: 'tl-1',
+ role: 'user',
+ userId,
+ },
+ { content: 'sessionless', id: 'tl-2', role: 'user', sessionId: 'sess-a', userId },
+ {
+ agentId: 'agent-a',
+ content: 'in topic',
+ id: 'tl-3',
+ role: 'user',
+ topicId: 'trash-topic',
+ userId,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'other user',
+ id: 'tl-4',
+ role: 'user',
+ userId: otherUserId,
+ },
+ ]);
+
+ const result = await messageModel.softDeleteTopicless(
+ { agentIds: ['agent-a'], sessionIds: ['sess-a'] },
+ { deletedAt },
+ );
+
+ expect(result.map((entry) => entry.id).sort()).toEqual(['tl-1', 'tl-2']);
+ expect((await row('tl-1')).isDeleted).toBe(true);
+ expect((await row('tl-2')).isDeleted).toBe(true);
+ expect((await row('tl-3')).isDeleted).toBeNull();
+ expect((await row('tl-4')).isDeleted).toBeNull();
+ });
+
+ it('supports filtering by a single parent kind', async () => {
+ await serverDB.insert(agents).values([{ id: 'agent-b', title: 'Agent B', userId }]);
+ await serverDB.insert(sessions).values([{ id: 'sess-b', userId }]);
+ await serverDB.insert(messages).values([
+ { agentId: 'agent-b', content: 'agentless', id: 'tl-5', role: 'user', userId },
+ { content: 'sessionless', id: 'tl-6', role: 'user', sessionId: 'sess-b', userId },
+ ]);
+
+ const byAgent = await messageModel.softDeleteTopicless(
+ { agentIds: ['agent-b'] },
+ { deletedAt },
+ );
+ expect(byAgent.map((entry) => entry.id)).toEqual(['tl-5']);
+
+ const bySession = await messageModel.softDeleteTopicless(
+ { sessionIds: ['sess-b'] },
+ { deletedAt },
+ );
+ expect(bySession.map((entry) => entry.id)).toEqual(['tl-6']);
+ });
+});
+
+describe('MessageTrashMutations.purgeMessages', () => {
+ it('is a no-op for an empty id list', async () => {
+ await expect(messageModel.purgeMessages([])).resolves.toBeUndefined();
+ });
+
+ it('only purges trashed rows inside the caller scope', async () => {
+ await serverDB.insert(messages).values([
+ { content: 'trashed', deletedAt, id: 'pm-1', isDeleted: true, role: 'user', userId },
+ { content: 'live', id: 'pm-2', role: 'user', userId },
+ {
+ content: 'other',
+ deletedAt,
+ id: 'pm-3',
+ isDeleted: true,
+ role: 'user',
+ userId: otherUserId,
+ },
+ ]);
+
+ await messageModel.purgeMessages(['pm-1', 'pm-2', 'pm-3']);
+
+ await expect(row('pm-1')).resolves.toBeUndefined();
+ await expect(row('pm-2')).resolves.toBeDefined();
+ await expect(row('pm-3')).resolves.toBeDefined();
+ });
+});
diff --git a/packages/database/src/models/__tests__/verifyCriterion.edge.test.ts b/packages/database/src/models/__tests__/verifyCriterion.edge.test.ts
new file mode 100644
index 00000000000..9775edfb4f2
--- /dev/null
+++ b/packages/database/src/models/__tests__/verifyCriterion.edge.test.ts
@@ -0,0 +1,287 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ documents,
+ files,
+ globalFiles,
+ users,
+ verifyCriteria,
+ verifyRubricCriteria,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { VerifyCriterionModel } from '../verifyCriterion';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'verify-criterion-edge-user';
+const otherUserId = 'verify-criterion-edge-other';
+
+const model = new VerifyCriterionModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(files);
+ await serverDB.delete(globalFiles);
+ await serverDB.delete(verifyRubricCriteria);
+ await serverDB.delete(verifyCriteria);
+ await serverDB.delete(documents);
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+const createDocument = async (id: string, content: string | null, ownerId = userId) => {
+ await serverDB.insert(documents).values({
+ content,
+ fileType: 'text/plain',
+ id,
+ source: 'test',
+ sourceType: 'api',
+ title: `Doc ${id}`,
+ totalCharCount: content?.length ?? 0,
+ totalLineCount: 1,
+ userId: ownerId,
+ });
+};
+
+const baseItem = (overrides: Record<string, unknown>) =>
+ ({
+ id: 'edge-check',
+ index: 0,
+ onFail: 'manual',
+ required: true,
+ title: 'Edge check',
+ verifierConfig: {},
+ verifierType: 'agent',
+ ...overrides,
+ }) as any;
+
+describe('VerifyCriterionModel short-circuits', () => {
+ it('returns an empty list when no ids are given to findByIds', async () => {
+ await expect(model.findByIds([])).resolves.toEqual([]);
+ });
+
+ it('returns an empty list when no ids are given to forkRubricCriteria', async () => {
+ await expect(model.forkRubricCriteria([])).resolves.toEqual([]);
+ });
+
+ it('keeps task-local ids untouched when no rubric links them', async () => {
+ const local = await model.create({ title: 'local', verifierType: 'agent' });
+ const other = await model.create({ title: 'other', verifierType: 'agent' });
+
+ await expect(model.forkRubricCriteria([local.id, other.id])).resolves.toEqual([
+ local.id,
+ other.id,
+ ]);
+ });
+});
+
+describe('VerifyCriterionModel.query filters', () => {
+ it('hides archived criteria unless includeArchived is set', async () => {
+ const archived = await model.create({ title: 'archived', verifierType: 'llm' });
+ await model.create({ title: 'live', verifierType: 'llm' });
+ await model.update(archived.id, { archivedAt: new Date() });
+
+ const defaultTitles = (await model.query()).map((row) => row.title);
+ expect(defaultTitles).not.toContain('archived');
+ expect(defaultTitles).toContain('live');
+
+ const allTitles = (await model.query({ includeArchived: true })).map((row) => row.title);
+ expect(allTitles).toEqual(expect.arrayContaining(['archived', 'live']));
+ });
+
+ it('escapes LIKE wildcards in the search term', async () => {
+ await model.create({ title: '100% done', verifierType: 'llm' });
+ await model.create({ title: '100x done', verifierType: 'llm' });
+ await model.create({ title: 'a_b', verifierType: 'llm' });
+ await model.create({ title: 'axb', verifierType: 'llm' });
+ await model.create({ title: 'a\\b', verifierType: 'llm' });
+
+ await expect(model.query({ search: '100%' })).resolves.toHaveLength(1);
+ await expect(model.query({ search: 'a_b' })).resolves.toHaveLength(1);
+ await expect(model.query({ search: 'a\\b' })).resolves.toHaveLength(1);
+ });
+
+ it('matches every tag in the filter', async () => {
+ await model.create({ tags: ['smoke', 'fast'], title: 'tagged', verifierType: 'llm' });
+ await model.create({ tags: ['smoke'], title: 'single', verifierType: 'llm' });
+
+ await expect(model.query({ tags: ['smoke'] })).resolves.toHaveLength(2);
+ await expect(model.query({ tags: ['smoke', 'fast'] })).resolves.toHaveLength(1);
+ await expect(model.query({ tags: ['smoke', 'missing'] })).resolves.toHaveLength(0);
+ });
+});
+
+describe('VerifyCriterionModel.materialize resources', () => {
+ it('freezes the document content referenced by the item', async () => {
+ await createDocument('edge-doc', 'document body');
+
+ const [result] = await model.materialize(
+ [baseItem({ documentId: 'edge-doc', id: 'doc-check' })],
+ 'delivery-doc',
+ );
+
+ expect(result.resourceSnapshot).toEqual({
+ documentContent: 'document body',
+ fixtures: [],
+ });
+ });
+
+ it('falls back to an empty string for a document without content', async () => {
+ await createDocument('edge-doc-empty', null);
+
+ const [result] = await model.materialize(
+ [baseItem({ documentId: 'edge-doc-empty', id: 'empty-doc-check' })],
+ 'delivery-doc',
+ );
+
+ expect(result.resourceSnapshot?.documentContent).toBe('');
+ });
+
+ it('rejects an item pointing at a document outside the caller scope', async () => {
+ await createDocument('foreign-doc', 'secret', otherUserId);
+
+ await expect(
+ model.materialize(
+ [baseItem({ documentId: 'foreign-doc', id: 'missing-doc-check' })],
+ 'delivery-doc',
+ ),
+ ).rejects.toThrow('Check document unavailable');
+ });
+
+ it('skips fixtures without a resource binding', async () => {
+ const [result] = await model.materialize(
+ [
+ baseItem({
+ definition: { fixtures: [{ id: 'f', name: 'Input' }] },
+ id: 'no-resource-check',
+ }),
+ ],
+ 'delivery-doc',
+ );
+
+ expect(result.resourceSnapshot).toEqual({ fixtures: [] });
+ });
+
+ it('freezes the hash and url of a file fixture', async () => {
+ await serverDB.insert(globalFiles).values({
+ creator: userId,
+ fileType: 'text/plain',
+ hashId: 'edge-hash',
+ size: 3,
+ url: 'https://example.com/f.txt',
+ });
+ await serverDB.insert(files).values({
+ fileHash: 'edge-hash',
+ fileType: 'text/plain',
+ id: 'edge-file',
+ name: 'f.txt',
+ size: 3,
+ url: 'https://example.com/f.txt',
+ userId,
+ });
+
+ const [result] = await model.materialize(
+ [
+ baseItem({
+ definition: {
+ fixtures: [{ id: 'f', name: 'Input', resource: { id: 'edge-file', type: 'file' } }],
+ },
+ id: 'file-check',
+ }),
+ ],
+ 'delivery-doc',
+ );
+
+ expect(result.resourceSnapshot?.fixtures).toEqual([
+ { fileHash: 'edge-hash', fixtureId: 'f', url: 'https://example.com/f.txt' },
+ ]);
+ });
+
+ it('rejects a file fixture without an immutable hash', async () => {
+ await serverDB.insert(files).values({
+ fileType: 'text/plain',
+ id: 'edge-file-nohash',
+ name: 'f.txt',
+ size: 3,
+ url: 'https://example.com/f.txt',
+ userId,
+ });
+
+ await expect(
+ model.materialize(
+ [
+ baseItem({
+ definition: {
+ fixtures: [
+ { id: 'f', name: 'Input', resource: { id: 'edge-file-nohash', type: 'file' } },
+ ],
+ },
+ id: 'nohash-check',
+ }),
+ ],
+ 'delivery-doc',
+ ),
+ ).rejects.toThrow('Fixture requires an immutable file hash');
+ });
+
+ it('derives a legacy definition from the item verifier config', async () => {
+ const criterion = await model.create({
+ title: 'legacy',
+ verifierConfig: {},
+ verifierType: 'agent',
+ });
+
+ const [result] = await model.materialize(
+ [
+ baseItem({
+ id: 'legacy-check',
+ sourceCriterionId: criterion.id,
+ verifierConfig: { expected: 'panel visible', method: 'click the button' },
+ }),
+ ],
+ 'delivery-legacy',
+ );
+
+ expect(result.definition).toEqual({
+ expected: 'panel visible',
+ steps: [{ id: 'legacy-method', instruction: 'click the button' }],
+ });
+ });
+
+ it('leaves the derived definition empty when the criterion has no hints', async () => {
+ const criterion = await model.create({
+ title: 'bare',
+ verifierConfig: {},
+ verifierType: 'agent',
+ });
+
+ const [result] = await model.materialize(
+ [baseItem({ id: 'bare-check', sourceCriterionId: criterion.id })],
+ 'delivery-bare',
+ );
+
+ expect(result.definition?.expected).toBeUndefined();
+ expect(result.definition?.steps).toBeUndefined();
+ });
+});
+
+describe('VerifyCriterionModel.update definitions', () => {
+ it('validates the definition before writing', async () => {
+ const criterion = await model.create({ title: 'update', verifierType: 'agent' });
+
+ await model.update(criterion.id, { definition: { expected: 'new' } });
+ expect((await model.findById(criterion.id))?.definition).toEqual({ expected: 'new' });
+
+ await expect(
+ model.update(criterion.id, { definition: { steps: 'nope' } as any }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/database/src/models/__tests__/verifyRun.query.test.ts b/packages/database/src/models/__tests__/verifyRun.query.test.ts
new file mode 100644
index 00000000000..c32825b2d4d
--- /dev/null
+++ b/packages/database/src/models/__tests__/verifyRun.query.test.ts
@@ -0,0 +1,331 @@
+// @vitest-environment node
+import { sql } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ acceptances,
+ agentOperations,
+ users,
+ verifyCheckResults,
+ verifyRuns,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { VerifyRunModel } from '../verifyRun';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'verify-run-query-user';
+const otherUserId = 'verify-run-query-other';
+const workspaceId = 'verify-run-query-ws';
+
+const model = (owner = userId, ws?: string) => new VerifyRunModel(serverDB, owner, ws);
+
+/** Pin `created_at` so keyset paging is deterministic down to the millisecond. */
+const pinCreatedAt = async (runId: string, iso: string) => {
+ await serverDB.execute(
+ sql`update ${verifyRuns} set created_at = ${iso}::timestamptz where id = ${runId}`,
+ );
+};
+
+const seedOperation = async (operationId: string, owner = userId, ws?: string) => {
+ await serverDB
+ .insert(agentOperations)
+ .values({ id: operationId, status: 'running', userId: owner, workspaceId: ws });
+ return operationId;
+};
+
+const titleOf = async (runId: string) => {
+ const run = await serverDB.query.verifyRuns.findFirst({ where: (t, { eq }) => eq(t.id, runId) });
+ return run?.title ?? null;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+describe('VerifyRunModel.query', () => {
+ it('lists a bounded page newest first, scoped to the owner', async () => {
+ const mine = await Promise.all([
+ model().create({ title: 'oldest', source: 'agent' }),
+ model().create({ title: 'middle', source: 'agent' }),
+ model().create({ title: 'newest', source: 'agent' }),
+ ]);
+ await pinCreatedAt(mine[0].id, '2026-01-01T00:00:00.000Z');
+ await pinCreatedAt(mine[1].id, '2026-01-02T00:00:00.000Z');
+ await pinCreatedAt(mine[2].id, '2026-01-03T00:00:00.000Z');
+ await model(otherUserId).create({ title: 'someone else', source: 'agent' });
+
+ const rows = await model().query(2);
+
+ expect(rows.map((row) => row.title)).toEqual(['newest', 'middle']);
+ expect(rows.every((row) => row.userId === userId)).toBe(true);
+ });
+});
+
+describe('VerifyRunModel.queryPage', () => {
+ it('keyset-pages rows that share one millisecond without dropping any', async () => {
+ const ids = [
+ '00000000-0000-4000-8000-00000000000a',
+ '00000000-0000-4000-8000-00000000000b',
+ '00000000-0000-4000-8000-00000000000c',
+ ];
+ for (const [index, id] of ids.entries()) {
+ await model().create({ id, title: `tie-${index}`, source: 'agent' });
+ await pinCreatedAt(id, '2026-02-01T00:00:00.000Z');
+ }
+
+ const first = await model().queryPage({ limit: 2 });
+
+ // Same-instant rows are ordered by id, descending.
+ expect(first.items.map((row) => row.id)).toEqual([ids[2], ids[1]]);
+ expect(first.nextCursor).not.toBeNull();
+
+ const second = await model().queryPage({ cursor: first.nextCursor!, limit: 2 });
+
+ // The leftover row satisfies neither the `eq` tiebreaker nor the `lt` bound
+ // unless createdAt is compared at the cursor's millisecond precision.
+ expect(second.items.map((row) => row.id)).toEqual([ids[0]]);
+ expect(second.nextCursor).toBeNull();
+ });
+
+ it('filters by title and treats LIKE metacharacters literally', async () => {
+ await model().create({ title: 'coverage 100% restored', source: 'agent' });
+ await model().create({ title: 'coverage 100x restored', source: 'agent' });
+ await model().create({ title: 'unrelated round', source: 'agent' });
+
+ const percent = await model().queryPage({ q: ' 100% ' });
+ const underscore = await model().queryPage({ q: 'unrelated_round' });
+
+ expect(percent.items.map((row) => row.title)).toEqual(['coverage 100% restored']);
+ expect(underscore.items).toHaveLength(0);
+ });
+
+ it('falls back to the first page for a malformed cursor', async () => {
+ await model().create({ title: 'only round', source: 'agent' });
+
+ for (const cursor of ['no-delimiter', '__missing-timestamp', 'not-a-date__abc']) {
+ const page = await model().queryPage({ cursor });
+ expect(page.items.map((row) => row.title)).toEqual(['only round']);
+ expect(page.nextCursor).toBeNull();
+ }
+ });
+});
+
+describe('VerifyRunModel.findByOperations', () => {
+ it('rolls up passed/total per operation in one read', async () => {
+ await seedOperation('op-rollup-1');
+ await seedOperation('op-rollup-2');
+ const runA = await model().create({ operationId: 'op-rollup-1', source: 'agent' });
+ const runB = await model().create({ operationId: 'op-rollup-2', source: 'agent' });
+ await serverDB.insert(verifyCheckResults).values([
+ { checkItemId: 'a-1', userId, verdict: 'passed', verifyRunId: runA.id, verifierType: 'llm' },
+ { checkItemId: 'a-2', userId, verdict: 'failed', verifyRunId: runA.id, verifierType: 'llm' },
+ { checkItemId: 'b-1', userId, verdict: 'passed', verifyRunId: runB.id, verifierType: 'llm' },
+ ]);
+
+ const byOperation = await model().findByOperations(['op-rollup-1', 'op-rollup-2']);
+
+ expect(byOperation.get('op-rollup-1')).toMatchObject({ passed: 1, total: 2 });
+ expect(byOperation.get('op-rollup-2')).toMatchObject({ passed: 1, total: 1 });
+ expect(byOperation.get('op-rollup-2')?.id).toBe(runB.id);
+ });
+
+ it('reports 0/0 for a run whose checks are not recorded yet', async () => {
+ await seedOperation('op-rollup-empty');
+ await model().create({ operationId: 'op-rollup-empty', source: 'agent' });
+
+ const [entry] = [...(await model().findByOperations(['op-rollup-empty'])).values()];
+
+ expect(entry).toMatchObject({ passed: 0, total: 0 });
+ });
+
+ it('ignores empty requests and operations it cannot see', async () => {
+ await seedOperation('op-rollup-mine');
+ await seedOperation('op-rollup-theirs', otherUserId);
+ await model().create({ operationId: 'op-rollup-mine', source: 'agent' });
+ await model(otherUserId).create({ operationId: 'op-rollup-theirs', source: 'agent' });
+
+ await expect(model().findByOperations([])).resolves.toEqual(new Map());
+ const byOperation = await model().findByOperations(['op-rollup-mine', 'op-rollup-theirs']);
+
+ expect([...byOperation.keys()]).toEqual(['op-rollup-mine']);
+ });
+});
+
+describe('VerifyRunModel.visibility', () => {
+ it('flips one round without touching another owner', async () => {
+ const mine = await model().create({ source: 'agent' });
+ const theirs = await model(otherUserId).create({ source: 'agent' });
+
+ await model().setVisibility(mine.id, 'private');
+ // Target the foreign round by id too: the run-id predicate alone would
+ // update it, so a missing owner check has to show up as a flipped row.
+ await model().setVisibility(theirs.id, 'private');
+
+ const reload = async (runId: string) =>
+ serverDB.query.verifyRuns.findFirst({ where: (t, { eq }) => eq(t.id, runId) });
+ expect((await reload(mine.id))?.visibility).toBe('private');
+ expect((await reload(theirs.id))?.visibility).toBe('public');
+ });
+
+ it('cascades to every round chained to an acceptance', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 'subject-1', subjectType: 'task', userId })
+ .returning();
+ const first = await model().create({ source: 'agent' });
+ const second = await model().create({ source: 'agent' });
+ await model().attachToAcceptance(first.id, acceptance.id);
+ await model().attachToAcceptance(second.id, acceptance.id);
+
+ await model().setVisibilityByAcceptance(acceptance.id, 'private');
+
+ const rounds = await model().listByAcceptance(acceptance.id);
+ expect(rounds.map((round) => round.visibility)).toEqual(['private', 'private']);
+ });
+});
+
+describe('VerifyRunModel.appendGroupFeedback', () => {
+ it('appends entries and keeps what the round already carried', async () => {
+ const run = await model().create({ source: 'agent' });
+ await model().setDecision(run.id, 'reject', { comment: 'first pass' });
+
+ const first = await model().appendGroupFeedback(run.id, {
+ category: '',
+ comment: 'missing edge case',
+ createdAt: '2026-03-01T00:00:00.000Z',
+ });
+ const second = await model().appendGroupFeedback(run.id, {
+ category: 'copy',
+ comment: 'wording is off',
+ createdAt: '2026-03-02T00:00:00.000Z',
+ });
+
+ expect(first.groupFeedback).toHaveLength(1);
+ expect(second.comment).toBe('first pass');
+ expect(second.groupFeedback?.map((entry) => entry.comment)).toEqual([
+ 'missing edge case',
+ 'wording is off',
+ ]);
+ });
+
+ it('refuses a round it cannot see', async () => {
+ const theirs = await model(otherUserId).create({ source: 'agent' });
+
+ await expect(
+ model().appendGroupFeedback(theirs.id, {
+ category: '',
+ comment: 'nope',
+ createdAt: '2026-03-01T00:00:00.000Z',
+ }),
+ ).rejects.toThrow(/not found in the current workspace/);
+ });
+});
+
+describe('VerifyRunModel.claimTaskDrive', () => {
+ it('claims the drive exactly once and preserves other metadata', async () => {
+ const run = await model().create({ source: 'agent' });
+ await model().setMetadata(run.id, { maxRepairRounds: 2 });
+
+ await expect(model().claimTaskDrive(run.id)).resolves.toBe(true);
+ await expect(model().claimTaskDrive(run.id)).resolves.toBe(false);
+
+ const reloaded = await serverDB.query.verifyRuns.findFirst({
+ where: (t, { eq }) => eq(t.id, run.id),
+ });
+ expect(reloaded?.metadata).toMatchObject({ maxRepairRounds: 2 });
+ expect(reloaded?.metadata?.taskDrivenAt).toEqual(expect.any(String));
+ });
+
+ it("never claims another owner's round", async () => {
+ const theirs = await model(otherUserId).create({ source: 'agent' });
+
+ await expect(model().claimTaskDrive(theirs.id)).resolves.toBe(false);
+ });
+});
+
+describe('VerifyRunModel.update', () => {
+ it('patches the given fields and returns the updated row', async () => {
+ const run = await model().create({ source: 'agent', title: 'before' });
+
+ const updated = await model().update(run.id, { goal: 'ship it', title: 'after' });
+
+ expect(updated).toMatchObject({ goal: 'ship it', title: 'after' });
+ expect(await titleOf(run.id)).toBe('after');
+ });
+
+ it('returns undefined for an unknown or foreign round', async () => {
+ const theirs = await model(otherUserId).create({ source: 'agent' });
+
+ await expect(
+ model().update('00000000-0000-4000-8000-0000000000ff', { title: 'ghost' }),
+ ).resolves.toBeUndefined();
+ await expect(model().update(theirs.id, { title: 'stolen' })).resolves.toBeUndefined();
+ expect(await titleOf(theirs.id)).toBeNull();
+ });
+});
+
+describe('VerifyRunModel.create ownership guard', () => {
+ it('rejects an operation that is not visible to the caller', async () => {
+ await seedOperation('op-guard-invisible', otherUserId);
+
+ await expect(model().create({ operationId: 'op-guard-invisible' })).rejects.toThrow(
+ /not found in the current workspace/,
+ );
+ });
+
+ it('rejects a workspace operation created by another member', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Verify WS', primaryOwnerId: userId, slug: 'verify-ws' });
+ await seedOperation('op-guard-workspace', otherUserId, workspaceId);
+
+ // Visible through the workspace, but reserving its unique operation_id would
+ // lock the real owner out of their own round.
+ await expect(
+ model(userId, workspaceId).create({ operationId: 'op-guard-workspace' }),
+ ).rejects.toThrow(/belongs to another member/);
+ });
+});
+
+describe('VerifyRunModel draft plan guards', () => {
+ const item = {
+ id: 'item-1',
+ index: 0,
+ onFail: 'manual' as const,
+ required: true,
+ title: 'goal met',
+ verifierConfig: {},
+ verifierType: 'llm' as const,
+ };
+
+ it('refuses to set a plan on a confirmed round but lets a replace no-op', async () => {
+ const run = await model().create({ source: 'agent' });
+ await model().setPlan(run.id, [item]);
+ await model().confirmPlan(run.id);
+
+ await expect(model().setPlan(run.id, [{ ...item, title: 'changed' }])).rejects.toThrow(
+ /Draft verification round required/,
+ );
+ await expect(
+ model().replacePlanItems(run.id, [{ ...item, title: 'changed' }]),
+ ).resolves.toBeUndefined();
+
+ const reloaded = await serverDB.query.verifyRuns.findFirst({
+ where: (t, { eq }) => eq(t.id, run.id),
+ });
+ expect(reloaded?.plan?.map((entry) => entry.title)).toEqual(['goal met']);
+ });
+
+ it('refuses to edit the plan of a flow round', async () => {
+ const run = await model().create({ source: 'agent' });
+ await serverDB.execute(
+ sql`update ${verifyRuns} set flow_snapshots = '[]'::jsonb || '[{"flowId":"flow-1"}]'::jsonb where id = ${run.id}`,
+ );
+
+ await expect(model().setPlan(run.id, [item])).rejects.toThrow(/new flow round/);
+ });
+});
diff --git a/packages/database/src/models/__tests__/widget.guards.test.ts b/packages/database/src/models/__tests__/widget.guards.test.ts
new file mode 100644
index 00000000000..a58a5506137
--- /dev/null
+++ b/packages/database/src/models/__tests__/widget.guards.test.ts
@@ -0,0 +1,180 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { trashItems, users, widgetRuns, widgets, widgetVersions } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { CreateWidgetVersionInput } from '../widget';
+import { WidgetModel } from '../widget';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'widget-guards-user';
+const otherUserId = 'widget-guards-other';
+const NOT_A_UUID = 'not-a-uuid';
+
+const script = (n: number): CreateWidgetVersionInput => ({
+ manifest: { title: `v${n}` },
+ outputType: 'stat',
+ runtime: 'node',
+ script: `console.log(${n})`,
+ sourceType: 'agent',
+ view: { size: 'sm' },
+});
+
+beforeEach(async () => {
+ await serverDB.delete(widgetRuns);
+ await serverDB.delete(widgetVersions);
+ await serverDB.delete(widgets);
+ await serverDB.delete(trashItems);
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(widgetRuns);
+ await serverDB.delete(widgetVersions);
+ await serverDB.delete(widgets);
+ await serverDB.delete(trashItems);
+ await serverDB.delete(users);
+});
+
+describe('WidgetModel guards and scheduling', () => {
+ const model = new WidgetModel(serverDB, userId);
+ const other = new WidgetModel(serverDB, otherUserId);
+
+ it('short-circuits every id-scoped method on a malformed uuid', async () => {
+ const widget = await model.create({ title: 'Guards' });
+ const version = await model.createVersion(widget!.id, script(1));
+
+ expect(await model.restore(NOT_A_UUID)).toBeUndefined();
+ expect(await model.delete(NOT_A_UUID)).toBeUndefined();
+ expect(await model.purge(NOT_A_UUID)).toBeUndefined();
+ expect(
+ await model.setSchedule(NOT_A_UUID, {
+ nextRunAt: null,
+ schedulePattern: null,
+ scheduleTimezone: null,
+ }),
+ ).toBeUndefined();
+ expect(await model.createVersion(NOT_A_UUID, script(2))).toBeUndefined();
+ expect(await model.findVersion(widget!.id, NOT_A_UUID)).toBeUndefined();
+ expect(await model.publishVersion(NOT_A_UUID, version!.id)).toBeUndefined();
+ expect(await model.publishVersion(widget!.id, NOT_A_UUID)).toBeUndefined();
+ expect(await model.finishRun(NOT_A_UUID, { status: 'succeeded' })).toBeUndefined();
+ expect(await model.findRun(widget!.id, NOT_A_UUID)).toBeUndefined();
+ expect(await model.findPreviewRun(widget!.id, NOT_A_UUID)).toBeUndefined();
+ expect(await WidgetModel.findLiveWithPublishedVersion(serverDB, NOT_A_UUID)).toBeUndefined();
+ expect(
+ await WidgetModel.renewRunLease(serverDB, {
+ expectedStartedAt: new Date(),
+ runId: NOT_A_UUID,
+ }),
+ ).toBeUndefined();
+ await expect(
+ WidgetModel.startRun(serverDB, widget!, { trigger: 'preview', versionId: NOT_A_UUID }),
+ ).rejects.toThrow('Version does not belong to this widget');
+ });
+
+ it('filters malformed scheduler ids instead of querying', async () => {
+ const options = {
+ createdAfter: new Date(0),
+ limit: 10,
+ startedBefore: new Date(),
+ };
+
+ expect(
+ await WidgetModel.findStaleScheduledRuns(serverDB, { ...options, runId: NOT_A_UUID }),
+ ).toEqual([]);
+ expect(
+ await WidgetModel.findStaleScheduledRuns(serverDB, { ...options, widgetId: NOT_A_UUID }),
+ ).toEqual([]);
+ });
+
+ it('replaces a schedule and fails the runs reserved by the old one', async () => {
+ const widget = await model.create({
+ schedulePattern: '0 * * * *',
+ scheduleTimezone: 'UTC',
+ title: 'Scheduled',
+ });
+ const version = await model.createVersion(widget!.id, script(1));
+ await model.publishVersion(widget!.id, version!.id);
+
+ const [run] = await serverDB
+ .insert(widgetRuns)
+ .values({
+ status: 'running',
+ trigger: 'schedule',
+ userId,
+ versionId: version!.id,
+ widgetId: widget!.id,
+ })
+ .returning();
+
+ const nextRunAt = new Date('2026-10-19T00:00:00.000Z');
+ const updated = await model.setSchedule(widget!.id, {
+ nextRunAt,
+ schedulePattern: '*/5 * * * *',
+ scheduleTimezone: 'Asia/Shanghai',
+ });
+
+ expect(updated).toMatchObject({
+ nextRunAt,
+ schedulePattern: '*/5 * * * *',
+ scheduleTimezone: 'Asia/Shanghai',
+ });
+
+ const [failedRun] = await serverDB.select().from(widgetRuns).where(eq(widgetRuns.id, run.id));
+ expect(failedRun).toMatchObject({
+ error: {
+ code: 'SCHEDULE_CHANGED',
+ message: 'The schedule changed before this run finished',
+ },
+ status: 'failed',
+ });
+ expect(failedRun.finishedAt).not.toBeNull();
+ });
+
+ it('does not let another user reschedule a widget', async () => {
+ const widget = await model.create({ title: 'Owner only' });
+
+ expect(
+ await other.setSchedule(widget!.id, {
+ nextRunAt: null,
+ schedulePattern: null,
+ scheduleTimezone: null,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('defaults the due query window when options are omitted', async () => {
+ const schedule = async (title: string, nextRunAt: Date) => {
+ const widget = await model.create({
+ schedulePattern: '0 * * * *',
+ scheduleTimezone: 'UTC',
+ title,
+ });
+ const version = await model.createVersion(widget!.id, script(1));
+ await model.publishVersion(widget!.id, version!.id);
+ await model.setSchedule(widget!.id, {
+ nextRunAt,
+ schedulePattern: '0 * * * *',
+ scheduleTimezone: 'UTC',
+ });
+ return widget!;
+ };
+
+ // A populated table is what makes the defaults observable: an empty read
+ // stays green for any cutoff or limit.
+ await schedule('Due earlier', new Date('2026-10-01T00:00:00.000Z'));
+ await schedule('Due later', new Date('2026-10-02T00:00:00.000Z'));
+ await schedule('Not due yet', new Date('2030-01-01T00:00:00.000Z'));
+
+ const due = await WidgetModel.findDue(serverDB);
+
+ // Both due rows and no future one: the omitted window is "now", and the
+ // omitted limit cannot be 0.
+ expect(due.map((row) => row.widget.title)).toEqual(['Due earlier', 'Due later']);
+ });
+});
diff --git a/packages/database/src/models/agentDocuments/agentDocument/edits.test.ts b/packages/database/src/models/agentDocuments/agentDocument/edits.test.ts
new file mode 100644
index 00000000000..1f09cd6cfb3
--- /dev/null
+++ b/packages/database/src/models/agentDocuments/agentDocument/edits.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, documents, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import type { AgentDocument } from '../types';
+import {
+ AgentDocumentModel,
+ DocumentLoadFormat,
+ DocumentLoadPosition,
+ DocumentLoadRule,
+ PolicyLoad,
+} from '.';
+import type { AgentDocumentContext } from './context';
+import { buildBackingDocumentUpdate, buildBindingSettingsUpdate } from './edits';
+
+const userId = 'agent-document-edits-user';
+const agentId = 'agent-document-edits-agent';
+/** A well-formed binding id that no row uses (`agent_documents.id` is a uuid column). */
+const missingBindingId = '00000000-0000-4000-8000-000000000000';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+/** The builders under test read no scope column, so the ctx is a typed stand-in. */
+const ctx = { db: serverDB, userId } as unknown as AgentDocumentContext;
+
+const binding = (policy: AgentDocument['policy'], policyLoad?: PolicyLoad) =>
+ ({ policy, policyLoad }) as AgentDocument;
+
+let agentDocumentModel: AgentDocumentModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+});
+
+/** Creates a backing document plus its binding and returns the binding id. */
+const seedBinding = async () => {
+ const [doc] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'seeded content',
+ fileType: 'article',
+ filename: 'seeded.html',
+ source: 'https://example.com',
+ sourceType: 'web',
+ title: 'Seeded Page',
+ totalCharCount: 14,
+ totalLineCount: 1,
+ userId,
+ })
+ .returning();
+
+ const associated = await agentDocumentModel.associate({ agentId, documentId: doc!.id });
+
+ return associated.id;
+};
+
+describe('agent document edit helpers', () => {
+ describe('buildBindingSettingsUpdate', () => {
+ it('falls back to the raw/always defaults when the binding has no policy', () => {
+ const result = buildBindingSettingsUpdate(binding(null));
+
+ expect(result.policyLoadFormat).toBe(DocumentLoadFormat.RAW);
+ expect(result.policyLoadPosition).toBe(DocumentLoadPosition.BEFORE_FIRST_USER);
+ expect(result.policyLoadRule).toBe(DocumentLoadRule.ALWAYS);
+ expect(result).not.toHaveProperty('policyLoad');
+ expect(result.policy?.context?.position).toBe(DocumentLoadPosition.BEFORE_FIRST_USER);
+ expect(result.policy?.context?.rule).toBe(DocumentLoadRule.ALWAYS);
+ });
+
+ it('carries the stored context and an explicit policyLoad', () => {
+ const result = buildBindingSettingsUpdate(
+ binding(
+ {
+ context: {
+ policyLoadFormat: DocumentLoadFormat.FILE,
+ position: DocumentLoadPosition.BEFORE_SYSTEM,
+ rule: DocumentLoadRule.BY_KEYWORDS,
+ },
+ },
+ PolicyLoad.PROGRESSIVE,
+ ),
+ { policyLoad: PolicyLoad.FULL },
+ );
+
+ expect(result.policyLoadFormat).toBe(DocumentLoadFormat.FILE);
+ expect(result.policyLoadPosition).toBe(DocumentLoadPosition.BEFORE_SYSTEM);
+ expect(result.policyLoadRule).toBe(DocumentLoadRule.BY_KEYWORDS);
+ expect(result.policyLoad).toBe(PolicyLoad.FULL);
+ });
+
+ it('applies the requested load rules when the stored policy has no context', () => {
+ const result = buildBindingSettingsUpdate(binding({}), {
+ loadPosition: DocumentLoadPosition.BEFORE_FIRST_USER,
+ loadRules: {
+ keywordMatchMode: 'any',
+ keywords: ['alpha', 'beta'],
+ maxTokens: 99,
+ priority: 5,
+ regexp: '^alpha',
+ rule: DocumentLoadRule.BY_REGEXP,
+ timeRange: { from: '2026-01-01' },
+ },
+ policy: {},
+ });
+
+ expect(result.policy?.context?.keywordMatchMode).toBe('any');
+ expect(result.policy?.context?.keywords).toEqual(['alpha', 'beta']);
+ expect(result.policy?.context?.maxTokens).toBe(99);
+ expect(result.policy?.context?.priority).toBe(5);
+ expect(result.policy?.context?.regexp).toBe('^alpha');
+ expect(result.policy?.context?.rule).toBe(DocumentLoadRule.BY_REGEXP);
+ expect(result.policy?.context?.timeRange).toEqual({ from: '2026-01-01' });
+ expect(result.policy?.context?.position).toBe(DocumentLoadPosition.BEFORE_FIRST_USER);
+ expect(result.policyLoadRule).toBe(DocumentLoadRule.BY_REGEXP);
+ });
+
+ it('keeps the stored context when the request carries no matching rule', () => {
+ const result = buildBindingSettingsUpdate(
+ binding({ context: { maxTokens: 7, rule: DocumentLoadRule.BY_KEYWORDS } }),
+ { loadRules: { maxTokens: 99, rule: DocumentLoadRule.ALWAYS } },
+ );
+
+ expect(result.policy?.context?.maxTokens).toBe(7);
+ expect(result.policy?.context?.rule).toBe(DocumentLoadRule.BY_KEYWORDS);
+ });
+ });
+
+ describe('buildBackingDocumentUpdate', () => {
+ it('skips the write when the update touches no document field', () => {
+ expect(buildBackingDocumentUpdate(ctx, {})).toBeUndefined();
+ expect(buildBackingDocumentUpdate(ctx, undefined)).toBeUndefined();
+ });
+
+ it('recomputes the stats when only the content changes', () => {
+ const update = buildBackingDocumentUpdate(ctx, { content: 'line one\nline two' });
+
+ expect(update).toEqual({
+ content: 'line one\nline two',
+ totalCharCount: 17,
+ totalLineCount: 2,
+ });
+ });
+
+ it('writes the editor snapshot alone', () => {
+ const update = buildBackingDocumentUpdate(ctx, { editorData: { root: {} } });
+
+ expect(update).toEqual({ editorData: { root: {} } });
+ });
+
+ it('writes the file type alone', () => {
+ const update = buildBackingDocumentUpdate(ctx, { fileType: 'article' });
+
+ expect(update).toEqual({ fileType: 'article' });
+ });
+ });
+
+ describe('binding guards', () => {
+ it('returns undefined for a binding outside the scope', async () => {
+ await expect(
+ agentDocumentModel.updateDocumentIdentity(missingBindingId, { title: 'Renamed' }),
+ ).resolves.toBeUndefined();
+ await expect(agentDocumentModel.rename(missingBindingId, 'Renamed')).resolves.toBeUndefined();
+ await expect(
+ agentDocumentModel.movePath(missingBindingId, { filename: 'moved.md', parentId: null }),
+ ).resolves.toBeUndefined();
+ await expect(
+ agentDocumentModel.updateToolLoadRule(missingBindingId, { mode: 'manual' }),
+ ).resolves.toBeUndefined();
+ await expect(
+ agentDocumentModel.updateEditorSnapshotIfUnchanged(
+ missingBindingId,
+ { content: 'a', editorData: null },
+ { content: 'b', editorData: { root: {} } },
+ ),
+ ).resolves.toBe(false);
+ });
+
+ it('writes the repaired snapshot when the read values still match', async () => {
+ const bindingId = await seedBinding();
+
+ const written = await agentDocumentModel.updateEditorSnapshotIfUnchanged(
+ bindingId,
+ { content: 'seeded content', editorData: null },
+ { content: 'seeded content\nline two', editorData: { root: {} } },
+ );
+
+ expect(written).toBe(true);
+ });
+
+ it('refuses to overwrite a snapshot that moved on since it was read', async () => {
+ const bindingId = await seedBinding();
+
+ const written = await agentDocumentModel.updateEditorSnapshotIfUnchanged(
+ bindingId,
+ { content: 'seeded content', editorData: { root: {} } },
+ { content: 'rewritten content', editorData: { root: {} } },
+ );
+
+ expect(written).toBe(false);
+ });
+
+ it('leaves the binding untouched when the new title or filename is blank', async () => {
+ const bindingId = await seedBinding();
+
+ const renamed = await agentDocumentModel.rename(bindingId, ' ');
+ expect(renamed?.id).toBe(bindingId);
+ expect(renamed?.documentId).toBeDefined();
+
+ const moved = await agentDocumentModel.movePath(bindingId, {
+ filename: ' ',
+ parentId: null,
+ });
+ expect(moved?.id).toBe(bindingId);
+ });
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/experiment.edge.test.ts b/packages/database/src/models/agentEval/__tests__/experiment.edge.test.ts
new file mode 100644
index 00000000000..67daeb72bb6
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/experiment.edge.test.ts
@@ -0,0 +1,139 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalExperimentBenchmarks,
+ agentEvalExperiments,
+ agentEvalRuns,
+ users,
+} from '../../../schemas';
+import { AgentEvalExperimentModel } from '../experiment';
+
+const serverDB = await getTestDB();
+
+const userId = 'experiment-edge-user';
+const model = new AgentEvalExperimentModel(serverDB, userId);
+
+const createBenchmark = async () => {
+ const [benchmark] = await serverDB
+ .insert(agentEvalBenchmarks)
+ .values({
+ identifier: `bench-edge-${Math.random().toString(36).slice(2, 8)}`,
+ isSystem: false,
+ name: 'Edge Benchmark',
+ rubrics: [],
+ userId,
+ })
+ .returning();
+ return benchmark;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(agentEvalRuns);
+ await serverDB.delete(agentEvalDatasets);
+ await serverDB.delete(agentEvalExperimentBenchmarks);
+ await serverDB.delete(agentEvalExperiments);
+ await serverDB.delete(agentEvalBenchmarks);
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentEvalRuns);
+ await serverDB.delete(agentEvalDatasets);
+ await serverDB.delete(agentEvalExperimentBenchmarks);
+ await serverDB.delete(agentEvalExperiments);
+ await serverDB.delete(agentEvalBenchmarks);
+ await serverDB.delete(users);
+});
+
+describe('AgentEvalExperimentModel edge cases', () => {
+ it('creates an experiment without benchmarks', async () => {
+ const created = await model.create({ benchmarkIds: [], name: 'No benchmarks' });
+
+ expect(created.name).toBe('No benchmarks');
+ const junctions = await serverDB
+ .select()
+ .from(agentEvalExperimentBenchmarks)
+ .where(eq(agentEvalExperimentBenchmarks.experimentId, created.id));
+ expect(junctions).toEqual([]);
+ });
+
+ it('query returns zero counts and empty lists for a bare experiment', async () => {
+ await model.create({ benchmarkIds: [], name: 'Bare' });
+
+ const [row] = await model.query();
+
+ expect(row).toMatchObject({
+ benchmarkCount: 0,
+ benchmarks: [],
+ datasetCount: 0,
+ name: 'Bare',
+ recentRuns: [],
+ runCount: 0,
+ });
+ });
+
+ it('findByBenchmarkIds short-circuits an empty input', async () => {
+ const benchmark = await createBenchmark();
+ const experiment = await model.create({
+ benchmarkIds: [benchmark.id],
+ name: 'Linked',
+ });
+
+ await expect(model.findByBenchmarkIds([])).resolves.toEqual([]);
+ expect(await model.findByBenchmarkIds([benchmark.id])).toMatchObject([
+ { experimentId: experiment.id, experimentName: 'Linked' },
+ ]);
+ });
+
+ it('update returns undefined for an experiment the caller cannot see', async () => {
+ await expect(model.update('missing-experiment', { name: 'Nope' })).resolves.toBeUndefined();
+ });
+
+ it('update with an empty benchmark list clears the junctions', async () => {
+ const benchmark = await createBenchmark();
+ const experiment = await model.create({
+ benchmarkIds: [benchmark.id],
+ name: 'Clear me',
+ });
+
+ const updated = await model.update(experiment.id, { benchmarkIds: [] });
+
+ expect(updated).toMatchObject({ id: experiment.id });
+ const junctions = await serverDB
+ .select()
+ .from(agentEvalExperimentBenchmarks)
+ .where(eq(agentEvalExperimentBenchmarks.experimentId, experiment.id));
+ expect(junctions).toEqual([]);
+ });
+
+ it('update without benchmarkIds leaves existing junctions alone', async () => {
+ const benchmark = await createBenchmark();
+ const experiment = await model.create({
+ benchmarkIds: [benchmark.id],
+ name: 'Keep junctions',
+ });
+
+ await model.update(experiment.id, { description: 'updated' });
+
+ const junctions = await serverDB
+ .select()
+ .from(agentEvalExperimentBenchmarks)
+ .where(eq(agentEvalExperimentBenchmarks.experimentId, experiment.id));
+ expect(junctions).toHaveLength(1);
+ });
+
+ it('rethrows a unique violation it cannot resolve to a visible experiment', async () => {
+ const id = 'experiment-owned-by-someone-else';
+ await serverDB.insert(users).values({ id: 'experiment-other-owner' });
+ await serverDB
+ .insert(agentEvalExperiments)
+ .values({ id, name: 'other', userId: 'experiment-other-owner' });
+
+ await expect(model.create({ benchmarkIds: [], id, name: 'mine' })).rejects.toThrow();
+ });
+});
diff --git a/packages/database/src/models/agentIntervention/__tests__/utils.test.ts b/packages/database/src/models/agentIntervention/__tests__/utils.test.ts
new file mode 100644
index 00000000000..7db212bc456
--- /dev/null
+++ b/packages/database/src/models/agentIntervention/__tests__/utils.test.ts
@@ -0,0 +1,472 @@
+import type { AgentInterventionSanitizedRequest } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ actionCapability,
+ asRecord,
+ canonicalDtoJson,
+ canonicalJson,
+ hasBoundedFormRecord,
+ hasExactKeys,
+ hashAgentInterventionRequestRevision,
+ hasOnlyKeys,
+ hasValidAnswers,
+ hasValidCustomDetail,
+ hasValidCustomResult,
+ isBoundedFormValue,
+ isCanonicalDtoJsonSafe,
+ isCanonicalJsonSafe,
+ isCustomExecutionResult,
+ isPlainRecord,
+ isUniqueViolation,
+ normalizeDtoJson,
+ providerOptionIds,
+ sameDtoJson,
+ sameJson,
+ terminalStatusForAction,
+ uniqueSorted,
+} from '../utils';
+
+const request = (patch: Partial<AgentInterventionSanitizedRequest>) =>
+ patch as AgentInterventionSanitizedRequest;
+
+describe('canonicalJson', () => {
+ it('serializes JSON primitives', () => {
+ expect(canonicalJson(null)).toBe('null');
+ expect(canonicalJson('text')).toBe('"text"');
+ expect(canonicalJson(true)).toBe('true');
+ expect(canonicalJson(-1.5)).toBe('-1.5');
+ });
+
+ it('sorts object keys and drops undefined only when asked', () => {
+ expect(canonicalJson({ b: 1, a: 2 })).toBe('{"a":2,"b":1}');
+ expect(canonicalDtoJson({ a: 1, b: undefined })).toBe('{"a":1}');
+ // Strict mode keeps `undefined` and therefore rejects it as not JSON-safe.
+ expect(() => canonicalJson({ a: 1, b: undefined })).toThrow(TypeError);
+ });
+
+ it('rejects values that are not JSON-safe', () => {
+ expect(() => canonicalJson(Number.NaN)).toThrow(TypeError);
+ expect(() => canonicalJson(Infinity)).toThrow(TypeError);
+ expect(() => canonicalJson(() => undefined)).toThrow(TypeError);
+ expect(() => canonicalJson(1n)).toThrow(TypeError);
+ expect(() => canonicalJson(new Map())).toThrow(TypeError);
+ });
+
+ it('rejects cyclic and non-standard arrays', () => {
+ const cyclic: Record<string, unknown> = {};
+ cyclic.self = cyclic;
+ expect(() => canonicalJson(cyclic)).toThrow(TypeError);
+
+ const withExtraProp: unknown[] & { extra?: number } = [1];
+ withExtraProp.extra = 2;
+ expect(() => canonicalJson(withExtraProp)).toThrow(TypeError);
+ });
+
+ it('serializes arrays element by element', () => {
+ expect(canonicalJson([])).toBe('[]');
+ expect(canonicalJson(['b', 1, null])).toBe('["b",1,null]');
+ });
+
+ it('rejects non-standard and sparse arrays', () => {
+ // eslint-disable-next-line no-sparse-arrays
+ expect(() => canonicalJson([1, , 3])).toThrow(TypeError);
+
+ const unknownPrototype = Object.create(Array.prototype) as unknown[];
+ expect(() => canonicalJson(unknownPrototype)).toThrow(TypeError);
+
+ const withSymbol: unknown[] = [1];
+ (withSymbol as unknown as Record<symbol, number>)[Symbol('s')] = 2;
+ expect(() => canonicalJson(withSymbol)).toThrow(TypeError);
+ });
+
+ it('rejects hidden or symbol-keyed properties', () => {
+ const value = { a: 1 } as Record<string | symbol, unknown>;
+ Object.defineProperty(value, 'hidden', { enumerable: false, value: 2 });
+ expect(() => canonicalJson(value)).toThrow(TypeError);
+
+ expect(() => canonicalJson({ [Symbol('s')]: 1 })).toThrow(TypeError);
+ });
+});
+
+describe('canonical json helpers', () => {
+ it('compares by canonical form', () => {
+ expect(sameJson({ a: 1, b: 2 }, { b: 2, a: 1 })).toBe(true);
+ expect(sameJson({ a: 1 }, { a: 2 })).toBe(false);
+ expect(sameDtoJson({ a: 1, b: undefined }, { a: 1 })).toBe(true);
+ expect(sameDtoJson({ a: 1 }, { a: 2 })).toBe(false);
+ });
+
+ it('normalizes to a sorted plain object', () => {
+ expect(normalizeDtoJson({ b: 1, a: 2 })).toEqual({ a: 2, b: 1 });
+ });
+
+ it('reports safety without throwing', () => {
+ expect(isCanonicalJsonSafe({ a: 1 })).toBe(true);
+ expect(isCanonicalJsonSafe(new Map())).toBe(false);
+ expect(isCanonicalDtoJsonSafe({ a: 1 })).toBe(true);
+ expect(isCanonicalDtoJsonSafe(new Map())).toBe(false);
+ });
+});
+
+describe('small helpers', () => {
+ it('dedupes and sorts strings', () => {
+ expect(uniqueSorted(['b', 'a', 'b'])).toEqual(['a', 'b']);
+ });
+
+ it('recognises plain records', () => {
+ expect(isPlainRecord({})).toBe(true);
+ expect(isPlainRecord([])).toBe(false);
+ expect(isPlainRecord(null)).toBe(false);
+ expect(isPlainRecord('x')).toBe(false);
+ expect(asRecord({ a: 1 })).toEqual({ a: 1 });
+ expect(asRecord([1])).toEqual({});
+ expect(asRecord(null)).toEqual({});
+ });
+
+ it('detects a pg unique violation including the wrapped cause', () => {
+ expect(isUniqueViolation({ code: '23505' })).toBe(true);
+ expect(isUniqueViolation({ cause: { code: '23505' } })).toBe(true);
+ expect(isUniqueViolation({ code: '23503' })).toBe(false);
+ expect(isUniqueViolation(null)).toBe(false);
+ });
+
+ it('accepts only the custom execution result shape', () => {
+ expect(isCustomExecutionResult({ content: 'c', pluginState: {} })).toBe(true);
+ expect(isCustomExecutionResult({ content: 'c', extra: 1, pluginState: {} })).toBe(false);
+ expect(isCustomExecutionResult({ content: 1, pluginState: {} })).toBe(false);
+ expect(isCustomExecutionResult({ content: 'c' })).toBe(false);
+ });
+
+ it('checks allowed and exact key sets', () => {
+ expect(hasOnlyKeys({ a: 1 }, ['a', 'b'])).toBe(true);
+ expect(hasOnlyKeys({ c: 1 }, ['a'])).toBe(false);
+ expect(hasExactKeys({ b: 1, a: 2 }, ['a', 'b'])).toBe(true);
+ expect(hasExactKeys({ a: 1 }, ['a', 'b'])).toBe(false);
+ });
+
+ it('maps resolution actions to capabilities and terminal statuses', () => {
+ expect(actionCapability({ type: 'stop' })).toBe('stop');
+ expect(terminalStatusForAction({ type: 'stop' })).toBe('cancelled');
+ expect(terminalStatusForAction({ type: 'cancel_interaction' })).toBe('cancelled');
+ expect(terminalStatusForAction({ type: 'approve' })).toBe('resolved');
+ });
+
+ it('hashes the request revision deterministically', () => {
+ expect(hashAgentInterventionRequestRevision('{"a":1}')).toBe(
+ hashAgentInterventionRequestRevision('{"a":1}'),
+ );
+ expect(hashAgentInterventionRequestRevision('{"a":1}')).not.toBe(
+ hashAgentInterventionRequestRevision('{"a":2}'),
+ );
+ });
+});
+
+describe('providerOptionIds', () => {
+ it('collects option ids from options, questions and fields', () => {
+ const ids = providerOptionIds(
+ request({
+ fields: [{ id: 'f', options: [{ id: 'field-opt' }] }],
+ options: [{ id: 'top' }, {}],
+ questions: [{ id: 'q', options: [{ id: 'question-opt' }, {}] }],
+ } as never),
+ );
+
+ expect([...ids].sort()).toEqual(['field-opt', 'question-opt', 'top']);
+ });
+
+ it('returns an empty set when the request carries no options', () => {
+ expect(providerOptionIds(request({}))).toEqual(new Set());
+ expect(providerOptionIds(request({ fields: [{ id: 'no-options' }] } as never))).toEqual(
+ new Set(),
+ );
+ });
+});
+
+describe('isBoundedFormValue', () => {
+ it('accepts bounded scalars and string arrays', () => {
+ expect(isBoundedFormValue(null)).toBe(true);
+ expect(isBoundedFormValue(false)).toBe(true);
+ expect(isBoundedFormValue(1.5)).toBe(true);
+ expect(isBoundedFormValue('short')).toBe(true);
+ expect(isBoundedFormValue(['a', 'b'])).toBe(true);
+ });
+
+ it('rejects unbounded or non-string values', () => {
+ expect(isBoundedFormValue(Number.POSITIVE_INFINITY)).toBe(false);
+ expect(isBoundedFormValue('x'.repeat(10_001))).toBe(false);
+ expect(isBoundedFormValue([1])).toBe(false);
+ expect(isBoundedFormValue({})).toBe(false);
+ expect(isBoundedFormValue(Array.from({ length: 101 }, () => 'a'))).toBe(false);
+ });
+});
+
+describe('hasBoundedFormRecord', () => {
+ it('accepts a shallow record of bounded values', () => {
+ expect(hasBoundedFormRecord({ a: 'x', b: ['y'] })).toBe(true);
+ });
+
+ it('rejects non-records, empty keys and oversized values', () => {
+ expect(hasBoundedFormRecord(null)).toBe(false);
+ expect(hasBoundedFormRecord({ '': 'x' })).toBe(false);
+ expect(hasBoundedFormRecord({ ['k'.repeat(257)]: 'x' })).toBe(false);
+ expect(hasBoundedFormRecord({ a: {} })).toBe(false);
+ });
+});
+
+describe('hasValidAnswers', () => {
+ const questionRequest = request({
+ questions: [
+ {
+ id: 'q1',
+ multiSelect: true,
+ options: [
+ { id: 'o1', label: 'One' },
+ { id: 'o2', label: 'Two' },
+ ],
+ question: 'Pick',
+ },
+ {
+ multiSelect: false,
+ options: [{ label: 'Label only' }],
+ question: 'Pick one',
+ },
+ ],
+ });
+
+ it('accepts multi-select arrays limited to the declared options', () => {
+ expect(hasValidAnswers(questionRequest, { 'Pick one': 'Label only', 'q1': ['o1', 'o2'] })).toBe(
+ true,
+ );
+ });
+
+ it('rejects a multi-select value that is not a string array', () => {
+ expect(hasValidAnswers(questionRequest, { q1: 'o1' })).toBe(false);
+ expect(hasValidAnswers(questionRequest, { q1: [1] })).toBe(false);
+ });
+
+ it('rejects answers outside the declared options or keys', () => {
+ expect(hasValidAnswers(questionRequest, { q1: ['unknown'] })).toBe(false);
+ expect(hasValidAnswers(questionRequest, { nope: 'x' })).toBe(false);
+ });
+
+ it('accepts a custom answer when the question allows it', () => {
+ const allowCustom = request({
+ questions: [
+ {
+ allowCustomAnswer: true,
+ id: 'q1',
+ multiSelect: false,
+ options: [{ id: 'o1' }],
+ question: 'Pick',
+ },
+ ],
+ });
+
+ expect(hasValidAnswers(allowCustom, { q1: 'typed' })).toBe(true);
+ });
+
+ it('requires a value for every question unless a freeform answer is given', () => {
+ expect(hasValidAnswers(questionRequest, {})).toBe(false);
+ expect(
+ hasValidAnswers(
+ request({ ...questionRequest, answerPolicy: { allowFreeform: true } } as never),
+ { __freeform__: 'typed' },
+ ),
+ ).toBe(true);
+ expect(
+ hasValidAnswers(
+ request({ ...questionRequest, answerPolicy: { allowFreeform: true } } as never),
+ { __freeform__: 1 as never },
+ ),
+ ).toBe(false);
+ expect(
+ hasValidAnswers(
+ request({ ...questionRequest, answerPolicy: { allowSupplement: true } } as never),
+ { __supplement__: 'note' },
+ ),
+ ).toBe(false);
+ });
+
+ it('validates field definitions by type', () => {
+ const fieldRequest = request({
+ fields: [
+ { id: 'flag', required: true, type: 'boolean' },
+ { id: 'count', type: 'number' },
+ {
+ id: 'tags',
+ options: [{ id: 't1' }],
+ type: 'multi_select',
+ },
+ { id: 'text', options: [{ id: 'a' }, { id: 'b' }], type: 'string' },
+ ],
+ });
+
+ expect(hasValidAnswers(fieldRequest, { count: 3, flag: true, tags: ['t1'], text: 'a' })).toBe(
+ true,
+ );
+ expect(hasValidAnswers(fieldRequest, { count: '3', flag: true, tags: ['t1'], text: 'a' })).toBe(
+ false,
+ );
+ expect(hasValidAnswers(fieldRequest, { count: 1, flag: true, tags: 't1', text: 'a' })).toBe(
+ false,
+ );
+ expect(hasValidAnswers(fieldRequest, { count: 1, flag: true, tags: ['zzz'], text: 'a' })).toBe(
+ false,
+ );
+ expect(hasValidAnswers(fieldRequest, { count: 1, flag: true, tags: ['t1'], text: 'zzz' })).toBe(
+ false,
+ );
+ // `flag` is required and missing.
+ expect(hasValidAnswers(fieldRequest, { count: 1, tags: ['t1'], text: 'a' })).toBe(false);
+ });
+
+ it('accepts a field without options and falls back to the option label', () => {
+ const fieldRequest = request({
+ fields: [
+ { id: 'plain', type: 'string' },
+ { id: 'choice', options: [{ label: 'Labelled' }], type: 'string' },
+ ],
+ });
+
+ expect(hasValidAnswers(fieldRequest, { choice: 'Labelled', plain: 'x' })).toBe(true);
+ });
+
+ it('rejects a request that declares no answer surface', () => {
+ expect(hasValidAnswers(request({}), { a: 'x' })).toBe(false);
+ });
+});
+
+describe('hasValidCustomDetail', () => {
+ const agentDetail = {
+ agents: [{ id: 'a1', title: 'Agent' }],
+ kind: 'agent_marketplace' as const,
+ };
+
+ it('treats a missing detail as valid', () => {
+ expect(hasValidCustomDetail(request({}))).toBe(true);
+ });
+
+ it('rejects a detail that is not a plain record', () => {
+ expect(hasValidCustomDetail(request({ customDetail: [] } as never))).toBe(false);
+ });
+
+ it('accepts a well-formed agent marketplace detail', () => {
+ expect(
+ hasValidCustomDetail(
+ request({
+ customDetail: {
+ ...agentDetail,
+ agents: [
+ {
+ avatar: 'https://example.com/a.png',
+ description: 'desc',
+ id: 'a1',
+ title: 'Agent',
+ },
+ ],
+ categoryHints: ['writing'],
+ requestId: 'req-1',
+ selectedIds: ['a1'],
+ },
+ } as never),
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects unknown keys and a wrong kind', () => {
+ expect(
+ hasValidCustomDetail(request({ customDetail: { ...agentDetail, extra: 1 } } as never)),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(request({ customDetail: { ...agentDetail, kind: 'other' } } as never)),
+ ).toBe(false);
+ });
+
+ it('rejects malformed agent entries', () => {
+ expect(
+ hasValidCustomDetail(request({ customDetail: { ...agentDetail, agents: 'a1' } } as never)),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(
+ request({
+ customDetail: {
+ ...agentDetail,
+ agents: Array.from({ length: 101 }, () => ({ id: 'a' })),
+ },
+ } as never),
+ ),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(
+ request({
+ customDetail: { ...agentDetail, agents: [{ id: 'a1' }, { id: 'a1' }] },
+ } as never),
+ ),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(
+ request({ customDetail: { ...agentDetail, agents: [{ id: 'a1', title: '' }] } } as never),
+ ),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(
+ request({
+ customDetail: { ...agentDetail, agents: [{ avatar: 1, id: 'a1', title: 'x' }] },
+ } as never),
+ ),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(
+ request({
+ customDetail: { ...agentDetail, agents: [{ id: 'a1', title: 'x', description: 1 }] },
+ } as never),
+ ),
+ ).toBe(false);
+ expect(
+ hasValidCustomDetail(request({ customDetail: { ...agentDetail, agents: ['a1'] } } as never)),
+ ).toBe(false);
+ });
+
+ it('rejects malformed selectedIds, categoryHints and requestId', () => {
+ const withDetail = (patch: Record<string, unknown>) =>
+ request({ customDetail: { ...agentDetail, ...patch } } as never);
+
+ expect(hasValidCustomDetail(withDetail({ selectedIds: 'a1' }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ selectedIds: ['missing'] }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ selectedIds: ['a1', 'a1'] }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ categoryHints: [''] }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ categoryHints: [1] }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ categoryHints: 'x' }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ requestId: '' }))).toBe(false);
+ expect(hasValidCustomDetail(withDetail({ requestId: 1 }))).toBe(false);
+ });
+});
+
+describe('hasValidCustomResult', () => {
+ it('rejects a non-record result', () => {
+ expect(hasValidCustomResult(request({}), null)).toBe(false);
+ });
+
+ it('accepts any bounded record when no detail is declared', () => {
+ expect(hasValidCustomResult(request({}), { any: 'thing' })).toBe(true);
+ });
+
+ it('requires selectedIds to come from the declared agents', () => {
+ const withDetail = request({
+ customDetail: { agents: [{ id: 'a1', title: 'A' }], kind: 'agent_marketplace' },
+ } as never);
+
+ expect(hasValidCustomResult(withDetail, { selectedIds: ['a1'] })).toBe(true);
+ expect(hasValidCustomResult(withDetail, { selectedIds: ['a2'] })).toBe(false);
+ expect(hasValidCustomResult(withDetail, { selectedIds: 'a1' })).toBe(false);
+ expect(hasValidCustomResult(withDetail, { other: [] })).toBe(false);
+ expect(hasValidCustomResult(withDetail, { selectedIds: ['a1', 'a1'] })).toBe(false);
+ });
+
+ it('rejects an unknown detail kind', () => {
+ const withDetail = request({ customDetail: { agents: [], kind: 'other' } } as never);
+
+ expect(hasValidCustomResult(withDetail, { selectedIds: [] })).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.scope.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.scope.test.ts
new file mode 100644
index 00000000000..09961d690a9
--- /dev/null
+++ b/packages/database/src/models/scm/__tests__/changeRequest.scope.test.ts
@@ -0,0 +1,378 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ acceptances,
+ scmChangeRequests,
+ scmInstallations,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { isFailingCheck, mergeChecks, ScmChangeRequestModel } from '../changeRequest';
+import { ScmInstallationModel } from '../installation';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'scm-scope-user';
+const otherUserId = 'scm-scope-other-user';
+const topicId = 'scm-scope-topic';
+const workspaceId = 'scm-scope-workspace';
+const missingId = 'scm-scope-missing-row';
+
+const sha = '3'.repeat(40);
+
+const snapshot = {
+ headSha: sha,
+ number: 7,
+ provider: 'github' as const,
+ repoFullName: 'lobehub/lobehub',
+ state: 'open' as const,
+ url: 'https://github.com/lobehub/lobehub/pull/7',
+ userId,
+};
+
+const check = (name: string, conclusion: string | undefined, status = 'completed') => ({
+ conclusion,
+ externalId: `check_run:${name}`,
+ name,
+ status,
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmChangeRequests);
+ await serverDB.delete(scmInstallations);
+ await serverDB.delete(acceptances);
+ await serverDB.delete(topics);
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+});
+
+describe('scm check identity', () => {
+ it('keys a check the provider named nothing by its external id alone', () => {
+ const unnamed = {
+ conclusion: 'success',
+ externalId: 'status:deadbeef',
+ name: '',
+ status: 'completed',
+ };
+ // Without a name there is no namespace to build, so the id *is* the
+ // identity — a later result for the same context still supersedes it.
+ expect(mergeChecks(null, [unnamed])).toEqual([unnamed]);
+ expect(mergeChecks([unnamed], [{ ...unnamed, conclusion: 'failure' }])).toEqual([
+ { ...unnamed, conclusion: 'failure' },
+ ]);
+ });
+
+ it('counts only a completed run with a failing conclusion as a failure', () => {
+ const completed = (conclusion?: string) => ({
+ conclusion,
+ externalId: 'check_run:1',
+ name: 'Test',
+ status: 'completed',
+ });
+
+ expect(isFailingCheck(completed('failure'))).toBe(true);
+ expect(isFailingCheck(completed('timed_out'))).toBe(true);
+ expect(isFailingCheck(completed('success'))).toBe(false);
+ expect(isFailingCheck(completed())).toBe(false);
+ expect(isFailingCheck({ ...completed('failure'), status: 'queued' })).toBe(false);
+ });
+});
+
+describe('ScmChangeRequestModel lookups', () => {
+ it('resolves a change request by the provider id for it, within the provider', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ externalId: 'PR_node_1',
+ });
+
+ expect(
+ await ScmChangeRequestModel.findByExternalId(serverDB, 'github', 'PR_node_1'),
+ ).toMatchObject({ id: row.id });
+ expect(
+ await ScmChangeRequestModel.findByExternalId(serverDB, 'github', 'PR_node_missing'),
+ ).toBeNull();
+ expect(
+ await ScmChangeRequestModel.findByExternalId(serverDB, 'gitlab', 'PR_node_1'),
+ ).toBeNull();
+ });
+
+ it('lists every change request linked to one acceptance', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+
+ const first = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: acceptance.id },
+ });
+ const second = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { acceptanceId: acceptance.id },
+ number: 8,
+ });
+
+ const rows = await ScmChangeRequestModel.listByAcceptance(serverDB, acceptance.id);
+ expect(rows.map((row) => row.id).sort()).toEqual([first.id, second.id].sort());
+ expect(
+ await ScmChangeRequestModel.listByAcceptance(
+ serverDB,
+ '00000000-0000-0000-0000-000000000000',
+ ),
+ ).toEqual([]);
+ });
+
+ it('lists the change requests opened from one topic', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { topicId },
+ number: 41,
+ });
+
+ expect((await ScmChangeRequestModel.listByTopic(serverDB, topicId)).map((r) => r.id)).toEqual([
+ row.id,
+ ]);
+ expect(await ScmChangeRequestModel.listByTopic(serverDB, 'topic-with-nothing')).toEqual([]);
+ });
+
+ it('shows a scope its own rows plus everything on the installations it connected', async () => {
+ const installation = await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'lobehub',
+ accountType: 'organization',
+ installationId: '91001',
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+
+ const mine = await ScmChangeRequestModel.upsert(serverDB, { ...snapshot, number: 21 });
+ // A member's personal agent opened it, but it is on this user's
+ // installation — a workspace must still see its own repositories.
+ const viaInstallation = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ links: { installationId: installation.id },
+ number: 22,
+ userId: otherUserId,
+ });
+ const foreign = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ number: 23,
+ userId: otherUserId,
+ });
+
+ const ids = (await ScmChangeRequestModel.listByScope(serverDB, { userId })).map(
+ (row) => row.id,
+ );
+ expect(ids).toContain(mine.id);
+ expect(ids).toContain(viaInstallation.id);
+ expect(ids).not.toContain(foreign.id);
+
+ expect(
+ await ScmChangeRequestModel.listByScope(serverDB, { userId }, { limit: 1 }),
+ ).toHaveLength(1);
+ });
+
+ it('scopes a workspace to its own rows, not its members’ personal ones', async () => {
+ const inWorkspace = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ number: 31,
+ userId,
+ workspaceId,
+ });
+ await ScmChangeRequestModel.upsert(serverDB, { ...snapshot, number: 32, userId });
+
+ const rows = await ScmChangeRequestModel.listByScope(serverDB, { userId, workspaceId });
+ expect(rows.map((row) => row.id)).toEqual([inWorkspace.id]);
+ });
+
+ it('reports a missing row instead of guessing at it', async () => {
+ expect(await ScmChangeRequestModel.attachLinks(serverDB, missingId, { topicId })).toBeNull();
+ expect(
+ await ScmChangeRequestModel.applyChecks(serverDB, missingId, { checks: [], headSha: sha }),
+ ).toBeNull();
+ expect(
+ await ScmChangeRequestModel.applyReviewerDecision(serverDB, missingId, {
+ decision: 'approved',
+ reviewerId: 'reviewer-1',
+ }),
+ ).toEqual({ applied: false, reviewDecision: null });
+ });
+
+ it('refuses to invent a row when the replay finds nothing to lock', async () => {
+ // The retry exists for exactly one case: losing the first-insert race.
+ // If the row is not there either, the caller must hear about it rather
+ // than receive a row that was never written.
+ const spy = vi.spyOn(ScmChangeRequestModel as any, 'upsertOnce').mockResolvedValue(null);
+
+ await expect(ScmChangeRequestModel.upsert(serverDB, snapshot)).rejects.toThrow(
+ 'scm change request vanished between insert and retry',
+ );
+
+ spy.mockRestore();
+ });
+
+ it('reports nothing for a repository name and number it never saw', async () => {
+ await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ expect(
+ await ScmChangeRequestModel.findByIdentity(serverDB, 'github', 'lobehub/lobehub', 999),
+ ).toBeNull();
+ expect(
+ await ScmChangeRequestModel.findByIdentity(serverDB, 'gitlab', 'lobehub/lobehub', 7),
+ ).toBeNull();
+ });
+
+ it('opens a row for a delivery that names no commit at all', async () => {
+ // `opened` events may arrive without a head sha; the row still exists and
+ // a later check-run delivery can settle against it.
+ const { headSha: _omitted, ...withoutSha } = snapshot;
+ const created = await ScmChangeRequestModel.upsert(serverDB, withoutSha);
+ expect(created.headSha).toBeNull();
+ expect(created.ciHeadSha).toBeNull();
+
+ // A second delivery without a sha keeps whatever the row already has.
+ await ScmChangeRequestModel.upsert(serverDB, { ...withoutSha, headSha: sha });
+ const updated = await ScmChangeRequestModel.upsert(serverDB, withoutSha);
+ expect(updated.headSha).toBe(sha);
+ });
+
+ it('holds every check for a commit the push has not made the head yet', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ const other = '4'.repeat(40);
+
+ const first = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Test', 'success')],
+ headSha: other,
+ });
+ expect(first?.applied).toBe(false);
+
+ // A second job of the same not-yet-head commit joins the bucket instead of
+ // replacing it — dropping the first would lose a failure.
+ await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Lint', 'failure')],
+ headSha: other,
+ });
+ const held = (await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata?.pendingChecks;
+ expect(held?.checks.map((entry) => entry.name).sort()).toEqual(['Lint', 'Test']);
+ });
+
+ it('rolls up the first commit reported for a row that has no ci head yet', async () => {
+ const { headSha: _omitted, ...withoutSha } = snapshot;
+ const row = await ScmChangeRequestModel.upsert(serverDB, withoutSha);
+
+ const applied = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Test', 'success')],
+ headSha: sha,
+ });
+
+ expect(applied).toMatchObject({ applied: true, ciStatus: 'success', previousCiStatus: null });
+ });
+
+ it('replaces the stored checks wholesale when the caller says so', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Test', 'failure')],
+ headSha: sha,
+ });
+
+ const replaced = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [check('Test', 'success')],
+ headSha: sha,
+ replace: true,
+ });
+
+ expect(replaced?.ciStatus).toBe('success');
+ expect(replaced?.row.checks).toHaveLength(1);
+ });
+
+ it('records a verdict with no timestamp of its own, and a dismissal that empties the rollup', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ const approved = await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ decision: 'approved',
+ reviewerId: 'reviewer-1',
+ });
+ expect(approved).toEqual({ applied: true, reviewDecision: 'approved' });
+
+ // Dismissing the only reviewer leaves nobody asking for anything.
+ const dismissed = await ScmChangeRequestModel.applyReviewerDecision(serverDB, row.id, {
+ decision: null,
+ reviewerId: 'reviewer-1',
+ });
+ expect(dismissed).toEqual({ applied: true, reviewDecision: null });
+ });
+
+ it('records a rollup decision and a lifecycle event on the row', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ await ScmChangeRequestModel.setReviewDecision(serverDB, row.id, 'approved');
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.reviewDecision).toBe(
+ 'approved',
+ );
+
+ await ScmChangeRequestModel.setReviewDecision(serverDB, row.id, null);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.reviewDecision).toBeNull();
+
+ const at = new Date('2026-01-02T03:04:05.000Z');
+ await ScmChangeRequestModel.recordEvent(serverDB, row.id, 'synchronized', at);
+ expect(await ScmChangeRequestModel.findById(serverDB, row.id)).toMatchObject({
+ lastEventAt: at,
+ lastEventKind: 'synchronized',
+ });
+
+ // Without a stamp the event is recorded as of now, which is all the
+ // debounce window needs.
+ await ScmChangeRequestModel.recordEvent(serverDB, row.id, 'reopened');
+ const reopened = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(reopened?.lastEventKind).toBe('reopened');
+ expect(reopened?.lastEventAt).toBeInstanceOf(Date);
+ });
+
+ it('lets exactly one handler claim the tracking comment slot', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(true);
+ // A second delivery of the same burst must not post a second comment.
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(false);
+
+ // A claim that went stale — the post crashed — is takeable again.
+ await serverDB
+ .update(scmChangeRequests)
+ .set({ metadata: { commentClaimedAt: new Date(Date.now() - 6 * 60_000).toISOString() } })
+ .where(eq(scmChangeRequests.id, row.id));
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(true);
+
+ // Once the comment is posted the slot is closed for good.
+ await serverDB
+ .update(scmChangeRequests)
+ .set({ metadata: { lobehubCommentId: '99001' } })
+ .where(eq(scmChangeRequests.id, row.id));
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(false);
+ });
+
+ it('gives the comment slot back when the post never happened', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(true);
+
+ await ScmChangeRequestModel.releaseCommentSlot(serverDB, row.id);
+
+ const stored = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(stored?.metadata).not.toHaveProperty('commentClaimedAt');
+ expect(await ScmChangeRequestModel.claimCommentSlot(serverDB, row.id)).toBe(true);
+ });
+});
diff --git a/packages/database/src/models/scm/__tests__/identity.test.ts b/packages/database/src/models/scm/__tests__/identity.test.ts
new file mode 100644
index 00000000000..3f5dca8f989
--- /dev/null
+++ b/packages/database/src/models/scm/__tests__/identity.test.ts
@@ -0,0 +1,151 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { scmIdentities, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { ScmIdentityModel } from '../identity';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'scm-identity-user';
+const otherUserId = 'scm-identity-other';
+
+const baseParams = {
+ externalLogin: 'octocat',
+ externalUserId: 'ext-42',
+ provider: 'github' as const,
+ userId,
+};
+
+const credentials = { accessToken: 'ghu_token', refreshToken: 'ghr_token' };
+
+beforeEach(async () => {
+ await db.delete(scmIdentities);
+ await db.delete(users);
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await db.delete(scmIdentities);
+ await db.delete(users);
+});
+
+describe('ScmIdentityModel', () => {
+ it('creates an identity with defaults and reads it back by provider account', async () => {
+ const row = await ScmIdentityModel.upsert(db, baseParams);
+
+ expect(row).toMatchObject({
+ credentials: null,
+ externalLogin: 'octocat',
+ metadata: {},
+ provider: 'github',
+ tokenExpiresAt: null,
+ userId,
+ });
+
+ await expect(
+ ScmIdentityModel.findByExternalUser(db, 'github', 'ext-42'),
+ ).resolves.toMatchObject({ id: row.id });
+
+ // No gatekeeper: a null credential column stays null.
+ await expect(ScmIdentityModel.findByUser(db, 'github', userId)).resolves.toMatchObject({
+ credentials: null,
+ id: row.id,
+ });
+ });
+
+ it('round-trips credentials as plaintext JSON when no gatekeeper is provided', async () => {
+ await ScmIdentityModel.upsert(db, { ...baseParams, credentials });
+
+ const [stored] = await db
+ .select()
+ .from(scmIdentities)
+ .where(eq(scmIdentities.userId, userId))
+ .limit(1);
+ expect(stored.credentials).toBe(JSON.stringify(credentials));
+
+ const identity = await ScmIdentityModel.findByUser(db, 'github', userId);
+ expect(identity?.credentials).toEqual(credentials);
+ });
+
+ it('encrypts on write and decrypts on read through the gatekeeper', async () => {
+ const gateKeeper = {
+ decrypt: vi.fn(async (ciphertext: string) => ({
+ plaintext: Buffer.from(ciphertext, 'base64').toString(),
+ })),
+ encrypt: vi.fn(async (plaintext: string) => Buffer.from(plaintext).toString('base64')),
+ };
+
+ await ScmIdentityModel.upsert(db, { ...baseParams, credentials }, gateKeeper);
+
+ const [stored] = await db
+ .select()
+ .from(scmIdentities)
+ .where(eq(scmIdentities.userId, userId))
+ .limit(1);
+ expect(stored.credentials).not.toBe(JSON.stringify(credentials));
+ expect(gateKeeper.encrypt).toHaveBeenCalledWith(JSON.stringify(credentials));
+
+ const identity = await ScmIdentityModel.findByUser(db, 'github', userId, gateKeeper);
+ expect(identity?.credentials).toEqual(credentials);
+ expect(gateKeeper.decrypt).toHaveBeenCalledWith(stored.credentials);
+ });
+
+ it('keeps stored credentials when a re-authorization omits them', async () => {
+ const created = await ScmIdentityModel.upsert(db, { ...baseParams, credentials });
+
+ const updated = await ScmIdentityModel.upsert(db, {
+ ...baseParams,
+ externalLogin: 'octocat-renamed',
+ metadata: { scopes: ['repo'] },
+ tokenExpiresAt: new Date('2027-01-01T00:00:00.000Z'),
+ });
+
+ expect(updated.id).toBe(created.id);
+ expect(updated).toMatchObject({
+ credentials: JSON.stringify(credentials),
+ externalLogin: 'octocat-renamed',
+ metadata: { scopes: ['repo'] },
+ });
+ expect(updated.tokenExpiresAt?.toISOString()).toBe('2027-01-01T00:00:00.000Z');
+ });
+
+ it('clears credentials when the caller explicitly passes null', async () => {
+ await ScmIdentityModel.upsert(db, { ...baseParams, credentials });
+
+ const cleared = await ScmIdentityModel.upsert(db, { ...baseParams, credentials: null });
+
+ expect(cleared.credentials).toBeNull();
+ });
+
+ it('returns null for an unknown provider account or user', async () => {
+ await expect(ScmIdentityModel.findByExternalUser(db, 'github', 'missing')).resolves.toBeNull();
+ await expect(ScmIdentityModel.findByUser(db, 'github', 'missing-user')).resolves.toBeNull();
+ });
+
+ it('returns null credentials when the stored payload is not JSON', async () => {
+ await ScmIdentityModel.upsert(db, baseParams);
+ await db
+ .update(scmIdentities)
+ .set({ credentials: 'not-json' })
+ .where(eq(scmIdentities.userId, userId));
+
+ await expect(ScmIdentityModel.findByUser(db, 'github', userId)).resolves.toMatchObject({
+ credentials: null,
+ });
+ });
+
+ it('throws when the provider account is already bound to another user', async () => {
+ const created = await ScmIdentityModel.upsert(db, baseParams);
+
+ await expect(
+ ScmIdentityModel.upsert(db, { ...baseParams, externalLogin: 'hijack', userId: otherUserId }),
+ ).rejects.toThrow('belongs to another user');
+
+ // The original binding is untouched.
+ const [stored] = await db.select().from(scmIdentities).where(eq(scmIdentities.id, created.id));
+ expect(stored).toMatchObject({ externalLogin: 'octocat', userId });
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
index 6c415293a32..2f7b693e7c9 100644
--- a/packages/database/src/models/work/__tests__/githubToolResult.test.ts
+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts
@@ -421,4 +421,251 @@ describe('normalizeGithubShellToolResult', () => {
}),
).toBeNull();
});
+
+ it('skips a shell payload flagged as an application error', () => {
+ expect(
+ normalizeGithubShellToolResult({
+ data: {
+ command: `gh pr create --repo lobehub/lobehub --title 'x'`,
+ exitCode: 0,
+ isError: true,
+ output: 'https://github.com/lobehub/lobehub/pull/1',
+ },
+ toolName: 'command_execution',
+ }),
+ ).toBeNull();
+ });
+});
+
+/**
+ * Structured REST-shaped tool results (`create_issue`, `update_pull_request`, ...)
+ * reach the same `owner/repo#number` identity through `unwrapData` → `buildParams`.
+ */
+describe('normalizeGithubToolResult (structured REST results)', () => {
+ const structured = (data: unknown, args?: Record<string, unknown>, toolName = 'create_issue') =>
+ normalizeGithubToolResult({ args, data, toolName });
+
+ it('parses a numeric string `number` into the identifier', () => {
+ const operation = structured({ number: '42', repository_full_name: 'lobehub/lobehub' });
+
+ expect(operation?.params).toMatchObject({
+ changeType: 'created',
+ identifier: 'lobehub/lobehub#42',
+ resourceType: 'github_issue',
+ });
+ });
+
+ it('defaults missing args to an empty record', () => {
+ const operation = structured({ number: 7, repository_full_name: 'lobehub/lobehub' });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#7');
+ });
+
+ it('resolves the repo from the args when the result carries none', () => {
+ const operation = structured({ number: 5 }, { repository: 'lobehub/lobehub' });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#5');
+ });
+
+ it('resolves the repo from an api.github.com repository_url', () => {
+ const operation = structured({
+ number: 5,
+ repository_url: 'https://api.github.com/repos/lobehub/lobehub',
+ });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#5');
+ });
+
+ it('falls back to the `url` field when html_url is absent', () => {
+ const operation = structured({
+ number: 5,
+ repository_full_name: 'lobehub/lobehub',
+ url: 'https://github.com/lobehub/lobehub/issues/5',
+ });
+
+ expect(operation?.params.url).toBe('https://github.com/lobehub/lobehub/issues/5');
+ });
+
+ it('collapses merged and draft into the display status', () => {
+ const merged = structured({ merged: true, number: 5, repository_full_name: 'o/r' });
+ expect(merged?.params.status).toBe('merged');
+
+ const draft = structured({ draft: true, number: 6, repository_full_name: 'o/r' });
+ expect(draft?.params.status).toBe('draft');
+ });
+
+ it('unwraps an MCP content-parts array', () => {
+ const operation = structured([
+ { text: '{"number": 7, "repository_full_name": "lobehub/lobehub"}' },
+ ]);
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#7');
+ });
+
+ it('unwraps a content-parts array of plain strings', () => {
+ const operation = structured(['{"number": 8, "repository_full_name": "lobehub/lobehub"}']);
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#8');
+ });
+
+ it('falls back to the first array element when parts carry no text', () => {
+ // No text/content in the parts ⇒ the joined text is empty and the first
+ // element is used as-is; it holds no identity, so nothing registers.
+ expect(structured([{}])).toBeNull();
+ });
+
+ it('unwraps a `content` array on a wrapper record', () => {
+ const operation = structured({
+ content: [{ text: '{"number": 8, "repository_full_name": "lobehub/lobehub"}' }],
+ });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#8');
+ });
+
+ it('keeps the wrapper record when its content array is not JSON', () => {
+ expect(structured({ content: [{ text: 'not-json' }] })).toBeNull();
+ });
+
+ it('unwraps a nested resource wrapper key', () => {
+ const operation = structured({
+ issue: { number: 11, repository_full_name: 'lobehub/lobehub' },
+ });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#11');
+ });
+
+ it('skips payloads that are not JSON objects', () => {
+ expect(structured('plain text payload')).toBeNull();
+ });
+
+ it('ignores non-record parts between MCP content parts', () => {
+ const operation = structured([
+ { text: '{"number": 9, "repository_full_name": "lobehub/lobehub"}' },
+ 42,
+ ]);
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#9');
+ });
+
+ it('ignores an unparseable repository_url', () => {
+ expect(structured({ number: 5, repository_url: 'not a url' })).toBeNull();
+ });
+
+ it('skips structured results flagged as an application error', () => {
+ expect(
+ structured({ isError: true, number: 5, repository_full_name: 'lobehub/lobehub' }),
+ ).toBeNull();
+ });
+
+ it('skips tools that are not GitHub write tools', () => {
+ const operation = structured(
+ { number: 5, repository_full_name: 'lobehub/lobehub' },
+ undefined,
+ 'get_issue',
+ );
+
+ expect(operation).toBeNull();
+ });
+
+ it('skips results without a resolvable identity', () => {
+ expect(structured({ title: 'no repo or number' })).toBeNull();
+ });
+});
+
+describe('normalizeGithubToolResult (gh CLI edge cases)', () => {
+ it('reads the command from args when the result record carries none', () => {
+ const operation = normalizeGithubToolResult({
+ args: { command: `gh issue create --repo lobehub/lobehub --title 'From args'` },
+ data: { output: 'https://github.com/lobehub/lobehub/issues/77' },
+ toolName: 'runCommand',
+ });
+
+ expect(operation?.params).toMatchObject({
+ identifier: 'lobehub/lobehub#77',
+ title: 'From args',
+ });
+ });
+
+ it('skips a result with no command at all', () => {
+ expect(
+ normalizeGithubToolResult({
+ data: { output: 'https://github.com/lobehub/lobehub/issues/77' },
+ toolName: 'runCommand',
+ }),
+ ).toBeNull();
+ });
+
+ it('skips a non-object payload', () => {
+ expect(
+ normalizeGithubToolResult({ data: 'plain text payload', toolName: 'runCommand' }),
+ ).toBeNull();
+ });
+
+ it('ignores gh subcommands that are neither issue nor pr', () => {
+ expect(
+ normalizeGithubToolResult({
+ data: { command: 'gh repo create lobehub/x --public', exitCode: 0, output: '' },
+ toolName: 'runCommand',
+ }),
+ ).toBeNull();
+ });
+
+ it('tolerates a value flag with no value at the end of the command', () => {
+ const operation = normalizeGithubToolResult({
+ data: {
+ command: 'gh issue create --repo lobehub/lobehub --title',
+ exitCode: 0,
+ output: 'https://github.com/lobehub/lobehub/issues/88',
+ },
+ toolName: 'runCommand',
+ });
+
+ expect(operation?.params.identifier).toBe('lobehub/lobehub#88');
+ expect(operation?.params.title).toBeUndefined();
+ });
+
+ it('parses the short -t/-b/-d flags on gh pr create', () => {
+ const operation = normalizeGithubToolResult({
+ data: {
+ command: `gh pr create -R lobehub/lobehub -t 'Short flags' -b 'Body text' -d`,
+ exitCode: 0,
+ output: 'https://github.com/lobehub/lobehub/pull/99',
+ },
+ toolName: 'runCommand',
+ });
+
+ expect(operation?.params).toMatchObject({
+ content: 'Body text',
+ identifier: 'lobehub/lobehub#99',
+ resourceType: 'github_pull_request',
+ status: 'draft',
+ title: 'Short flags',
+ });
+ });
+
+ it('takes an entity URL positional as the edit target', () => {
+ const operation = normalizeGithubToolResult({
+ data: {
+ command: `gh pr edit https://github.com/lobehub/lobehub/pull/9 --title 'Retitled'`,
+ exitCode: 0,
+ output: '',
+ },
+ toolName: 'runCommand',
+ });
+
+ expect(operation?.params).toMatchObject({
+ changeType: 'updated',
+ identifier: 'lobehub/lobehub#9',
+ title: 'Retitled',
+ });
+ });
+
+ it('skips a create command that leaves no resolvable identity', () => {
+ expect(
+ normalizeGithubToolResult({
+ data: { command: `gh issue create --title 'No repo'`, exitCode: 0, output: 'no url here' },
+ toolName: 'runCommand',
+ }),
+ ).toBeNull();
+ });
});
diff --git a/packages/database/src/models/work/__tests__/linearToolResult.test.ts b/packages/database/src/models/work/__tests__/linearToolResult.test.ts
new file mode 100644
index 00000000000..ec392883f7d
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/linearToolResult.test.ts
@@ -0,0 +1,150 @@
+// @vitest-environment node
+import type { SkillToolResultWorkInput } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { WORK_DESCRIPTION_PREVIEW_LENGTH } from '../internal';
+import { normalizeLinearToolResult } from '../linearToolResult';
+
+type Extra = Partial<Omit<SkillToolResultWorkInput, 'data'>>;
+
+const issue = (data: unknown, extra: Extra = {}) =>
+ normalizeLinearToolResult({ data, toolName: 'save_issue', ...extra });
+
+const document = (data: unknown) =>
+ normalizeLinearToolResult({ data, toolName: 'create_document' });
+
+describe('normalizeLinearToolResult · payload unwrapping', () => {
+ it('unwraps an array payload through its first entry', () => {
+ const operation = issue([{ id: 'issue-uuid-1', title: 'From an array' }]);
+
+ expect(operation?.type).toBe('register');
+ expect(operation?.params.resourceId).toBe('issue-uuid-1');
+ expect(operation?.params.resourceType).toBe('linear_issue');
+ expect(operation?.params.title).toBe('From an array');
+ });
+
+ it('returns null when the array holds no record', () => {
+ expect(issue([42])).toBeNull();
+ });
+
+ it('returns null for a scalar payload that is not a record', () => {
+ expect(issue('plain text result')).toBeNull();
+ });
+
+ it('returns null for an empty payload on both entity paths', () => {
+ expect(issue(null)).toBeNull();
+ expect(document(null)).toBeNull();
+ });
+
+ it('returns null when the unwrapped record carries no identity field', () => {
+ expect(issue({ title: 'Identity missing' })).toBeNull();
+ });
+
+ it('unwraps a document payload nested under `document`', () => {
+ const operation = document({ document: { id: 'doc-uuid-1', slug: 'my-doc', title: 'Doc' } });
+
+ expect(operation?.params.resourceId).toBe('doc-uuid-1');
+ expect(operation?.params.resourceType).toBe('linear_document');
+ expect(operation?.params.identifier).toBe('my-doc');
+ });
+});
+
+describe('normalizeLinearToolResult · identifier resolution', () => {
+ it('uses the record id when it already looks like an issue identifier', () => {
+ const operation = issue({ id: 'ENG-123', title: 'Looks like a key' });
+
+ expect(operation?.params.identifier).toBe('ENG-123');
+ expect(operation?.params.patchFields).toContain('identifier');
+ });
+
+ it('falls back to the issue segment of the url', () => {
+ const operation = issue({
+ id: 'issue-uuid-2',
+ title: 'From url',
+ url: 'https://linear.app/acme/issue/ENG-42',
+ });
+
+ expect(operation?.params.identifier).toBe('ENG-42');
+ });
+
+ it('resolves no identifier when the url carries no issue segment', () => {
+ const operation = issue({
+ id: 'issue-uuid-3',
+ title: 'No segment',
+ url: 'https://linear.app/acme/profile',
+ });
+
+ expect(operation?.params.identifier).toBeNull();
+ });
+
+ it('resolves no identifier when the issue segment is the last path element', () => {
+ const operation = issue({
+ id: 'issue-uuid-4',
+ title: 'Dangling segment',
+ url: 'https://linear.app/acme/issue',
+ });
+
+ expect(operation?.params.identifier).toBeNull();
+ });
+
+ it('resolves no identifier when the url cannot be parsed', () => {
+ const operation = issue({ id: 'issue-uuid-5', title: 'Broken url', url: 'not-a-url' });
+
+ expect(operation?.params.identifier).toBeNull();
+ expect(operation?.params.url).toBeUndefined();
+ });
+
+ it('falls back to the document segment of the url when the record has no slug', () => {
+ const operation = document({
+ document: {
+ id: 'doc-uuid-2',
+ title: 'Doc from url',
+ url: 'https://linear.app/acme/document/my-doc',
+ },
+ });
+
+ expect(operation?.params.identifier).toBe('my-doc');
+ });
+});
+
+describe('normalizeLinearToolResult · text fields', () => {
+ it('caps the card preview while keeping the full body in content', () => {
+ const long = 'x'.repeat(WORK_DESCRIPTION_PREVIEW_LENGTH + 30);
+ const operation = issue({ description: long, id: 'issue-uuid-6', title: 'Long body' });
+
+ expect(operation?.params.description).toBe(`${'x'.repeat(WORK_DESCRIPTION_PREVIEW_LENGTH)}...`);
+ expect(operation?.params.content).toBe(long);
+ });
+
+ it('drops a blank description but still records the patch field', () => {
+ const operation = issue({ description: '', id: 'issue-uuid-7', title: 'Blank body' });
+
+ expect(operation?.params.description).toBeNull();
+ expect(operation?.params.patchFields).toContain('description');
+ });
+
+ it('carries an explicit null field through as a null patch', () => {
+ const operation = issue({ content: null, id: 'issue-uuid-8', title: null });
+
+ expect(operation?.params.title).toBeNull();
+ expect(operation?.params.content).toBeNull();
+ expect(operation?.params.patchFields).toContain('title');
+ expect(operation?.params.patchFields).toContain('content');
+ });
+
+ it('drops a blank string status instead of persisting an empty value', () => {
+ const operation = issue({ id: 'issue-uuid-9', status: '', title: 'Blank status' });
+
+ expect(operation?.params.status).toBeNull();
+ });
+
+ it('reads the status from a nested state object', () => {
+ const operation = issue({
+ id: 'issue-uuid-10',
+ state: { name: 'In Progress' },
+ title: 'Nested state',
+ });
+
+ expect(operation?.params.status).toBe('In Progress');
+ });
+});
diff --git a/packages/database/vitest.config.server.mts b/packages/database/vitest.config.server.mts
index 9d9d8d9396a..f7e577a016e 100644
--- a/packages/database/vitest.config.server.mts
+++ b/packages/database/vitest.config.server.mts
@@ -38,6 +38,10 @@ export default defineConfig({
'**/.{idea,git,cache,output,temp}/**',
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*',
'src/server/core/dbForTest.ts',
+ // Test-only helpers and fixtures are not production surface. Vitest 4
+ // ships an empty `coverageConfigDefaults.exclude`, so without this
+ // `_test_template.ts` / `_fixtures.ts` leak into the package totals.
+ 'src/**/__tests__/**',
],
include: ['src/models/**/*.ts', 'src/server/**/*.ts'],
provider: 'v8',