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.

✨ feat(agent-documents): add runtime migration into an agent's dedicated library (#22587)

Arvin Xu24abe87fe862
diff --git a/packages/database/src/repositories/agentSpace/__tests__/index.test.ts b/packages/database/src/repositories/agentSpace/__tests__/index.test.ts
new file mode 100644
index 00000000000..5ca1ae09150
--- /dev/null
+++ b/packages/database/src/repositories/agentSpace/__tests__/index.test.ts
@@ -0,0 +1,229 @@
+// @vitest-environment node
+import { eq, inArray, sql } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { KnowledgeBaseModel } from '../../../models/knowledgeBase';
+import {
+ AGENT_SKILL_TEMPLATE_ID,
+ agentDocuments,
+ agents,
+ agentsKnowledgeBases,
+ documents,
+ knowledgeBases,
+ SKILL_MANAGEMENT_SOURCE,
+ SKILL_MANAGEMENT_SOURCE_TYPE,
+ users,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { AgentSpaceRepository } from '../index';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-space-user';
+const otherUserId = 'agent-space-other-user';
+const agentId = 'agt_space_1';
+const repository = new AgentSpaceRepository(db, userId);
+const isServerDB = process.env.TEST_SERVER_DB === '1';
+const editedAt = new Date('2024-01-02T03:04:05.000Z');
+
+const insertDocument = async (
+ id: string,
+ overrides: Partial<typeof documents.$inferInsert> = {},
+ binding: Partial<typeof agentDocuments.$inferInsert> | null = {},
+) => {
+ await db.insert(documents).values({
+ fileType: 'custom/document',
+ id,
+ source: `agent-document://${agentId}/${id}.md`,
+ sourceType: 'agent',
+ title: id,
+ totalCharCount: 0,
+ totalLineCount: 0,
+ updatedAt: editedAt,
+ userId,
+ ...overrides,
+ });
+ if (binding)
+ await db.insert(agentDocuments).values({ agentId, documentId: id, userId, ...binding });
+};
+
+const knowledgeBaseIdOf = async (id: string) => {
+ const [row] = await db
+ .select({ knowledgeBaseId: documents.knowledgeBaseId })
+ .from(documents)
+ .where(eq(documents.id, id));
+ return row.knowledgeBaseId;
+};
+
+beforeEach(async () => {
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(agents).values({ id: agentId, title: 'Writer', userId });
+});
+
+describe('AgentSpaceRepository', () => {
+ describe('ensure', () => {
+ it('creates one hidden, disabled space per agent even under concurrent calls', async () => {
+ const ids = await Promise.all([
+ repository.ensure(agentId),
+ repository.ensure(agentId),
+ repository.ensure(agentId),
+ ]);
+
+ expect(new Set(ids).size).toBe(1);
+ const spaces = await db
+ .select()
+ .from(knowledgeBases)
+ .where(eq(knowledgeBases.userId, userId));
+ expect(spaces).toHaveLength(1);
+ expect(spaces[0]).toMatchObject({
+ name: 'Writer',
+ settings: { owner: { id: agentId, type: 'agent' } },
+ type: 'agent',
+ });
+ await expect(
+ db.select().from(agentsKnowledgeBases).where(eq(agentsKnowledgeBases.agentId, agentId)),
+ ).resolves.toMatchObject([{ enabled: false, knowledgeBaseId: ids[0] }]);
+ await expect(new KnowledgeBaseModel(db, userId).query()).resolves.toEqual([]);
+ });
+
+ it('does not create a space for an agent the caller cannot see', async () => {
+ await expect(
+ new AgentSpaceRepository(db, otherUserId).ensure(agentId),
+ ).resolves.toBeUndefined();
+ await expect(
+ db.select().from(knowledgeBases).where(eq(knowledgeBases.userId, userId)),
+ ).resolves.toEqual([]);
+ });
+
+ it('does not reveal an existing space to a caller who cannot see the agent', async () => {
+ await repository.ensure(agentId);
+ const outsider = new AgentSpaceRepository(db, otherUserId);
+
+ await expect(outsider.findId(agentId)).resolves.toBeUndefined();
+ await expect(outsider.ensure(agentId)).resolves.toBeUndefined();
+ });
+
+ it('does not mistake an ordinary mounted library for the space', async () => {
+ await db.insert(knowledgeBases).values({ id: 'kb-mounted', name: 'Mounted', userId });
+ await db
+ .insert(agentsKnowledgeBases)
+ .values({ agentId, knowledgeBaseId: 'kb-mounted', userId });
+
+ await expect(repository.findId(agentId)).resolves.toBeUndefined();
+ });
+ });
+
+ describe('migrateBatch', () => {
+ it('moves dedicated documents, including soft-deleted bindings, and keeps updatedAt', async () => {
+ await insertDocument('doc-a');
+ await insertDocument('doc-trashed', {}, { deletedAt: new Date() });
+
+ const result = await repository.migrateBatch(agentId);
+
+ const spaceId = await repository.findId(agentId);
+ expect(spaceId).toBeDefined();
+ expect(result).toEqual({ done: true, migrated: 2, skipped: false });
+ await expect(knowledgeBaseIdOf('doc-a')).resolves.toBe(spaceId);
+ await expect(knowledgeBaseIdOf('doc-trashed')).resolves.toBe(spaceId);
+ const [row] = await db.select().from(documents).where(eq(documents.id, 'doc-a'));
+ expect(row.updatedAt).toEqual(editedAt);
+ });
+
+ it('migrates managed skills only when this agent owns the binding', async () => {
+ const skill = {
+ source: SKILL_MANAGEMENT_SOURCE,
+ sourceType: SKILL_MANAGEMENT_SOURCE_TYPE,
+ } as const;
+ await insertDocument('skill-owned', skill, { templateId: AGENT_SKILL_TEMPLATE_ID });
+ await insertDocument('skill-borrowed', skill);
+
+ await repository.migrateBatch(agentId);
+
+ await expect(knowledgeBaseIdOf('skill-owned')).resolves.toBeTruthy();
+ await expect(knowledgeBaseIdOf('skill-borrowed')).resolves.toBeNull();
+ });
+
+ it('leaves associated documents and documents already in a library untouched', async () => {
+ await db.insert(knowledgeBases).values({ id: 'kb-home', name: 'Home', userId });
+ await insertDocument('doc-page', { source: 'page', sourceType: 'api' });
+ await insertDocument('doc-other-agent', { source: 'agent-document://agt_space_2/x.md' });
+ // `_` must match literally: this source would pass a LIKE prefix for agt_space_1.
+ await insertDocument('doc-like-wildcard', { source: 'agent-document://agtXspace_1/x.md' });
+ await insertDocument('doc-in-library', { knowledgeBaseId: 'kb-home' });
+
+ await expect(repository.migrateBatch(agentId)).resolves.toEqual({
+ done: true,
+ migrated: 0,
+ skipped: false,
+ });
+
+ await expect(knowledgeBaseIdOf('doc-page')).resolves.toBeNull();
+ await expect(knowledgeBaseIdOf('doc-other-agent')).resolves.toBeNull();
+ await expect(knowledgeBaseIdOf('doc-like-wildcard')).resolves.toBeNull();
+ await expect(knowledgeBaseIdOf('doc-in-library')).resolves.toBe('kb-home');
+ await expect(repository.findId(agentId)).resolves.toBeUndefined();
+ });
+
+ it('resumes across batches, stays correct half-migrated, and is idempotent', async () => {
+ for (const id of ['doc-1', 'doc-2', 'doc-3']) await insertDocument(id);
+
+ await expect(repository.migrateBatch(agentId, 2)).resolves.toEqual({
+ done: false,
+ migrated: 2,
+ skipped: false,
+ });
+ await expect(knowledgeBaseIdOf('doc-3')).resolves.toBeNull();
+ await expect(
+ db.select().from(agentDocuments).where(eq(agentDocuments.agentId, agentId)),
+ ).resolves.toHaveLength(3);
+
+ await expect(repository.migrateBatch(agentId, 2)).resolves.toEqual({
+ done: true,
+ migrated: 1,
+ skipped: false,
+ });
+ await expect(repository.migrateBatch(agentId, 2)).resolves.toEqual({
+ done: true,
+ migrated: 0,
+ skipped: false,
+ });
+ await expect(
+ db.select().from(knowledgeBases).where(eq(knowledgeBases.userId, userId)),
+ ).resolves.toHaveLength(1);
+ });
+
+ it('picks up a document written after the agent finished migrating', async () => {
+ await insertDocument('doc-first');
+ await repository.migrateBatch(agentId);
+
+ await insertDocument('doc-straggler');
+ await repository.migrateBatch(agentId);
+
+ await expect(knowledgeBaseIdOf('doc-straggler')).resolves.toBe(
+ await repository.findId(agentId),
+ );
+ });
+
+ // Try-lock needs a second session to observe the holder, which PGlite cannot provide.
+ it.skipIf(!isServerDB)(
+ 'skips instead of waiting when another batch holds the agent',
+ async () => {
+ await insertDocument('doc-held');
+
+ await db.transaction(async (holder) => {
+ await holder.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${`agentSpaceMigration:${agentId}`})::bigint)`,
+ );
+
+ await expect(repository.migrateBatch(agentId)).resolves.toEqual({
+ done: false,
+ migrated: 0,
+ skipped: true,
+ });
+ });
+ },
+ );
+ });
+});
diff --git a/packages/database/src/repositories/agentSpace/index.ts b/packages/database/src/repositories/agentSpace/index.ts
new file mode 100644
index 00000000000..e411a78ed9b
--- /dev/null
+++ b/packages/database/src/repositories/agentSpace/index.ts
@@ -0,0 +1,194 @@
+import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm';
+
+import {
+ agentDocuments,
+ agents,
+ agentsKnowledgeBases,
+ documents,
+ knowledgeBases,
+} from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { isDedicatedToAgentWhere } from '../../utils/agentDocumentsOwnership';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+const AGENT_SPACE_TYPE = 'agent';
+const DEFAULT_MIGRATION_BATCH_SIZE = 200;
+
+type Db = LobeChatDatabase | Transaction;
+
+export interface AgentSpaceMigrationResult {
+ /** No dedicated document of this agent is left outside its space. */
+ done: boolean;
+ /** Documents moved into the space by this batch. */
+ migrated: number;
+ /** Another batch held the agent's lock, so this one did nothing. */
+ skipped: boolean;
+}
+
+/**
+ * Owns the knowledge base dedicated to one agent and moves its documents in at runtime.
+ *
+ * Ownership lives in `knowledge_bases.type` + `settings.owner`, and the agent reaches
+ * its space through a disabled `agents_knowledge_bases` row. None of that is a database
+ * constraint, so uniqueness per agent is enforced here with an advisory lock.
+ *
+ * Migration only fills `documents.knowledge_base_id`. `agent_documents` stays the read
+ * path, so a half-migrated agent behaves exactly like an unmigrated one.
+ */
+export class AgentSpaceRepository {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ /**
+ * Finds the space of an agent visible to the caller, without creating one.
+ */
+ async findId(agentId: string, db: Db = this.db): Promise<string | undefined> {
+ const [space] = await db
+ .select({ id: knowledgeBases.id })
+ .from(agentsKnowledgeBases)
+ .innerJoin(knowledgeBases, eq(knowledgeBases.id, agentsKnowledgeBases.knowledgeBaseId))
+ .innerJoin(agents, eq(agents.id, agentsKnowledgeBases.agentId))
+ .where(
+ and(
+ eq(agentsKnowledgeBases.agentId, agentId),
+ // The mount is keyed by agent alone, so the caller's access comes from the agent.
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ eq(knowledgeBases.type, AGENT_SPACE_TYPE),
+ sql`${knowledgeBases.settings} -> 'owner' ->> 'id' = ${agentId}`,
+ ),
+ )
+ .limit(1);
+
+ return space?.id;
+ }
+
+ /**
+ * Returns the agent's space, creating it on first use.
+ *
+ * Returns:
+ * - The knowledge base id, or undefined when the agent is not visible to the caller.
+ */
+ async ensure(agentId: string): Promise<string | undefined> {
+ return (
+ (await this.findId(agentId)) ?? this.db.transaction((trx) => this.ensureWithTx(trx, agentId))
+ );
+ }
+
+ /**
+ * Same as {@link ensure}, inside a caller-owned transaction so a document insert
+ * and its space commit together.
+ */
+ async ensureWithTx(trx: Transaction, agentId: string): Promise<string | undefined> {
+ await trx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${`agentSpace:${agentId}`})::bigint)`,
+ );
+
+ // Re-check under the lock: the previous holder may have just created it.
+ const existingId = await this.findId(agentId, trx);
+ if (existingId) return existingId;
+
+ const [agent] = await trx
+ .select({
+ title: agents.title,
+ userId: agents.userId,
+ visibility: agents.visibility,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, agentId),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ ),
+ )
+ .limit(1);
+ if (!agent) return undefined;
+
+ const owner = { userId: agent.userId, workspaceId: agent.workspaceId };
+ const [space] = await trx
+ .insert(knowledgeBases)
+ .values({
+ ...owner,
+ name: agent.title || agentId,
+ settings: { owner: { id: agentId, type: AGENT_SPACE_TYPE } },
+ type: AGENT_SPACE_TYPE,
+ visibility: agent.visibility,
+ })
+ .returning({ id: knowledgeBases.id });
+
+ // Disabled: the space must never join the agent's RAG sources.
+ await trx
+ .insert(agentsKnowledgeBases)
+ .values({ ...owner, agentId, enabled: false, knowledgeBaseId: space.id });
+
+ return space.id;
+ }
+
+ /**
+ * Moves one batch of the agent's dedicated documents into its space.
+ *
+ * Use when:
+ * - An agent is accessed and may still have documents outside its space. Callers
+ * repeat until `done`; a repeat after completion is a cheap no-op, which also
+ * picks up documents written by older server versions.
+ *
+ * Expects:
+ * - The caller has already authorized access to `agentId`.
+ *
+ * Returns:
+ * - Progress for this batch. Never waits for a concurrent batch of the same agent.
+ */
+ async migrateBatch(
+ agentId: string,
+ limit = DEFAULT_MIGRATION_BATCH_SIZE,
+ ): Promise<AgentSpaceMigrationResult> {
+ return this.db.transaction(async (trx) => {
+ const lockKey = `agentSpaceMigration:${agentId}`;
+ const { rows } = await trx.execute<{ locked: boolean }>(
+ sql`SELECT pg_try_advisory_xact_lock(hashtext(${lockKey})::bigint) AS locked`,
+ );
+ if (!rows[0]?.locked) return { done: false, migrated: 0, skipped: true };
+
+ const candidates = await trx
+ .select({ id: documents.id })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(documents.id, agentDocuments.documentId))
+ .where(
+ and(
+ // Soft-deleted bindings are included so a restored document is already in place.
+ eq(agentDocuments.agentId, agentId),
+ isNull(documents.knowledgeBaseId),
+ isDedicatedToAgentWhere(agentId),
+ ),
+ )
+ .orderBy(asc(documents.id))
+ .limit(limit);
+
+ // Agents without dedicated documents never get an empty space.
+ if (candidates.length === 0) return { done: true, migrated: 0, skipped: false };
+
+ const spaceId = await this.ensureWithTx(trx, agentId);
+ if (!spaceId) return { done: false, migrated: 0, skipped: true };
+
+ const migrated = await trx
+ .update(documents)
+ // Explicit `updatedAt` bypasses `$onUpdate`: moving a document is not an edit.
+ .set({ knowledgeBaseId: spaceId, updatedAt: documents.updatedAt as unknown as Date })
+ .where(
+ and(
+ inArray(
+ documents.id,
+ candidates.map(({ id }) => id),
+ ),
+ isNull(documents.knowledgeBaseId),
+ ),
+ )
+ .returning({ id: documents.id });
+
+ return { done: candidates.length < limit, migrated: migrated.length, skipped: false };
+ });
+ }
+}
diff --git a/packages/database/src/utils/agentDocumentsOwnership.ts b/packages/database/src/utils/agentDocumentsOwnership.ts
index e5be0957b41..ec71f505724 100644
--- a/packages/database/src/utils/agentDocumentsOwnership.ts
+++ b/packages/database/src/utils/agentDocumentsOwnership.ts
@@ -59,6 +59,28 @@ const isDedicatedToAgents = (
return agentIds.has(provenanceAgentId);
};
+/**
+ * SQL form of {@link isDedicatedToAgents} for one agent, over `documents` joined to `agent_documents`.
+ *
+ * Use when:
+ * - Candidates must be selected in the database instead of classified row by row.
+ *
+ * Returns:
+ * - A predicate that fails safe the same way: unknown provenance is not dedicated.
+ */
+export const isDedicatedToAgentWhere = (agentId: string) =>
+ and(
+ inArray(documents.sourceType, [...DEDICATED_AGENT_DOCUMENT_SOURCE_TYPES]),
+ or(
+ // `starts_with`, not LIKE: agent ids contain `_`, a LIKE wildcard.
+ sql`starts_with(${documents.source}, ${`${AGENT_DOCUMENT_SOURCE_PREFIX}${agentId}/`})`,
+ and(
+ eq(documents.source, SKILL_MANAGEMENT_SOURCE),
+ eq(agentDocuments.templateId, AGENT_SKILL_TEMPLATE_ID),
+ ),
+ ),
+ );
+
/**
* A document tree moves or stays as a WHOLE.
*