🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(database): split the 1899-line agentDocument model into cohesive modules (#21153)
Arvin Xua3e1e059c8d0
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsdeleted file mode 100644index 4cbdfcc7165..00000000000--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ /dev/null@@ -1,1899 +0,0 @@-import { AGENT_DOCUMENT_FILE_TYPE, AGENT_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';-import type { DocumentAccessScope } from '@lobechat/types';-import { ordinaryDocumentAccessScope, stripAgentShareDocumentProvenance } from '@lobechat/types';-import {- and,- asc,- desc,- eq,- exists,- inArray,- isNotNull,- isNull,- like,- ne,- notExists,- or,- sql,-} from 'drizzle-orm';--import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';-import { AGENT_SKILL_TEMPLATE_ID, agentDocuments, documents } from '../../schemas';-import type { LobeChatDatabase, Transaction } from '../../type';-import { documentMatchesAccessScope } from '../../utils/documentVisibility';-import { buildWorkspaceWhere } from '../../utils/workspace';-import { buildCopyParams } from './copyDocument';-import { deriveAgentDocumentFields } from './deriveFields';-import { buildDocumentFilename } from './filename';-import {- composeToolPolicyUpdate,- isLoadableDocument,- normalizePolicy,- parseLoadRules,- resolveDocumentLoadPosition,- sortByLoadRulePriority,-} from './policy';-import type {- AgentDocument,- AgentDocumentContextRow,- AgentDocumentListItem,- AgentDocumentListSourceType,- AgentDocumentPolicy,- AgentDocumentSourceType,- AgentDocumentWithRules,- DocumentLoadRules,- ToolUpdateLoadRule,-} from './types';-import {- AgentAccess,- DocumentLoadFormat,- DocumentLoadPosition,- DocumentLoadRule,- PolicyLoad,-} from './types';--export * from './types';--interface AgentDocumentQueryOptions {- cursor?: string;- deletedOnly?: boolean;- includeDeleted?: boolean;- limit?: number;-}--interface AgentDocumentCreateParams {- createdAt?: Date;- editorData?: Record<string, any>;- fileId?: string;- fileType?: string;- loadPosition?: DocumentLoadPosition;- loadRules?: DocumentLoadRules;- metadata?: Record<string, any>;- parentId?: string | null;- policy?: AgentDocumentPolicy;- policyLoad?: PolicyLoad;- source?: string;- sourceType?: AgentDocumentSourceType;- templateId?: string;- title?: string;- updatedAt?: Date;-}--interface ConvertAgentDocumentToSkillIndexParams {- agentDocumentId: string;- content: string;- editorData?: Record<string, unknown>;- filename: string;- metadata: Record<string, unknown>;- parentId: string;- source: string;- sourceType: AgentDocumentSourceType;- title: string;-}--/** Columns of one document-tree row (agent binding joined to its document). */-const listItemColumns = {- createdAt: documents.createdAt,- description: documents.description,- documentId: agentDocuments.documentId,- documentUpdatedAt: documents.updatedAt,- fileId: documents.fileId,- fileType: documents.fileType,- filename: documents.filename,- id: agentDocuments.id,- parentId: documents.parentId,- policy: agentDocuments.policy,- sourceType: documents.sourceType,- templateId: agentDocuments.templateId,- title: documents.title,- updatedAt: agentDocuments.updatedAt,-};--interface AgentDocumentListQueryRow {- createdAt: Date;- description: string | null;- documentId: string;- documentUpdatedAt: Date;- fileId: string | null;- filename: string | null;- fileType: string;- id: string;- parentId: string | null;- policy: unknown;- sourceType: AgentDocumentSourceType;- templateId: string | null;- title: string | null;- updatedAt: Date;-}--/**- * Map the list API's source filter onto `documents.source_type`.- *- * The list contract has two buckets: `web` (crawled pages) and `file` (everything- * authored or uploaded as an agent document). Authored docs are stored as- * `agent` / `agent-signal` / `api`, so `file` means "not web" rather than the- * literal `file` source type, which only covers uploaded originals.- */-const listSourceTypeFilter = (sourceType?: AgentDocumentListSourceType) => {- if (sourceType === 'web') return [eq(documents.sourceType, 'web')];- if (sourceType === 'file') return [ne(documents.sourceType, 'web')];- return [];-};--export class AgentDocumentModel {- private userId: string;- private workspaceId?: string;- private db: LobeChatDatabase;- private documentAccessScope: DocumentAccessScope;-- constructor(- db: LobeChatDatabase,- userId: string,- workspaceId?: string,- documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,- ) {- this.userId = userId;- this.workspaceId = workspaceId;- this.db = db;- this.documentAccessScope = documentAccessScope;- }-- /**- * Workspace-aware ownership predicate for the `agent_documents` binding table.- * Personal mode → `user_id = ? AND workspace_id IS NULL`; workspace mode → `workspace_id = ?`.- */- private agentDocOwnership() {- // NOTICE:- // For now, we expect a caller authorized to access an agent to access all resources- // bound under its agent documents, including backing files, without a separate- // Resources publish step. Tool reads and UI previews need the same access contract.- // Agent documents and backing files use separate visibility checks; uploads without- // the agent-document source can expose a document in tools/the tree while its- // original-file preview returns 404. Dedicated uploads now default to public.- // Context: AgentDocumentsService.importFile and FileDocumentPreview; this predicate- // scopes bindings but does not itself authorize access to the agent.- // Replace this interim assumption when a consistent workspace authorization model- // covers agent documents, backing files, tool execution, and resource publishing.-- // REVIEW: A private upload must not silently become readable merely because someone- // can access its agent. Restricting preview or even one read tool is insufficient:- // if an agent can read private content through another path or its existing context,- // a user can prompt it to copy or summarize that content into a shared knowledge base- // and leak it. The current assumption does not provide per-resource confidentiality.-- // TODO: Revisit this coarse model before extending workspace permission controls.- // Define how sharing is authorized and how reads, execution context, and writes to- // broader audiences are constrained; enforce the resulting rules across all paths.- return and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentDocuments),- exists(- this.db- .select({ id: documents.id })- .from(documents)- .where(- and(- eq(documents.id, agentDocuments.documentId),- documentMatchesAccessScope(documents.metadata, this.documentAccessScope),- ),- ),- ),- );- }-- /** Workspace-aware ownership predicate for the backing `documents` rows. */- private documentOwnership() {- return and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),- documentMatchesAccessScope(documents.metadata, this.documentAccessScope),- );- }-- private getDocumentStats(content: string) {- if (!content) return { totalCharCount: 0, totalLineCount: 0 };-- return {- totalCharCount: content.length,- totalLineCount: content.split('\n').length,- };- }-- private getMetadataDescription(metadata?: Record<string, unknown> | null): string | undefined {- if (!metadata) return undefined;-- if (typeof metadata.description === 'string') return metadata.description;-- const skill = metadata.skill;- if (!skill || typeof skill !== 'object') return undefined;-- const frontmatter = (skill as Record<string, unknown>).frontmatter;- if (!frontmatter || typeof frontmatter !== 'object') return undefined;-- const description = (frontmatter as Record<string, unknown>).description;- return typeof description === 'string' ? description : undefined;- }-- private scopeMetadata(metadata?: Record<string, any>): Record<string, any> | undefined {- const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);- if (this.documentAccessScope.type !== 'agentShare') return sanitizedMetadata;-- return {- ...sanitizedMetadata,- agentShare: {- shareId: this.documentAccessScope.shareId,- topicId: this.documentAccessScope.topicId,- visitorUserId: this.documentAccessScope.visitorUserId,- },- };- }-- private toAgentDocument(- settings: typeof agentDocuments.$inferSelect,- doc: DocumentItem,- ): AgentDocument {- const policy = (settings.policy as AgentDocumentPolicy | null) ?? null;- const policyLoadFormat =- (settings.policyLoadFormat as DocumentLoadFormat | null) ??- policy?.context?.policyLoadFormat ??- DocumentLoadFormat.RAW;-- return {- accessPublic: settings.accessPublic,- accessSelf: settings.accessSelf,- accessShared: settings.accessShared,- agentId: settings.agentId,- policyLoad: settings.policyLoad as PolicyLoad,- content: doc.content ?? '',- createdAt: settings.createdAt,- deleteReason: settings.deleteReason,- deletedAt: settings.deletedAt,- deletedByAgentId: settings.deletedByAgentId,- deletedByUserId: settings.deletedByUserId,- description: doc.description ?? null,- documentId: settings.documentId,- editorData: doc.editorData ?? null,- fileType: doc.fileType,- filename: doc.filename ?? '',- id: settings.id,- metadata: (doc.metadata as Record<string, any> | null) ?? null,- parentId: doc.parentId ?? null,- policy,- policyLoadFormat,- policyLoadPosition: settings.policyLoadPosition,- policyLoadRule: settings.policyLoadRule,- source: doc.source ?? null,- sourceType: doc.sourceType,- templateId: settings.templateId ?? null,- title: doc.title ?? doc.filename ?? '',- updatedAt: settings.updatedAt,- userId: settings.userId,- };- }-- private toAgentDocumentListItem(row: AgentDocumentListQueryRow): AgentDocumentListItem {- const filename = row.filename ?? '';- const policy = (row.policy as AgentDocumentPolicy | null) ?? null;- const item = {- createdAt: row.createdAt,- description: row.description ?? null,- documentId: row.documentId,- documentUpdatedAt: row.documentUpdatedAt,- fileId: row.fileId,- fileType: row.fileType,- filename,- id: row.id,- loadPosition: policy?.context?.position,- parentId: row.parentId ?? null,- sourceType: row.sourceType,- templateId: row.templateId ?? null,- title: row.title ?? filename,- updatedAt: row.updatedAt,- };-- return {- ...item,- ...deriveAgentDocumentFields(item),- };- }-- private buildDeletedAtFilters(options?: AgentDocumentQueryOptions) {- if (options?.deletedOnly) return [isNotNull(agentDocuments.deletedAt)];- if (options?.includeDeleted) return [];-- return [isNull(agentDocuments.deletedAt)];- }-- private normalizeListOffset(cursor?: string): number {- if (!cursor) return 0;-- const parsed = Number.parseInt(cursor, 10);-- // Offset cursors keep the first VFS pagination pass storage-neutral.- // Callers that need opaque cursors can wrap this model helper at the service layer later.- return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;- }-- private async listByParentIds(- agentId: string,- parentIds: string[],- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument[]> {- if (parentIds.length === 0) return [];-- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- inArray(documents.parentId, parentIds),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id));-- return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));- }-- /**- * Counts live children per parent `documentId`, for listings that show which- * entries (folders or documents) have something nested under them. Omit- * `parentIds` to count every parent of the agent in one grouped query.- * Parents without children are absent from the map.- */- async countChildrenByParentIds(- agentId: string,- parentIds?: string[],- ): Promise<Map<string, number>> {- if (parentIds?.length === 0) return new Map();-- const rows = await this.db- .select({ count: sql<number>`count(*)::int`, parentId: documents.parentId })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- parentIds ? inArray(documents.parentId, parentIds) : isNotNull(documents.parentId),- isNull(agentDocuments.deletedAt),- ),- )- .groupBy(documents.parentId);-- return new Map(- rows.flatMap((row) => (row.parentId ? [[row.parentId, Number(row.count)] as const] : [])),- );- }-- /**- * Associates an existing document row with an agent document binding.- *- * Use when:- * - A document already exists and should become visible to an agent.- * - Managed mount providers need to bind pre-created document tree nodes.- *- * Expects:- * - `documentId` belongs to the current user.- * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.- *- * Returns:- * - The inserted or existing agent document binding id.- * - An empty id only when the source document is missing.- *- */- async associate(params: {- agentId: string;- documentId: string;- policyLoad?: PolicyLoad;- }): Promise<{ id: string }> {- const { agentId, documentId, policyLoad } = params;-- return this.db.transaction(async (trx) => {- const [doc] = await trx- .select()- .from(documents)- .where(and(eq(documents.id, documentId), this.documentOwnership()))- .limit(1);-- if (!doc) return { id: '' };-- const [result] = await trx- .insert(agentDocuments)- .values({- accessPublic: 0,- accessSelf:- AgentAccess.EXECUTE |- AgentAccess.LIST |- AgentAccess.READ |- AgentAccess.WRITE |- AgentAccess.DELETE,- accessShared: 0,- agentId,- documentId,- policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,- policyLoadFormat: DocumentLoadFormat.RAW,- policyLoadPosition: DocumentLoadPosition.BEFORE_FIRST_USER,- policyLoadRule: DocumentLoadRule.ALWAYS,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })- .onConflictDoNothing()- .returning({ id: agentDocuments.id });-- if (result) return result;-- // A concurrent caller (or an earlier run) may already own this unique- // agent/document binding. The conflict loser must resolve that row instead- // of leaking `undefined` to callers that need the binding id.- const [existing] = await trx- .select({ id: agentDocuments.id })- .from(agentDocuments)- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(agentDocuments.documentId, documentId),- ),- )- .limit(1);-- return { id: existing?.id ?? '' };- });- }-- /**- * Creates a document row and links it to an agent in one transaction.- *- * Use when:- * - Creating ordinary agent-visible VFS files or folders.- * - Creating model-owned documents that still need agent document policy metadata.- *- * Expects:- * - `filename` is a single VFS segment supplied by the caller.- * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.- *- * Returns:- * - The created agent document with joined document content and metadata.- *- */- async create(- agentId: string,- filename: string,- content: string,- params?: AgentDocumentCreateParams,- ): Promise<AgentDocument> {- return this.db.transaction((trx) => this.createWithTx(trx, agentId, filename, content, params));- }-- /**- * Creates a document row and links it to an agent inside a caller-owned transaction.- *- * Use when:- * - A higher-level aggregate must create multiple agent documents atomically.- * - Callers already run `db.transaction` and need to avoid nested transactions.- *- * Expects:- * - `trx` is the active transaction for every write in the aggregate.- * - `filename` is a single VFS segment supplied by the caller.- *- * Returns:- * - The created agent document with joined document content and metadata.- */- async createWithTx(- trx: Transaction,- agentId: string,- filename: string,- content: string,- params?: AgentDocumentCreateParams,- ): Promise<AgentDocument> {- const {- createdAt,- editorData,- fileId,- fileType = AGENT_DOCUMENT_FILE_TYPE,- loadPosition,- loadRules,- metadata,- parentId,- policy,- policyLoad,- source,- sourceType = AGENT_DOCUMENT_SOURCE_TYPE,- templateId,- title: providedTitle,- updatedAt,- } = params ?? {};-- const title = providedTitle?.trim() || filename.replace(/\.[^.]+$/, '');- const stats = this.getDocumentStats(content);- const normalizedPolicy = normalizePolicy(loadPosition, loadRules, policy);- const scopedMetadata = this.scopeMetadata(metadata);-- const documentPayload: NewDocument = {- content,- createdAt,- description: this.getMetadataDescription(scopedMetadata),- // NOTICE:- // Agent documents often carry Markdown `content`, but editor history and restore UI- // depend on this serialized editor snapshot. Service callers that derive content from- // Markdown should pass a matching `editorData` snapshot instead of relying on content alone.- // Root cause: `document_histories` snapshots `editor_data`, so missing editor data makes- // pre-mutation history capture impossible.- // Removal condition: only if document history supports Markdown-content snapshots.- editorData,- fileType,- filename,- parentId,- metadata: scopedMetadata,- ...(fileId ? { fileId } : {}),- source: source ?? `agent-document://${agentId}/${encodeURIComponent(filename)}`,- sourceType,- title,- totalCharCount: stats.totalCharCount,- totalLineCount: stats.totalLineCount,- updatedAt: updatedAt ?? createdAt,- userId: this.userId,- // Keep newly created agent resources shared within their existing workspace scope.- visibility: 'public',- workspaceId: this.workspaceId ?? null,- };-- const [insertedDocument] = await trx.insert(documents).values(documentPayload).returning();-- const newDoc: NewAgentDocument = {- accessPublic: 0,- accessSelf:- AgentAccess.EXECUTE |- AgentAccess.LIST |- AgentAccess.READ |- AgentAccess.WRITE |- AgentAccess.DELETE,- accessShared: 0,- agentId,- createdAt,- policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,- deleteReason: null,- deletedAt: null,- deletedByAgentId: null,- deletedByUserId: null,- documentId: insertedDocument!.id,- policy: normalizedPolicy,- policyLoadFormat: normalizedPolicy.context?.policyLoadFormat || DocumentLoadFormat.RAW,- policyLoadPosition:- normalizedPolicy.context?.position || DocumentLoadPosition.BEFORE_FIRST_USER,- policyLoadRule: normalizedPolicy.context?.rule || DocumentLoadRule.ALWAYS,- templateId,- updatedAt: updatedAt ?? createdAt,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- };-- const [settings] = await trx.insert(agentDocuments).values(newDoc).returning();-- return this.toAgentDocument(settings!, insertedDocument!);- }-- /**- * Converts an existing ordinary agent document binding into a managed skill index.- *- * Use when:- * - Agent Signal promoted an already-created agent document into skill management.- * - The caller must preserve both the agent document id and backing document id.- *- * Expects:- * - `agentDocumentId` is a live binding owned by the current user.- * - `parentId` points to the managed skill bundle document row.- *- * Returns:- * - The same agent document binding after document identity and load metadata are updated.- *- */- async convertAgentDocumentToSkillIndex(- params: ConvertAgentDocumentToSkillIndexParams,- ): Promise<AgentDocument | undefined> {- return this.db.transaction((trx) => this.convertAgentDocumentToSkillIndexWithTx(trx, params));- }-- /**- * Converts a live agent document binding into a managed skill index inside a transaction.- *- * Use when:- * - A higher-level skill aggregate also creates the owning bundle in the same transaction.- * - The caller must preserve both `agent_documents.id` and `documents.id`.- *- * Expects:- * - `trx` is the active transaction for the whole skill creation operation.- * - `parentId` points to the managed skill bundle document row inside the same transaction.- *- * Returns:- * - The same agent document binding after document identity and load metadata are updated.- */- async convertAgentDocumentToSkillIndexWithTx(- trx: Transaction,- params: ConvertAgentDocumentToSkillIndexParams,- ): Promise<AgentDocument | undefined> {- const [existingResult] = await trx- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- eq(agentDocuments.id, params.agentDocumentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- )- .limit(1);-- if (!existingResult) return undefined;-- const existing = this.toAgentDocument(existingResult.settings, existingResult.doc);- if (!existing) return undefined;-- const stats = this.getDocumentStats(params.content);- const updatedAt = new Date();- const scopedMetadata = this.scopeMetadata(params.metadata);-- await trx- .update(documents)- .set({- content: params.content,- description: this.getMetadataDescription(scopedMetadata),- ...(params.editorData !== undefined && { editorData: params.editorData }),- filename: params.filename,- fileType: 'skills/index',- metadata: scopedMetadata,- parentId: params.parentId,- source: params.source,- sourceType: params.sourceType,- title: params.title,- totalCharCount: stats.totalCharCount,- totalLineCount: stats.totalLineCount,- })- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));-- await trx- .update(agentDocuments)- .set({- policyLoad: PolicyLoad.DISABLED,- templateId: 'agent-skill',- updatedAt,- })- .where(- and(- eq(agentDocuments.id, params.agentDocumentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- );-- const [updatedResult] = await trx- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- eq(agentDocuments.id, params.agentDocumentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- )- .limit(1);-- return updatedResult- ? this.toAgentDocument(updatedResult.settings, updatedResult.doc)- : undefined;- }-- /**- * Writes a repaired editor snapshot only if the backing document still holds- * the version the repair was computed from.- *- * Use when:- * - A read path rebuilds `editorData` from Markdown and must persist it so the- * node ids it exposes stay addressable, without clobbering a concurrent save.- *- * Expects:- * - `expected` is the `content` / `editorData` pair the caller read.- *- * Returns:- * - `true` when the snapshot was written; `false` when the document changed- * (or is gone) since it was read, in which case nothing is written.- */- async updateEditorSnapshotIfUnchanged(- documentId: string,- expected: { content: string; editorData: Record<string, any> | null },- next: { content: string; editorData: Record<string, any> },- ): Promise<boolean> {- const existing = await this.findById(documentId);- if (!existing) return false;-- const stats = this.getDocumentStats(next.content);- const expectedEditorData =- expected.editorData === null || expected.editorData === undefined- ? null- : JSON.stringify(expected.editorData);-- const updated = await this.db- .update(documents)- .set({- content: next.content,- editorData: next.editorData,- totalCharCount: stats.totalCharCount,- totalLineCount: stats.totalLineCount,- })- .where(- and(- eq(documents.id, existing.documentId),- this.documentOwnership(),- sql`coalesce(${documents.content}, '') = ${expected.content}`,- sql`${documents.editorData} IS NOT DISTINCT FROM ${expectedEditorData}::jsonb`,- ),- )- .returning({ id: documents.id });-- return updated.length > 0;- }-- async update(- documentId: string,- params?: {- content?: string;- editorData?: Record<string, any> | null;- fileType?: string;- loadPosition?: DocumentLoadPosition;- loadRules?: Partial<DocumentLoadRules>;- metadata?: Record<string, any>;- policy?: AgentDocumentPolicy;- policyLoad?: PolicyLoad;- },- ): Promise<void> {- const { content, editorData, fileType, loadPosition, loadRules, metadata, policy, policyLoad } =- params ?? {};-- const existing = await this.findById(documentId);-- if (!existing) return;-- const existingPolicy = existing.policy || {};- const existingContext = existingPolicy.context || {};-- const mergedPolicy = normalizePolicy(- loadPosition ||- (existingContext.position as DocumentLoadPosition | undefined) ||- DocumentLoadPosition.BEFORE_FIRST_USER,- {- keywordMatchMode: loadRules?.keywordMatchMode ?? existingContext.keywordMatchMode,- keywords: loadRules?.keywords ?? existingContext.keywords,- maxTokens: loadRules?.maxTokens ?? existingContext.maxTokens,- priority: loadRules?.priority ?? existingContext.priority,- regexp: loadRules?.regexp ?? existingContext.regexp,- rule: (loadRules?.rule ??- existingContext.rule ??- DocumentLoadRule.ALWAYS) as DocumentLoadRule,- timeRange: loadRules?.timeRange ?? existingContext.timeRange,- },- policy ? { ...existingPolicy, ...policy } : existingPolicy,- );-- const settingsUpdate: Partial<NewAgentDocument> = {- policy: mergedPolicy,- policyLoadFormat: mergedPolicy.context?.policyLoadFormat || DocumentLoadFormat.RAW,- policyLoadPosition: mergedPolicy.context?.position || DocumentLoadPosition.BEFORE_FIRST_USER,- policyLoadRule: mergedPolicy.context?.rule || DocumentLoadRule.ALWAYS,- ...(policyLoad !== undefined && { policyLoad }),- };-- await this.db.transaction(async (trx) => {- if (- content !== undefined ||- editorData !== undefined ||- fileType !== undefined ||- metadata !== undefined- ) {- const documentUpdate: Partial<NewDocument> = {};-- if (content !== undefined) {- // NOTICE:- // Updating Markdown content alone is valid for raw consumers, but it does not refresh- // the editor snapshot used by document history. Callers that replace full Markdown- // should also provide `editorData` from the same content when they expect history or- // editor restore support to keep working.- // Root cause: `DocumentService.trySaveCurrentDocumentHistory` validates editor data- // before creating history rows.- // Removal condition: only if document history supports Markdown-content snapshots.- const stats = this.getDocumentStats(content);- documentUpdate.content = content;- documentUpdate.totalCharCount = stats.totalCharCount;- documentUpdate.totalLineCount = stats.totalLineCount;- }-- if (editorData !== undefined) {- documentUpdate.editorData = editorData;- }-- if (fileType !== undefined) {- documentUpdate.fileType = fileType;- }-- if (metadata !== undefined) {- const scopedMetadata = this.scopeMetadata(metadata);- documentUpdate.metadata = scopedMetadata;- documentUpdate.description = this.getMetadataDescription(scopedMetadata);- }-- await trx- .update(documents)- .set(documentUpdate)- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));- }-- await trx- .update(agentDocuments)- .set(settingsUpdate)- .where(and(eq(agentDocuments.id, documentId), this.agentDocOwnership()));- });- }-- /**- * Updates backing document identity fields without changing ids or load policy.- *- * Use when:- * - Managed skill services need to rename or reparent a document row.- * - Callers must preserve agent document id and backing document id.- *- * Expects:- * - `agentDocumentId` is the agent document binding id, not the backing document row id.- * - Omitted fields are left untouched.- *- * Returns:- * - The same agent document binding after identity fields are updated.- *- */- async updateDocumentIdentity(- agentDocumentId: string,- params: {- filename?: string;- metadata?: Record<string, unknown>;- parentId?: string | null;- title?: string;- },- ): Promise<AgentDocument | undefined> {- const existing = await this.findById(agentDocumentId);- if (!existing) return undefined;-- if (- params.filename === undefined &&- params.metadata === undefined &&- params.parentId === undefined &&- params.title === undefined- ) {- return existing;- }-- await this.db- .update(documents)- .set({- ...(params.filename !== undefined && { filename: params.filename }),- ...(params.metadata !== undefined && {- description: this.getMetadataDescription(this.scopeMetadata(params.metadata)),- metadata: this.scopeMetadata(params.metadata),- }),- ...(params.parentId !== undefined && { parentId: params.parentId }),- ...(params.title !== undefined && { title: params.title }),- })- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));-- return this.findById(agentDocumentId);- }-- /**- * Renames an agent document by updating the backing document filename and title.- *- * Use when:- * - A caller wants title-style rename behavior.- * - The document should keep its binding, content, policy, and document identity.- *- * Expects:- * - `newTitle` is a human-readable title that can be normalized into a filename.- * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.- *- * Returns:- * - The renamed agent document, or `undefined` when the binding is not visible.- *- */- async rename(- documentId: string,- newTitle: string,- options?: { filename?: string },- ): Promise<AgentDocument | undefined> {- const existing = await this.findById(documentId);- if (!existing) return undefined;-- const title = newTitle.trim();- if (!title) return existing;-- const filename = options?.filename?.trim() || buildDocumentFilename(title);- const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;-- await this.db.transaction(async (trx) => {- await trx- .update(documents)- .set({- filename,- source,- title,- })- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));- });-- return this.findById(documentId);- }-- /**- * Moves or renames an agent document without changing its binding or document identity.- *- * Use when:- * - VFS `rename(from, to)` needs filesystem-style metadata mutation- * - Callers must preserve document id, agent document id, policy, history, and load settings- *- * Expects:- * - `filename` is already validated as a single VFS path segment- * - `parentId` points to a document row owned by the same user, or `null` for root- * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately- * - `title` defaults to `filename` (path-style rename); id-based moves pass the current title- * so relocating a document never rewrites what the user sees- *- * Returns:- * - The same agent document binding after the backing document row is moved- *- */- async movePath(- documentId: string,- params: { filename: string; parentId: string | null; title?: string },- ): Promise<AgentDocument | undefined> {- const existing = await this.findById(documentId);- if (!existing) return undefined;-- const filename = params.filename.trim();- if (!filename) return existing;-- const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;-- await this.db.transaction(async (trx) => {- await trx- .update(documents)- .set({- filename,- parentId: params.parentId,- source,- title: params.title ?? filename,- })- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));- });-- return this.findById(documentId);- }-- async copy(documentId: string, newTitle?: string): Promise<AgentDocument | undefined> {- const existing = await this.findById(documentId);- if (!existing) return undefined;-- const title = newTitle?.trim();- const filename = title- ? buildDocumentFilename(title)- : `copy-${Date.now()}-${existing.filename}`;-- // Empty-parse shells must not be duplicated as another shell (the clone- // reads as Lexical error #38 and blocks cleanup); see `copyDocument.ts`- // for the shell detection and raw-text downgrade.- return this.create(- existing.agentId,- filename,- existing.content,- buildCopyParams(existing, title),- );- }-- async updateToolLoadRule(- documentId: string,- rule: ToolUpdateLoadRule,- ): Promise<AgentDocument | undefined> {- const existing = await this.findById(documentId);- if (!existing) return undefined;- const composedPolicy = composeToolPolicyUpdate(existing.policy, rule, existing.policyLoad);-- await this.db- .update(agentDocuments)- .set({- policyLoad: composedPolicy.policyLoad,- policy: composedPolicy.policy,- policyLoadFormat: composedPolicy.policyLoadFormat,- policyLoadRule: composedPolicy.policyLoadRule,- })- .where(- and(- eq(agentDocuments.id, documentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- );-- return this.findById(documentId);- }-- async findById(- documentId: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument | undefined> {- return this.findByIdWithOptions(documentId, options);- }-- async findByIdWithOptions(- documentId: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument | undefined> {- const [result] = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- eq(agentDocuments.id, documentId),- this.agentDocOwnership(),- ...this.buildDeletedAtFilters(options),- ),- )- .limit(1);-- if (!result) return undefined;-- return this.toAgentDocument(result.settings, result.doc);- }-- /**- * Updates an existing document by filename or creates a new one when missing.- *- * Use when:- * - Callers want idempotent writes keyed by agent and filename.- * - Existing document policy and metadata should be merged on update.- *- * Expects:- * - `filename` addresses the current agent's ordinary filename lookup.- * - Duplicate filenames are allowed; the first matching filename is the oldest live binding.- *- * Returns:- * - The updated or created agent document.- *- */- async upsert(- agentId: string,- filename: string,- content: string,- params?: {- createdAt?: Date;- editorData?: Record<string, any>;- loadPosition?: DocumentLoadPosition;- loadRules?: DocumentLoadRules;- metadata?: Record<string, any>;- policy?: AgentDocumentPolicy;- policyLoad?: PolicyLoad;- templateId?: string;- updatedAt?: Date;- },- ): Promise<AgentDocument> {- const {- createdAt,- editorData,- loadPosition,- loadRules,- metadata,- policy,- policyLoad,- templateId,- updatedAt,- } = params ?? {};-- const existing = await this.findByFilename(agentId, filename);-- if (existing) {- const currentRules = parseLoadRules(existing);- const mergedRules = loadRules ? { ...currentRules, ...loadRules } : currentRules;- const mergedMetadata = metadata- ? { ...existing.metadata, ...metadata }- : (existing.metadata ?? undefined);-- await this.update(existing.id, {- content,- editorData,- loadPosition,- loadRules: mergedRules,- metadata: mergedMetadata,- policy,- policyLoad,- });-- return (await this.findByFilename(agentId, filename))!;- }-- return this.create(agentId, filename, content, {- createdAt,- editorData,- loadPosition,- loadRules,- metadata,- policy,- policyLoad,- templateId,- updatedAt,- });- }-- async findByAgent(agentId: string): Promise<AgentDocumentWithRules[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- isNull(agentDocuments.deletedAt),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => {- const item = this.toAgentDocument(settings, doc);- return {- ...item,- ...deriveAgentDocumentFields(item),- loadRules: parseLoadRules(item),- };- });- }-- async listByAgent(- agentId: string,- options?: { excludeWeb?: boolean; parentId?: string; sourceType?: AgentDocumentListSourceType },- ): Promise<AgentDocumentListItem[]> {- const sourceType = options?.sourceType;- const parentId = options?.parentId;- const excludeWeb = options?.excludeWeb;- const results = await this.db- .select(listItemColumns)- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- isNull(agentDocuments.deletedAt),- ...listSourceTypeFilter(sourceType),- ...(excludeWeb ? [ne(documents.sourceType, 'web')] : []),- ...(parentId ? [eq(documents.parentId, parentId)] : []),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map((row) => this.toAgentDocumentListItem(row));- }-- async findSkillDocsByAgent(agentId: string): Promise<AgentDocumentWithRules[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- isNull(agentDocuments.deletedAt),- or(- eq(agentDocuments.templateId, AGENT_SKILL_TEMPLATE_ID),- like(documents.fileType, 'skills/%'),- ),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => {- const item = this.toAgentDocument(settings, doc);- return {- ...item,- ...deriveAgentDocumentFields(item),- loadRules: parseLoadRules(item),- };- });- }-- async findContextByAgent(agentId: string): Promise<AgentDocumentContextRow[]> {- const results = await this.db- .select({- doc: {- content: sql<string>`- CASE- WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS}- THEN COALESCE(${documents.content}, '')- ELSE ''- END- `.as('content'),- description: documents.description,- editorData: sql<Record<string, any> | null>`- CASE- WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS} THEN ${documents.editorData}- ELSE NULL- END- `.as('editor_data'),- filename: documents.filename,- fileType: documents.fileType,- parentId: documents.parentId,- sourceType: documents.sourceType,- title: documents.title,- totalCharCount: documents.totalCharCount,- },- settings: {- agentId: agentDocuments.agentId,- createdAt: agentDocuments.createdAt,- documentId: agentDocuments.documentId,- id: agentDocuments.id,- policy: agentDocuments.policy,- policyLoad: agentDocuments.policyLoad,- policyLoadFormat: agentDocuments.policyLoadFormat,- policyLoadPosition: agentDocuments.policyLoadPosition,- policyLoadRule: agentDocuments.policyLoadRule,- templateId: agentDocuments.templateId,- updatedAt: agentDocuments.updatedAt,- },- })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- isNull(agentDocuments.deletedAt),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => {- const policy = (settings.policy as AgentDocumentPolicy | null) ?? null;- const item: Omit<- AgentDocumentContextRow,- 'category' | 'isFolder' | 'isSkillBundle' | 'isSkillIndex' | 'loadRules'- > = {- content: doc.content,- contentCharCount: doc.totalCharCount,- createdAt: settings.createdAt,- description: doc.description ?? null,- documentId: settings.documentId,- editorData: doc.editorData ?? null,- filename: doc.filename ?? '',- fileType: doc.fileType,- id: settings.id,- parentId: doc.parentId ?? null,- policy,- policyLoad: settings.policyLoad as PolicyLoad,- policyLoadFormat:- (settings.policyLoadFormat as DocumentLoadFormat | null) ??- policy?.context?.policyLoadFormat ??- DocumentLoadFormat.RAW,- policyLoadPosition: settings.policyLoadPosition,- policyLoadRule: settings.policyLoadRule,- sourceType: doc.sourceType,- templateId: settings.templateId ?? null,- title: doc.title ?? doc.filename ?? '',- updatedAt: settings.updatedAt,- };- return {- ...item,- ...deriveAgentDocumentFields(item),- loadRules: parseLoadRules(item),- };- });- }-- async findByDocumentIds(- agentId: string,- documentIds: string[],- ): Promise<AgentDocumentWithRules[]> {- if (documentIds.length === 0) return [];-- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- inArray(agentDocuments.documentId, documentIds),- isNull(agentDocuments.deletedAt),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => {- const item = this.toAgentDocument(settings, doc);- return {- ...item,- ...deriveAgentDocumentFields(item),- loadRules: parseLoadRules(item),- };- });- }-- async listByDocumentIds(- agentId: string,- documentIds: string[],- options?: { sourceType?: AgentDocumentListSourceType },- ): Promise<AgentDocumentListItem[]> {- if (documentIds.length === 0) return [];-- const sourceType = options?.sourceType;- const results = await this.db- .select(listItemColumns)- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- inArray(agentDocuments.documentId, documentIds),- isNull(agentDocuments.deletedAt),- ...listSourceTypeFilter(sourceType),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map((row) => this.toAgentDocumentListItem(row));- }-- async hasByAgent(agentId: string): Promise<boolean> {- const [result] = await this.db- .select({ id: agentDocuments.id })- .from(agentDocuments)- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- isNull(agentDocuments.deletedAt),- ),- )- .limit(1);-- return !!result;- }-- async findByTemplate(agentId: string, templateId: string): Promise<AgentDocumentWithRules[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(agentDocuments.templateId, templateId),- isNull(agentDocuments.deletedAt),- ),- )- .orderBy(desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => {- const item = this.toAgentDocument(settings, doc);- return {- ...item,- ...deriveAgentDocumentFields(item),- loadRules: parseLoadRules(item),- };- });- }-- async findByFilename(- agentId: string,- filename: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument | undefined> {- const [result] = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(documents.filename, filename),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))- .limit(1);-- if (!result) return undefined;-- return this.toAgentDocument(result.settings, result.doc);- }-- async findByParentAndFilename(- agentId: string,- parentId: string | null,- filename: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument | undefined> {- const [result] = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(documents.filename, filename),- parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))- .limit(1);-- if (!result) return undefined;-- return this.toAgentDocument(result.settings, result.doc);- }-- /**- * Lists agent document bindings that share one tree segment.- *- * Use when:- * - VFS callers need to choose the visible entry for a path segment- * - Migration checks need to detect duplicate `parentId + filename` rows- *- * Expects:- * - `parentId` is the canonical document row parent id, not the agent document id- *- * Returns:- * - Matching bindings ordered oldest first so duplicate filename resolution is deterministic- */- async listByParentAndFilename(- agentId: string,- parentId: string | null,- filename: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(documents.filename, filename),- parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))- .limit(options?.limit ?? 9999)- .offset(this.normalizeListOffset(options?.cursor));-- return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));- }-- async findByDocumentId(- agentId: string,- documentId: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument | undefined> {- const [result] = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- eq(agentDocuments.documentId, documentId),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(desc(agentDocuments.updatedAt))- .limit(1);-- if (!result) return undefined;-- return this.toAgentDocument(result.settings, result.doc);- }-- async listByParent(- agentId: string,- parentId: string | null,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),- ...this.buildDeletedAtFilters(options),- ),- )- .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))- .limit(options?.limit ?? 9999)- .offset(this.normalizeListOffset(options?.cursor));-- return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));- }-- async listDeletedByAgent(agentId: string): Promise<AgentDocument[]> {- const results = await this.db- .select({ doc: documents, settings: agentDocuments })- .from(agentDocuments)- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))- .where(- and(- this.agentDocOwnership(),- eq(agentDocuments.agentId, agentId),- this.documentOwnership(),- isNotNull(agentDocuments.deletedAt),- ),- )- .orderBy(desc(agentDocuments.deletedAt), desc(agentDocuments.updatedAt));-- return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));- }-- async listSubtreeByDocumentId(- agentId: string,- rootDocumentId: string,- options?: AgentDocumentQueryOptions,- ): Promise<AgentDocument[]> {- const root = await this.findByDocumentId(agentId, rootDocumentId, options);-- if (!root) return [];-- const subtree = [root];- const pendingParentIds = [root.documentId];-- while (pendingParentIds.length > 0) {- const parentIds = pendingParentIds.splice(0, pendingParentIds.length);- const children = await this.listByParentIds(agentId, parentIds, options);-- for (const child of children) {- subtree.push(child);- pendingParentIds.push(child.documentId);- }- }-- return subtree;- }-- async delete(documentId: string, deleteReason?: string): Promise<void> {- // Soft delete only: mark deleted metadata and stop autoload.- // We intentionally keep both agent_documents row and linked documents row for recovery.- await this.db- .update(agentDocuments)- .set({- policyLoad: PolicyLoad.DISABLED,- deleteReason,- deletedAt: new Date(),- deletedByAgentId: null,- deletedByUserId: this.userId,- })- .where(- and(- eq(agentDocuments.id, documentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- );- }-- async deleteSubtreeByDocumentId(- agentId: string,- rootDocumentId: string,- deleteReason?: string,- ): Promise<void> {- const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId);-- if (subtree.length === 0) return;-- await this.db- .update(agentDocuments)- .set({- policyLoad: PolicyLoad.DISABLED,- deleteReason,- deletedAt: new Date(),- deletedByAgentId: null,- deletedByUserId: this.userId,- })- .where(- and(- this.agentDocOwnership(),- inArray(- agentDocuments.id,- subtree.map((item) => item.id),- ),- isNull(agentDocuments.deletedAt),- ),- );- }-- /**- * Restores a soft-deleted agent document binding to the live tree.- *- * Use when:- * - Moving a deleted document back into active VFS visibility.- * - Preserving the existing document row and agent document id.- *- * Expects:- * - `documentId` may refer to a deleted binding owned by the current user.- * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.- *- * Returns:- * - Nothing; missing bindings are ignored.- *- */- async restore(documentId: string): Promise<void> {- const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });-- if (!existing) return;-- await this.db.transaction(async (trx) => {- await trx- .update(agentDocuments)- .set({- deleteReason: null,- deletedAt: null,- deletedByAgentId: null,- deletedByUserId: null,- policyLoad: PolicyLoad.PROGRESSIVE,- })- .where(and(eq(agentDocuments.id, documentId), this.agentDocOwnership()));- });- }-- async restoreSubtreeByDocumentId(agentId: string, rootDocumentId: string): Promise<void> {- const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId, {- includeDeleted: true,- });-- if (subtree.length === 0) return;-- await this.db- .update(agentDocuments)- .set({- deleteReason: null,- deletedAt: null,- deletedByAgentId: null,- deletedByUserId: null,- policyLoad: PolicyLoad.PROGRESSIVE,- })- .where(- and(- this.agentDocOwnership(),- inArray(- agentDocuments.id,- subtree.map((item) => item.id),- ),- ),- );- }-- /**- * Removes a binding and its document when no other agent still owns that document.- *- * Use when:- * - Permanently deleting an agent trash entry.- * Expects:- * - The binding belongs to the current scope.- * Returns:- * - Backing file IDs for reference-safe cleanup by the storage service after commit.- */- async permanentlyDelete(documentId: string): Promise<string[]> {- const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });-- if (!existing) return [];-- return this.db.transaction(async (trx) => {- await trx- .delete(agentDocuments)- .where(and(eq(agentDocuments.id, documentId), this.agentDocOwnership()));-- return this.deleteUnboundDocuments(trx, [existing.documentId]);- });- }-- /**- * Permanently removes a subtree's bindings and documents without deleting shared documents.- *- * Use when:- * - Erasing a complete document subtree in one transaction.- * Expects:- * - The root belongs to the requested agent and current scope.- * Returns:- * - Backing file IDs requiring reference-safe storage cleanup after commit.- */- async permanentlyDeleteSubtreeByDocumentId(- agentId: string,- rootDocumentId: string,- ): Promise<string[]> {- const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId, {- includeDeleted: true,- });-- if (subtree.length === 0) return [];-- const agentDocumentIds = subtree.map((item) => item.id);- const documentIds = subtree.map((item) => item.documentId);-- return this.db.transaction(async (trx) => {- await trx- .delete(agentDocuments)- .where(and(this.agentDocOwnership(), inArray(agentDocuments.id, agentDocumentIds)));-- return this.deleteUnboundDocuments(trx, documentIds);- });- }-- /** Removes only documents with no surviving agent binding and returns their backing files. */- private async deleteUnboundDocuments(trx: Transaction, documentIds: string[]): Promise<string[]> {- // Serialize deletion with concurrent binding FK inserts before inspecting surviving owners.- await trx- .select({ id: documents.id })- .from(documents)- .where(and(this.documentOwnership(), inArray(documents.id, documentIds)))- .orderBy(documents.id)- .for('update');- // Removing one agent's binding must not cascade through another agent's shared document.- const removed = await trx- .delete(documents)- .where(- and(- this.documentOwnership(),- inArray(documents.id, documentIds),- notExists(- trx- .select({ id: agentDocuments.id })- .from(agentDocuments)- .where(eq(agentDocuments.documentId, documents.id)),- ),- ),- )- .returning({ fileId: documents.fileId });-- return [...new Set(removed.flatMap(({ fileId }) => (fileId ? [fileId] : [])))];- }-- async deleteByAgent(agentId: string, deleteReason?: string): Promise<void> {- await this.db- .update(agentDocuments)- .set({- policyLoad: PolicyLoad.DISABLED,- deleteReason,- deletedAt: new Date(),- // NOTICE: mark for telling everyone that this should not ever marked as user id, no matter what circumstances- deletedByAgentId: agentId,- deletedByUserId: null,- })- .where(- and(- eq(agentDocuments.agentId, agentId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- );- }-- async deleteByTemplate(- agentId: string,- templateId: string,- deleteReason?: string,- ): Promise<void> {- await this.db- .update(agentDocuments)- .set({- policyLoad: PolicyLoad.DISABLED,- deleteReason,- deletedAt: new Date(),- deletedByAgentId: null,- deletedByUserId: this.userId,- })- .where(- and(- eq(agentDocuments.agentId, agentId),- eq(agentDocuments.templateId, templateId),- this.agentDocOwnership(),- isNull(agentDocuments.deletedAt),- ),- );- }-- async getDocumentsByPosition(- agentId: string,- ): Promise<Map<DocumentLoadPosition, AgentDocumentWithRules[]>> {- const docs = await this.getLoadableDocuments(agentId);- const grouped = new Map<DocumentLoadPosition, AgentDocumentWithRules[]>();-- for (const doc of docs) {- const position = resolveDocumentLoadPosition(doc);- const existing = grouped.get(position) || [];-- existing.push(doc);- grouped.set(position, sortByLoadRulePriority(existing));- }-- return grouped;- }-- async getLoadableDocuments(- agentId: string,- _context?: {- currentTime?: Date;- userMessage?: string;- },- ): Promise<AgentDocumentWithRules[]> {- // Autoload gate: only documents explicitly marked as always-loadable are injected.- // Agent access bits are enforced by caller/tool layer for interactive list/read/write actions.- const docs = await this.findByAgent(agentId);- return docs.filter((doc) => isLoadableDocument(doc));- }-- async getInjectableDocuments(- agentId: string,- context?: {- currentTime?: Date;- userMessage?: string;- },- ): Promise<AgentDocumentWithRules[]> {- return this.getLoadableDocuments(agentId, context);- }-- async getAgentContext(agentId: string): Promise<string> {- const docs = await this.getLoadableDocuments(agentId);-- if (docs.length === 0) {- return '';- }-- const contextParts: string[] = [];-- for (const doc of docs) {- if (doc.content) {- contextParts.push(`--- ${doc.filename} ---`);- contextParts.push(doc.content);- contextParts.push('');- }- }-- return contextParts.join('\n').trim();- }-}diff --git a/packages/database/src/models/agentDocuments/agentDocument/context.ts b/packages/database/src/models/agentDocuments/agentDocument/context.tsnew file mode 100644index 00000000000..9e74c9f802c--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/context.ts@@ -0,0 +1,85 @@+import { type DocumentAccessScope, stripAgentShareDocumentProvenance } from '@lobechat/types';+import { and, eq, exists } from 'drizzle-orm';++import { agentDocuments, documents } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { documentMatchesAccessScope } from '../../../utils/documentVisibility';+import { buildWorkspaceWhere } from '../../../utils/workspace';++/**+ * The scope every `AgentDocumentModel` helper runs in, passed as the first+ * argument instead of `this` so the helper modules never import the class.+ */+export interface AgentDocumentContext {+ db: LobeChatDatabase;+ documentAccessScope: DocumentAccessScope;+ userId: string;+ workspaceId?: string;+}++/**+ * Workspace-aware ownership predicate for the `agent_documents` binding table.+ * Personal mode → `user_id = ? AND workspace_id IS NULL`; workspace mode → `workspace_id = ?`.+ */+export function agentDocOwnership(ctx: AgentDocumentContext) {+ // NOTICE:+ // For now, we expect a caller authorized to access an agent to access all resources+ // bound under its agent documents, including backing files, without a separate+ // Resources publish step. Tool reads and UI previews need the same access contract.+ // Agent documents and backing files use separate visibility checks; uploads without+ // the agent-document source can expose a document in tools/the tree while its+ // original-file preview returns 404. Dedicated uploads now default to public.+ // Context: AgentDocumentsService.importFile and FileDocumentPreview; this predicate+ // scopes bindings but does not itself authorize access to the agent.+ // Replace this interim assumption when a consistent workspace authorization model+ // covers agent documents, backing files, tool execution, and resource publishing.++ // REVIEW: A private upload must not silently become readable merely because someone+ // can access its agent. Restricting preview or even one read tool is insufficient:+ // if an agent can read private content through another path or its existing context,+ // a user can prompt it to copy or summarize that content into a shared knowledge base+ // and leak it. The current assumption does not provide per-resource confidentiality.++ // TODO: Revisit this coarse model before extending workspace permission controls.+ // Define how sharing is authorized and how reads, execution context, and writes to+ // broader audiences are constrained; enforce the resulting rules across all paths.+ return and(+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, agentDocuments),+ exists(+ ctx.db+ .select({ id: documents.id })+ .from(documents)+ .where(+ and(+ eq(documents.id, agentDocuments.documentId),+ documentMatchesAccessScope(documents.metadata, ctx.documentAccessScope),+ ),+ ),+ ),+ );+}++/** Workspace-aware ownership predicate for the backing `documents` rows. */+export function documentOwnership(ctx: AgentDocumentContext) {+ return and(+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, documents),+ documentMatchesAccessScope(documents.metadata, ctx.documentAccessScope),+ );+}++export function scopeMetadata(+ ctx: AgentDocumentContext,+ metadata?: Record<string, any>,+): Record<string, any> | undefined {+ const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);+ if (ctx.documentAccessScope.type !== 'agentShare') return sanitizedMetadata;++ return {+ ...sanitizedMetadata,+ agentShare: {+ shareId: ctx.documentAccessScope.shareId,+ topicId: ctx.documentAccessScope.topicId,+ visitorUserId: ctx.documentAccessScope.visitorUserId,+ },+ };+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/creation.ts b/packages/database/src/models/agentDocuments/agentDocument/creation.tsnew file mode 100644index 00000000000..e3aad567bb6--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/creation.ts@@ -0,0 +1,327 @@+import { AGENT_DOCUMENT_FILE_TYPE, AGENT_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';+import { and, eq, isNull } from 'drizzle-orm';++import {+ agentDocuments,+ type DocumentItem,+ documents,+ type NewAgentDocument,+ type NewDocument,+} from '../../../schemas';+import type { Transaction } from '../../../type';+import { normalizePolicy } from '../policy';+import {+ AgentAccess,+ type AgentDocument,+ DocumentLoadFormat,+ DocumentLoadPosition,+ DocumentLoadRule,+ PolicyLoad,+} from '../types';+import {+ agentDocOwnership,+ type AgentDocumentContext,+ documentOwnership,+ scopeMetadata,+} from './context';+import type { AgentDocumentCreateParams, ConvertAgentDocumentToSkillIndexParams } from './types';+import { getDocumentStats, getMetadataDescription, toAgentDocument } from './utils';++/**+ * Associates an existing document row with an agent document binding.+ *+ * Use when:+ * - A document already exists and should become visible to an agent.+ * - Managed mount providers need to bind pre-created document tree nodes.+ *+ * Expects:+ * - `documentId` belongs to the current user.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - The inserted or existing agent document binding id.+ * - An empty id only when the source document is missing.+ *+ */+export async function associate(+ ctx: AgentDocumentContext,+ params: {+ agentId: string;+ documentId: string;+ policyLoad?: PolicyLoad;+ },+): Promise<{ id: string }> {+ const { agentId, documentId, policyLoad } = params;++ // Single-table write: the document row is only read, and the binding insert+ // resolves conflicts itself, so no transaction is needed here.+ const [doc] = await ctx.db+ .select()+ .from(documents)+ .where(and(eq(documents.id, documentId), documentOwnership(ctx)))+ .limit(1);++ if (!doc) return { id: '' };++ const [result] = await ctx.db+ .insert(agentDocuments)+ .values({+ accessPublic: 0,+ accessSelf:+ AgentAccess.EXECUTE |+ AgentAccess.LIST |+ AgentAccess.READ |+ AgentAccess.WRITE |+ AgentAccess.DELETE,+ accessShared: 0,+ agentId,+ documentId,+ policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,+ policyLoadFormat: DocumentLoadFormat.RAW,+ policyLoadPosition: DocumentLoadPosition.BEFORE_FIRST_USER,+ policyLoadRule: DocumentLoadRule.ALWAYS,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? null,+ })+ .onConflictDoNothing()+ .returning({ id: agentDocuments.id });++ if (result) return result;++ // A concurrent caller (or an earlier run) may already own this unique+ // agent/document binding. The conflict loser must resolve that row instead+ // of leaking `undefined` to callers that need the binding id.+ const [existing] = await ctx.db+ .select({ id: agentDocuments.id })+ .from(agentDocuments)+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(agentDocuments.documentId, documentId),+ ),+ )+ .limit(1);++ return { id: existing?.id ?? '' };+}++/**+ * Inserts the backing `documents` row for a new agent document.+ *+ * Use when:+ * - `AgentDocumentRepository` creates an agent document and needs the document+ * row before it can insert the binding in the same transaction.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `documents`.+ * - `filename` is a single VFS segment supplied by the caller.+ *+ * Returns:+ * - The inserted document row.+ */+export async function insertBackingDocument(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentCreateParams,+): Promise<DocumentItem> {+ const {+ createdAt,+ editorData,+ fileId,+ fileType = AGENT_DOCUMENT_FILE_TYPE,+ metadata,+ parentId,+ source,+ sourceType = AGENT_DOCUMENT_SOURCE_TYPE,+ title: providedTitle,+ updatedAt,+ } = params ?? {};++ const title = providedTitle?.trim() || filename.replace(/\.[^.]+$/, '');+ const stats = getDocumentStats(content);+ const scopedMetadata = scopeMetadata(ctx, metadata);++ const documentPayload: NewDocument = {+ content,+ createdAt,+ description: getMetadataDescription(scopedMetadata),+ // NOTICE:+ // Agent documents often carry Markdown `content`, but editor history and restore UI+ // depend on this serialized editor snapshot. Service callers that derive content from+ // Markdown should pass a matching `editorData` snapshot instead of relying on content alone.+ // Root cause: `document_histories` snapshots `editor_data`, so missing editor data makes+ // pre-mutation history capture impossible.+ // Removal condition: only if document history supports Markdown-content snapshots.+ editorData,+ fileType,+ filename,+ parentId,+ metadata: scopedMetadata,+ ...(fileId ? { fileId } : {}),+ source: source ?? `agent-document://${agentId}/${encodeURIComponent(filename)}`,+ sourceType,+ title,+ totalCharCount: stats.totalCharCount,+ totalLineCount: stats.totalLineCount,+ updatedAt: updatedAt ?? createdAt,+ userId: ctx.userId,+ // Keep newly created agent resources shared within their existing workspace scope.+ visibility: 'public',+ workspaceId: ctx.workspaceId ?? null,+ };++ const [insertedDocument] = await trx.insert(documents).values(documentPayload).returning();++ return insertedDocument!;+}++/**+ * Inserts the `agent_documents` binding for a freshly inserted backing document.+ *+ * Use when:+ * - `AgentDocumentRepository` links the document row from+ * {@link insertBackingDocument} to an agent in the same transaction.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `agent_documents`.+ * - `document` is the backing row returned by {@link insertBackingDocument}.+ *+ * Returns:+ * - The created agent document with joined document content and metadata.+ */+export async function insertBinding(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentId: string,+ document: DocumentItem,+ params?: AgentDocumentCreateParams,+): Promise<AgentDocument> {+ const { createdAt, loadPosition, loadRules, policy, policyLoad, templateId, updatedAt } =+ params ?? {};+ const normalizedPolicy = normalizePolicy(loadPosition, loadRules, policy);++ const newDoc: NewAgentDocument = {+ accessPublic: 0,+ accessSelf:+ AgentAccess.EXECUTE |+ AgentAccess.LIST |+ AgentAccess.READ |+ AgentAccess.WRITE |+ AgentAccess.DELETE,+ accessShared: 0,+ agentId,+ createdAt,+ policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,+ deleteReason: null,+ deletedAt: null,+ deletedByAgentId: null,+ deletedByUserId: null,+ documentId: document.id,+ policy: normalizedPolicy,+ policyLoadFormat: normalizedPolicy.context?.policyLoadFormat || DocumentLoadFormat.RAW,+ policyLoadPosition:+ normalizedPolicy.context?.position || DocumentLoadPosition.BEFORE_FIRST_USER,+ policyLoadRule: normalizedPolicy.context?.rule || DocumentLoadRule.ALWAYS,+ templateId,+ updatedAt: updatedAt ?? createdAt,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? null,+ };++ const [settings] = await trx.insert(agentDocuments).values(newDoc).returning();++ return toAgentDocument(settings!, document);+}++/**+ * Reads one live binding joined to its document through a caller-owned transaction.+ *+ * Returns:+ * - The live agent document, or `undefined` when it is missing, deleted, or out of scope.+ */+export async function findLiveWithTx(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentDocumentId: string,+): Promise<AgentDocument | undefined> {+ const [result] = await trx+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ eq(agentDocuments.id, agentDocumentId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .limit(1);++ return result ? toAgentDocument(result.settings, result.doc) : undefined;+}++/**+ * Rewrites a backing document row into a managed skill index document.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `documents`.+ * - `documentId` is the backing row of a live binding resolved in the same transaction.+ */+export async function updateBackingDocumentAsSkillIndex(+ ctx: AgentDocumentContext,+ trx: Transaction,+ documentId: string,+ params: ConvertAgentDocumentToSkillIndexParams,+): Promise<void> {+ const stats = getDocumentStats(params.content);+ const scopedMetadata = scopeMetadata(ctx, params.metadata);++ await trx+ .update(documents)+ .set({+ content: params.content,+ description: getMetadataDescription(scopedMetadata),+ ...(params.editorData !== undefined && { editorData: params.editorData }),+ filename: params.filename,+ fileType: 'skills/index',+ metadata: scopedMetadata,+ parentId: params.parentId,+ source: params.source,+ sourceType: params.sourceType,+ title: params.title,+ totalCharCount: stats.totalCharCount,+ totalLineCount: stats.totalLineCount,+ })+ .where(and(eq(documents.id, documentId), documentOwnership(ctx)));+}++/**+ * Marks a live binding as a managed skill index: stop autoload and tag the template.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `agent_documents`.+ */+export async function markBindingAsSkillIndex(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentDocumentId: string,+): Promise<void> {+ await trx+ .update(agentDocuments)+ .set({+ policyLoad: PolicyLoad.DISABLED,+ templateId: 'agent-skill',+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(agentDocuments.id, agentDocumentId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ );+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/edits.ts b/packages/database/src/models/agentDocuments/agentDocument/edits.tsnew file mode 100644index 00000000000..f9d1315b3a7--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/edits.ts@@ -0,0 +1,383 @@+import { and, eq, isNull, sql } from 'drizzle-orm';++import {+ agentDocuments,+ documents,+ type NewAgentDocument,+ type NewDocument,+} from '../../../schemas';+import type { Transaction } from '../../../type';+import { buildDocumentFilename } from '../filename';+import { composeToolPolicyUpdate, normalizePolicy } from '../policy';+import {+ type AgentDocument,+ DocumentLoadFormat,+ DocumentLoadPosition,+ DocumentLoadRule,+ type ToolUpdateLoadRule,+} from '../types';+import {+ agentDocOwnership,+ type AgentDocumentContext,+ documentOwnership,+ scopeMetadata,+} from './context';+import { findById } from './queries';+import type { AgentDocumentUpdateParams } from './types';+import { getDocumentStats, getMetadataDescription } from './utils';++/**+ * Writes a repaired editor snapshot only if the backing document still holds+ * the version the repair was computed from.+ *+ * Use when:+ * - A read path rebuilds `editorData` from Markdown and must persist it so the+ * node ids it exposes stay addressable, without clobbering a concurrent save.+ *+ * Expects:+ * - `expected` is the `content` / `editorData` pair the caller read.+ *+ * Returns:+ * - `true` when the snapshot was written; `false` when the document changed+ * (or is gone) since it was read, in which case nothing is written.+ */+export async function updateEditorSnapshotIfUnchanged(+ ctx: AgentDocumentContext,+ documentId: string,+ expected: { content: string; editorData: Record<string, any> | null },+ next: { content: string; editorData: Record<string, any> },+): Promise<boolean> {+ const existing = await findById(ctx, documentId);+ if (!existing) return false;++ const stats = getDocumentStats(next.content);+ const expectedEditorData =+ expected.editorData === null || expected.editorData === undefined+ ? null+ : JSON.stringify(expected.editorData);++ const updated = await ctx.db+ .update(documents)+ .set({+ content: next.content,+ editorData: next.editorData,+ totalCharCount: stats.totalCharCount,+ totalLineCount: stats.totalLineCount,+ })+ .where(+ and(+ eq(documents.id, existing.documentId),+ documentOwnership(ctx),+ sql`coalesce(${documents.content}, '') = ${expected.content}`,+ sql`${documents.editorData} IS NOT DISTINCT FROM ${expectedEditorData}::jsonb`,+ ),+ )+ .returning({ id: documents.id });++ return updated.length > 0;+}++/**+ * Builds the `agent_documents` settings patch for an update, merging the+ * requested load policy into the binding's current policy.+ *+ * Use when:+ * - `AgentDocumentRepository.update` prepares the binding write for its transaction.+ */+export function buildBindingSettingsUpdate(+ existing: AgentDocument,+ params?: AgentDocumentUpdateParams,+): Partial<NewAgentDocument> {+ const { loadPosition, loadRules, policy, policyLoad } = params ?? {};++ const existingPolicy = existing.policy || {};+ const existingContext = existingPolicy.context || {};++ const mergedPolicy = normalizePolicy(+ loadPosition ||+ (existingContext.position as DocumentLoadPosition | undefined) ||+ DocumentLoadPosition.BEFORE_FIRST_USER,+ {+ keywordMatchMode: loadRules?.keywordMatchMode ?? existingContext.keywordMatchMode,+ keywords: loadRules?.keywords ?? existingContext.keywords,+ maxTokens: loadRules?.maxTokens ?? existingContext.maxTokens,+ priority: loadRules?.priority ?? existingContext.priority,+ regexp: loadRules?.regexp ?? existingContext.regexp,+ rule: (loadRules?.rule ??+ existingContext.rule ??+ DocumentLoadRule.ALWAYS) as DocumentLoadRule,+ timeRange: loadRules?.timeRange ?? existingContext.timeRange,+ },+ policy ? { ...existingPolicy, ...policy } : existingPolicy,+ );++ return {+ policy: mergedPolicy,+ policyLoadFormat: mergedPolicy.context?.policyLoadFormat || DocumentLoadFormat.RAW,+ policyLoadPosition: mergedPolicy.context?.position || DocumentLoadPosition.BEFORE_FIRST_USER,+ policyLoadRule: mergedPolicy.context?.rule || DocumentLoadRule.ALWAYS,+ ...(policyLoad !== undefined && { policyLoad }),+ };+}++/**+ * Builds the backing `documents` patch for an update.+ *+ * Returns:+ * - `undefined` when the update touches no document field, so the caller skips the write.+ */+export function buildBackingDocumentUpdate(+ ctx: AgentDocumentContext,+ params?: AgentDocumentUpdateParams,+): Partial<NewDocument> | undefined {+ const { content, editorData, fileType, metadata } = params ?? {};++ if (+ content === undefined &&+ editorData === undefined &&+ fileType === undefined &&+ metadata === undefined+ ) {+ return undefined;+ }++ const documentUpdate: Partial<NewDocument> = {};++ if (content !== undefined) {+ // NOTICE:+ // Updating Markdown content alone is valid for raw consumers, but it does not refresh+ // the editor snapshot used by document history. Callers that replace full Markdown+ // should also provide `editorData` from the same content when they expect history or+ // editor restore support to keep working.+ // Root cause: `DocumentService.trySaveCurrentDocumentHistory` validates editor data+ // before creating history rows.+ // Removal condition: only if document history supports Markdown-content snapshots.+ const stats = getDocumentStats(content);+ documentUpdate.content = content;+ documentUpdate.totalCharCount = stats.totalCharCount;+ documentUpdate.totalLineCount = stats.totalLineCount;+ }++ if (editorData !== undefined) {+ documentUpdate.editorData = editorData;+ }++ if (fileType !== undefined) {+ documentUpdate.fileType = fileType;+ }++ if (metadata !== undefined) {+ const scopedMetadata = scopeMetadata(ctx, metadata);+ documentUpdate.metadata = scopedMetadata;+ documentUpdate.description = getMetadataDescription(scopedMetadata);+ }++ return documentUpdate;+}++/**+ * Writes a prepared patch to a backing `documents` row.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `documents`.+ */+export async function updateBackingDocument(+ ctx: AgentDocumentContext,+ trx: Transaction,+ documentId: string,+ documentUpdate: Partial<NewDocument>,+): Promise<void> {+ await trx+ .update(documents)+ .set(documentUpdate)+ .where(and(eq(documents.id, documentId), documentOwnership(ctx)));+}++/**+ * Writes a prepared settings patch to one `agent_documents` binding.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `agent_documents`.+ */+export async function updateBindingSettings(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentDocumentId: string,+ settingsUpdate: Partial<NewAgentDocument>,+): Promise<void> {+ await trx+ .update(agentDocuments)+ .set(settingsUpdate)+ .where(and(eq(agentDocuments.id, agentDocumentId), agentDocOwnership(ctx)));+}++/**+ * Updates backing document identity fields without changing ids or load policy.+ *+ * Use when:+ * - Managed skill services need to rename or reparent a document row.+ * - Callers must preserve agent document id and backing document id.+ *+ * Expects:+ * - `agentDocumentId` is the agent document binding id, not the backing document row id.+ * - Omitted fields are left untouched.+ *+ * Returns:+ * - The same agent document binding after identity fields are updated.+ *+ */+export async function updateDocumentIdentity(+ ctx: AgentDocumentContext,+ agentDocumentId: string,+ params: {+ filename?: string;+ metadata?: Record<string, unknown>;+ parentId?: string | null;+ title?: string;+ },+): Promise<AgentDocument | undefined> {+ const existing = await findById(ctx, agentDocumentId);+ if (!existing) return undefined;++ if (+ params.filename === undefined &&+ params.metadata === undefined &&+ params.parentId === undefined &&+ params.title === undefined+ ) {+ return existing;+ }++ await ctx.db+ .update(documents)+ .set({+ ...(params.filename !== undefined && { filename: params.filename }),+ ...(params.metadata !== undefined && {+ description: getMetadataDescription(scopeMetadata(ctx, params.metadata)),+ metadata: scopeMetadata(ctx, params.metadata),+ }),+ ...(params.parentId !== undefined && { parentId: params.parentId }),+ ...(params.title !== undefined && { title: params.title }),+ })+ .where(and(eq(documents.id, existing.documentId), documentOwnership(ctx)));++ return findById(ctx, agentDocumentId);+}++/**+ * Renames an agent document by updating the backing document filename and title.+ *+ * Use when:+ * - A caller wants title-style rename behavior.+ * - The document should keep its binding, content, policy, and document identity.+ *+ * Expects:+ * - `newTitle` is a human-readable title that can be normalized into a filename.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - The renamed agent document, or `undefined` when the binding is not visible.+ *+ */+export async function rename(+ ctx: AgentDocumentContext,+ documentId: string,+ newTitle: string,+ options?: { filename?: string },+): Promise<AgentDocument | undefined> {+ const existing = await findById(ctx, documentId);+ if (!existing) return undefined;++ const title = newTitle.trim();+ if (!title) return existing;++ const filename = options?.filename?.trim() || buildDocumentFilename(title);+ const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;++ await ctx.db.transaction(async (trx) => {+ await trx+ .update(documents)+ .set({+ filename,+ source,+ title,+ })+ .where(and(eq(documents.id, existing.documentId), documentOwnership(ctx)));+ });++ return findById(ctx, documentId);+}++/**+ * Moves or renames an agent document without changing its binding or document identity.+ *+ * Use when:+ * - VFS `rename(from, to)` needs filesystem-style metadata mutation+ * - Callers must preserve document id, agent document id, policy, history, and load settings+ *+ * Expects:+ * - `filename` is already validated as a single VFS path segment+ * - `parentId` points to a document row owned by the same user, or `null` for root+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately+ * - `title` defaults to `filename` (path-style rename); id-based moves pass the current title+ * so relocating a document never rewrites what the user sees+ *+ * Returns:+ * - The same agent document binding after the backing document row is moved+ *+ */+export async function movePath(+ ctx: AgentDocumentContext,+ documentId: string,+ params: { filename: string; parentId: string | null; title?: string },+): Promise<AgentDocument | undefined> {+ const existing = await findById(ctx, documentId);+ if (!existing) return undefined;++ const filename = params.filename.trim();+ if (!filename) return existing;++ const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;++ await ctx.db.transaction(async (trx) => {+ await trx+ .update(documents)+ .set({+ filename,+ parentId: params.parentId,+ source,+ title: params.title ?? filename,+ })+ .where(and(eq(documents.id, existing.documentId), documentOwnership(ctx)));+ });++ return findById(ctx, documentId);+}++export async function updateToolLoadRule(+ ctx: AgentDocumentContext,+ documentId: string,+ rule: ToolUpdateLoadRule,+): Promise<AgentDocument | undefined> {+ const existing = await findById(ctx, documentId);+ if (!existing) return undefined;+ const composedPolicy = composeToolPolicyUpdate(existing.policy, rule, existing.policyLoad);++ await ctx.db+ .update(agentDocuments)+ .set({+ policyLoad: composedPolicy.policyLoad,+ policy: composedPolicy.policy,+ policyLoadFormat: composedPolicy.policyLoadFormat,+ policyLoadRule: composedPolicy.policyLoadRule,+ })+ .where(+ and(+ eq(agentDocuments.id, documentId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ );++ return findById(ctx, documentId);+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/index.test.ts b/packages/database/src/models/agentDocuments/agentDocument/index.test.tsnew file mode 100644index 00000000000..6a22d666004--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/index.test.ts@@ -0,0 +1,75 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import * as agentDocumentModule from '.';+import { AgentDocumentModel } from '.';++/**+ * Pins the public surface of `AgentDocumentModel` so a split into helper+ * modules keeps every caller-visible name and keeps instance methods on the+ * prototype.+ */+describe('AgentDocumentModel public surface', () => {+ it('keeps the module exports', () => {+ expect(Object.keys(agentDocumentModule).sort()).toEqual([+ 'AgentAccess',+ 'AgentDocumentModel',+ 'AutoLoadAccess',+ 'DocumentLoadFormat',+ 'DocumentLoadPosition',+ 'DocumentLoadRule',+ 'PolicyLoad',+ ]);+ });++ it('keeps every public instance method on the prototype', () => {+ const proto = AgentDocumentModel.prototype as unknown as Record<string, unknown>;+ const missing = [+ 'associate',+ 'convertAgentDocumentToSkillIndex',+ 'convertAgentDocumentToSkillIndexWithTx',+ 'copy',+ 'countChildrenByParentIds',+ 'create',+ 'createWithTx',+ 'delete',+ 'deleteByAgent',+ 'deleteByTemplate',+ 'deleteSubtreeByDocumentId',+ 'findByAgent',+ 'findByDocumentId',+ 'findByDocumentIds',+ 'findByFilename',+ 'findById',+ 'findByIdWithOptions',+ 'findByParentAndFilename',+ 'findByTemplate',+ 'findContextByAgent',+ 'findSkillDocsByAgent',+ 'getAgentContext',+ 'getDocumentsByPosition',+ 'getInjectableDocuments',+ 'getLoadableDocuments',+ 'hasByAgent',+ 'listByAgent',+ 'listByDocumentIds',+ 'listByParent',+ 'listByParentAndFilename',+ 'listDeletedByAgent',+ 'listSubtreeByDocumentId',+ 'movePath',+ 'permanentlyDelete',+ 'permanentlyDeleteSubtreeByDocumentId',+ 'rename',+ 'restore',+ 'restoreSubtreeByDocumentId',+ 'update',+ 'updateDocumentIdentity',+ 'updateEditorSnapshotIfUnchanged',+ 'updateToolLoadRule',+ 'upsert',+ ].filter((name) => !Object.hasOwn(proto, name) || typeof proto[name] !== 'function');++ expect(missing).toEqual([]);+ });+});diff --git a/packages/database/src/models/agentDocuments/agentDocument/index.ts b/packages/database/src/models/agentDocuments/agentDocument/index.tsnew file mode 100644index 00000000000..76f22451654--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/index.ts@@ -0,0 +1,558 @@+import type { DocumentAccessScope } from '@lobechat/types';+import { ordinaryDocumentAccessScope } from '@lobechat/types';++import { AgentDocumentRepository } from '../../../repositories/agentDocument';+import type { LobeChatDatabase, Transaction } from '../../../type';+import type {+ AgentDocument,+ AgentDocumentContextRow,+ AgentDocumentListItem,+ AgentDocumentListSourceType,+ AgentDocumentPolicy,+ AgentDocumentWithRules,+ DocumentLoadPosition,+ DocumentLoadRules,+ PolicyLoad,+ ToolUpdateLoadRule,+} from '../types';+import type { AgentDocumentContext } from './context';+import * as creation from './creation';+import * as edits from './edits';+import * as lifecycle from './lifecycle';+import * as loading from './loading';+import * as queries from './queries';+import * as tree from './tree';+import type {+ AgentDocumentCreateParams,+ AgentDocumentQueryOptions,+ AgentDocumentUpdateParams,+ ConvertAgentDocumentToSkillIndexParams,+} from './types';++export * from '../types';++export class AgentDocumentModel {+ /** The scope handed to the helper modules in this directory. */+ private readonly ctx: AgentDocumentContext;+ /**+ * Owns the flows that write both the `documents` row and its `agent_documents`+ * binding; this model forwards to it instead of opening those transactions.+ */+ private readonly repository: AgentDocumentRepository;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,+ ) {+ this.ctx = { db, documentAccessScope, userId, workspaceId };+ this.repository = new AgentDocumentRepository(db, userId, workspaceId, documentAccessScope);+ }++ /**+ * Counts live children per parent `documentId`, for listings that show which+ * entries (folders or documents) have something nested under them. Omit+ * `parentIds` to count every parent of the agent in one grouped query.+ * Parents without children are absent from the map.+ */+ async countChildrenByParentIds(+ agentId: string,+ parentIds?: string[],+ ): Promise<Map<string, number>> {+ return tree.countChildrenByParentIds(this.ctx, agentId, parentIds);+ }++ /**+ * Associates an existing document row with an agent document binding.+ *+ * Use when:+ * - A document already exists and should become visible to an agent.+ * - Managed mount providers need to bind pre-created document tree nodes.+ *+ * Expects:+ * - `documentId` belongs to the current user.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - The inserted or existing agent document binding id.+ * - An empty id only when the source document is missing.+ *+ */+ async associate(params: {+ agentId: string;+ documentId: string;+ policyLoad?: PolicyLoad;+ }): Promise<{ id: string }> {+ return creation.associate(this.ctx, params);+ }++ /**+ * Creates a document row and links it to an agent in one transaction+ * (owned by {@link AgentDocumentRepository.create}).+ *+ * Use when:+ * - Creating ordinary agent-visible VFS files or folders.+ * - Creating model-owned documents that still need agent document policy metadata.+ *+ * Expects:+ * - `filename` is a single VFS segment supplied by the caller.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - The created agent document with joined document content and metadata.+ *+ */+ async create(+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentCreateParams,+ ): Promise<AgentDocument> {+ return this.repository.create(agentId, filename, content, params);+ }++ /**+ * Creates a document row and links it to an agent inside a caller-owned transaction.+ *+ * Use when:+ * - A higher-level aggregate must create multiple agent documents atomically.+ * - Callers already run `db.transaction` and need to avoid nested transactions.+ *+ * Expects:+ * - `trx` is the active transaction for every write in the aggregate.+ * - `filename` is a single VFS segment supplied by the caller.+ *+ * Returns:+ * - The created agent document with joined document content and metadata.+ */+ async createWithTx(+ trx: Transaction,+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentCreateParams,+ ): Promise<AgentDocument> {+ return this.repository.createWithTx(trx, agentId, filename, content, params);+ }++ /**+ * Converts an existing ordinary agent document binding into a managed skill index.+ *+ * Use when:+ * - Agent Signal promoted an already-created agent document into skill management.+ * - The caller must preserve both the agent document id and backing document id.+ *+ * Expects:+ * - `agentDocumentId` is a live binding owned by the current user.+ * - `parentId` points to the managed skill bundle document row.+ *+ * Returns:+ * - The same agent document binding after document identity and load metadata are updated.+ *+ */+ async convertAgentDocumentToSkillIndex(+ params: ConvertAgentDocumentToSkillIndexParams,+ ): Promise<AgentDocument | undefined> {+ return this.repository.convertToSkillIndex(params);+ }++ /**+ * Converts a live agent document binding into a managed skill index inside a transaction.+ *+ * Use when:+ * - A higher-level skill aggregate also creates the owning bundle in the same transaction.+ * - The caller must preserve both `agent_documents.id` and `documents.id`.+ *+ * Expects:+ * - `trx` is the active transaction for the whole skill creation operation.+ * - `parentId` points to the managed skill bundle document row inside the same transaction.+ *+ * Returns:+ * - The same agent document binding after document identity and load metadata are updated.+ */+ async convertAgentDocumentToSkillIndexWithTx(+ trx: Transaction,+ params: ConvertAgentDocumentToSkillIndexParams,+ ): Promise<AgentDocument | undefined> {+ return this.repository.convertToSkillIndexWithTx(trx, params);+ }++ /**+ * Writes a repaired editor snapshot only if the backing document still holds+ * the version the repair was computed from.+ *+ * Use when:+ * - A read path rebuilds `editorData` from Markdown and must persist it so the+ * node ids it exposes stay addressable, without clobbering a concurrent save.+ *+ * Expects:+ * - `expected` is the `content` / `editorData` pair the caller read.+ *+ * Returns:+ * - `true` when the snapshot was written; `false` when the document changed+ * (or is gone) since it was read, in which case nothing is written.+ */+ async updateEditorSnapshotIfUnchanged(+ documentId: string,+ expected: { content: string; editorData: Record<string, any> | null },+ next: { content: string; editorData: Record<string, any> },+ ): Promise<boolean> {+ return edits.updateEditorSnapshotIfUnchanged(this.ctx, documentId, expected, next);+ }++ async update(documentId: string, params?: AgentDocumentUpdateParams): Promise<void> {+ return this.repository.update(documentId, params);+ }++ /**+ * Updates backing document identity fields without changing ids or load policy.+ *+ * Use when:+ * - Managed skill services need to rename or reparent a document row.+ * - Callers must preserve agent document id and backing document id.+ *+ * Expects:+ * - `agentDocumentId` is the agent document binding id, not the backing document row id.+ * - Omitted fields are left untouched.+ *+ * Returns:+ * - The same agent document binding after identity fields are updated.+ *+ */+ async updateDocumentIdentity(+ agentDocumentId: string,+ params: {+ filename?: string;+ metadata?: Record<string, unknown>;+ parentId?: string | null;+ title?: string;+ },+ ): Promise<AgentDocument | undefined> {+ return edits.updateDocumentIdentity(this.ctx, agentDocumentId, params);+ }++ /**+ * Renames an agent document by updating the backing document filename and title.+ *+ * Use when:+ * - A caller wants title-style rename behavior.+ * - The document should keep its binding, content, policy, and document identity.+ *+ * Expects:+ * - `newTitle` is a human-readable title that can be normalized into a filename.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - The renamed agent document, or `undefined` when the binding is not visible.+ *+ */+ async rename(+ documentId: string,+ newTitle: string,+ options?: { filename?: string },+ ): Promise<AgentDocument | undefined> {+ return edits.rename(this.ctx, documentId, newTitle, options);+ }++ /**+ * Moves or renames an agent document without changing its binding or document identity.+ *+ * Use when:+ * - VFS `rename(from, to)` needs filesystem-style metadata mutation+ * - Callers must preserve document id, agent document id, policy, history, and load settings+ *+ * Expects:+ * - `filename` is already validated as a single VFS path segment+ * - `parentId` points to a document row owned by the same user, or `null` for root+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately+ * - `title` defaults to `filename` (path-style rename); id-based moves pass the current title+ * so relocating a document never rewrites what the user sees+ *+ * Returns:+ * - The same agent document binding after the backing document row is moved+ *+ */+ async movePath(+ documentId: string,+ params: { filename: string; parentId: string | null; title?: string },+ ): Promise<AgentDocument | undefined> {+ return edits.movePath(this.ctx, documentId, params);+ }++ async copy(documentId: string, newTitle?: string): Promise<AgentDocument | undefined> {+ return this.repository.copy(documentId, newTitle);+ }++ async updateToolLoadRule(+ documentId: string,+ rule: ToolUpdateLoadRule,+ ): Promise<AgentDocument | undefined> {+ return edits.updateToolLoadRule(this.ctx, documentId, rule);+ }++ async findById(+ documentId: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument | undefined> {+ return queries.findById(this.ctx, documentId, options);+ }++ async findByIdWithOptions(+ documentId: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument | undefined> {+ return queries.findByIdWithOptions(this.ctx, documentId, options);+ }++ /**+ * Updates an existing document by filename or creates a new one when missing.+ *+ * Use when:+ * - Callers want idempotent writes keyed by agent and filename.+ * - Existing document policy and metadata should be merged on update.+ *+ * Expects:+ * - `filename` addresses the current agent's ordinary filename lookup.+ * - Duplicate filenames are allowed; the first matching filename is the oldest live binding.+ *+ * Returns:+ * - The updated or created agent document.+ *+ */+ async upsert(+ agentId: string,+ filename: string,+ content: string,+ params?: {+ createdAt?: Date;+ editorData?: Record<string, any>;+ loadPosition?: DocumentLoadPosition;+ loadRules?: DocumentLoadRules;+ metadata?: Record<string, any>;+ policy?: AgentDocumentPolicy;+ policyLoad?: PolicyLoad;+ templateId?: string;+ updatedAt?: Date;+ },+ ): Promise<AgentDocument> {+ return this.repository.upsert(agentId, filename, content, params);+ }++ async findByAgent(agentId: string): Promise<AgentDocumentWithRules[]> {+ return queries.findByAgent(this.ctx, agentId);+ }++ async listByAgent(+ agentId: string,+ options?: { excludeWeb?: boolean; parentId?: string; sourceType?: AgentDocumentListSourceType },+ ): Promise<AgentDocumentListItem[]> {+ return queries.listByAgent(this.ctx, agentId, options);+ }++ async findSkillDocsByAgent(agentId: string): Promise<AgentDocumentWithRules[]> {+ return queries.findSkillDocsByAgent(this.ctx, agentId);+ }++ async findContextByAgent(agentId: string): Promise<AgentDocumentContextRow[]> {+ return queries.findContextByAgent(this.ctx, agentId);+ }++ async findByDocumentIds(+ agentId: string,+ documentIds: string[],+ ): Promise<AgentDocumentWithRules[]> {+ return queries.findByDocumentIds(this.ctx, agentId, documentIds);+ }++ async listByDocumentIds(+ agentId: string,+ documentIds: string[],+ options?: { sourceType?: AgentDocumentListSourceType },+ ): Promise<AgentDocumentListItem[]> {+ return queries.listByDocumentIds(this.ctx, agentId, documentIds, options);+ }++ async hasByAgent(agentId: string): Promise<boolean> {+ return queries.hasByAgent(this.ctx, agentId);+ }++ async findByTemplate(agentId: string, templateId: string): Promise<AgentDocumentWithRules[]> {+ return queries.findByTemplate(this.ctx, agentId, templateId);+ }++ async findByFilename(+ agentId: string,+ filename: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument | undefined> {+ return queries.findByFilename(this.ctx, agentId, filename, options);+ }++ async findByParentAndFilename(+ agentId: string,+ parentId: string | null,+ filename: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument | undefined> {+ return tree.findByParentAndFilename(this.ctx, agentId, parentId, filename, options);+ }++ /**+ * Lists agent document bindings that share one tree segment.+ *+ * Use when:+ * - VFS callers need to choose the visible entry for a path segment+ * - Migration checks need to detect duplicate `parentId + filename` rows+ *+ * Expects:+ * - `parentId` is the canonical document row parent id, not the agent document id+ *+ * Returns:+ * - Matching bindings ordered oldest first so duplicate filename resolution is deterministic+ */+ async listByParentAndFilename(+ agentId: string,+ parentId: string | null,+ filename: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument[]> {+ return tree.listByParentAndFilename(this.ctx, agentId, parentId, filename, options);+ }++ async findByDocumentId(+ agentId: string,+ documentId: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument | undefined> {+ return queries.findByDocumentId(this.ctx, agentId, documentId, options);+ }++ async listByParent(+ agentId: string,+ parentId: string | null,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument[]> {+ return tree.listByParent(this.ctx, agentId, parentId, options);+ }++ async listDeletedByAgent(agentId: string): Promise<AgentDocument[]> {+ return queries.listDeletedByAgent(this.ctx, agentId);+ }++ async listSubtreeByDocumentId(+ agentId: string,+ rootDocumentId: string,+ options?: AgentDocumentQueryOptions,+ ): Promise<AgentDocument[]> {+ return tree.listSubtreeByDocumentId(this.ctx, agentId, rootDocumentId, options);+ }++ async delete(documentId: string, deleteReason?: string): Promise<void> {+ return lifecycle.deleteDocument(this.ctx, documentId, deleteReason);+ }++ async deleteSubtreeByDocumentId(+ agentId: string,+ rootDocumentId: string,+ deleteReason?: string,+ ): Promise<void> {+ return lifecycle.deleteSubtreeByDocumentId(this.ctx, agentId, rootDocumentId, deleteReason);+ }++ /**+ * Restores a soft-deleted agent document binding to the live tree.+ *+ * Use when:+ * - Moving a deleted document back into active VFS visibility.+ * - Preserving the existing document row and agent document id.+ *+ * Expects:+ * - `documentId` may refer to a deleted binding owned by the current user.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - Nothing; missing bindings are ignored.+ *+ */+ async restore(documentId: string): Promise<void> {+ return lifecycle.restore(this.ctx, documentId);+ }++ async restoreSubtreeByDocumentId(agentId: string, rootDocumentId: string): Promise<void> {+ return lifecycle.restoreSubtreeByDocumentId(this.ctx, agentId, rootDocumentId);+ }++ /**+ * Removes a binding and its document when no other agent still owns that document.+ *+ * Use when:+ * - Permanently deleting an agent trash entry.+ * Expects:+ * - The binding belongs to the current scope.+ * Returns:+ * - Backing file IDs for reference-safe cleanup by the storage service after commit.+ */+ async permanentlyDelete(documentId: string): Promise<string[]> {+ return this.repository.permanentlyDelete(documentId);+ }++ /**+ * Permanently removes a subtree's bindings and documents without deleting shared documents.+ *+ * Use when:+ * - Erasing a complete document subtree in one transaction.+ * Expects:+ * - The root belongs to the requested agent and current scope.+ * Returns:+ * - Backing file IDs requiring reference-safe storage cleanup after commit.+ */+ async permanentlyDeleteSubtreeByDocumentId(+ agentId: string,+ rootDocumentId: string,+ ): Promise<string[]> {+ return this.repository.permanentlyDeleteSubtree(agentId, rootDocumentId);+ }++ async deleteByAgent(agentId: string, deleteReason?: string): Promise<void> {+ return lifecycle.deleteByAgent(this.ctx, agentId, deleteReason);+ }++ async deleteByTemplate(+ agentId: string,+ templateId: string,+ deleteReason?: string,+ ): Promise<void> {+ return lifecycle.deleteByTemplate(this.ctx, agentId, templateId, deleteReason);+ }++ async getDocumentsByPosition(+ agentId: string,+ ): Promise<Map<DocumentLoadPosition, AgentDocumentWithRules[]>> {+ return loading.getDocumentsByPosition(this.ctx, agentId);+ }++ async getLoadableDocuments(+ agentId: string,+ _context?: {+ currentTime?: Date;+ userMessage?: string;+ },+ ): Promise<AgentDocumentWithRules[]> {+ return loading.getLoadableDocuments(this.ctx, agentId, _context);+ }++ async getInjectableDocuments(+ agentId: string,+ context?: {+ currentTime?: Date;+ userMessage?: string;+ },+ ): Promise<AgentDocumentWithRules[]> {+ return loading.getInjectableDocuments(this.ctx, agentId, context);+ }++ async getAgentContext(agentId: string): Promise<string> {+ return loading.getAgentContext(this.ctx, agentId);+ }+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/lifecycle.ts b/packages/database/src/models/agentDocuments/agentDocument/lifecycle.tsnew file mode 100644index 00000000000..9e85872ebd6--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/lifecycle.ts@@ -0,0 +1,234 @@+import { and, eq, inArray, isNull, notExists } from 'drizzle-orm';++import { agentDocuments, documents } from '../../../schemas';+import type { Transaction } from '../../../type';+import { PolicyLoad } from '../types';+import { agentDocOwnership, type AgentDocumentContext, documentOwnership } from './context';+import { findByIdWithOptions } from './queries';+import { listSubtreeByDocumentId } from './tree';++export async function deleteDocument(+ ctx: AgentDocumentContext,+ documentId: string,+ deleteReason?: string,+): Promise<void> {+ // Soft delete only: mark deleted metadata and stop autoload.+ // We intentionally keep both agent_documents row and linked documents row for recovery.+ await ctx.db+ .update(agentDocuments)+ .set({+ policyLoad: PolicyLoad.DISABLED,+ deleteReason,+ deletedAt: new Date(),+ deletedByAgentId: null,+ deletedByUserId: ctx.userId,+ })+ .where(+ and(+ eq(agentDocuments.id, documentId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ );+}++export async function deleteSubtreeByDocumentId(+ ctx: AgentDocumentContext,+ agentId: string,+ rootDocumentId: string,+ deleteReason?: string,+): Promise<void> {+ const subtree = await listSubtreeByDocumentId(ctx, agentId, rootDocumentId);++ if (subtree.length === 0) return;++ await ctx.db+ .update(agentDocuments)+ .set({+ policyLoad: PolicyLoad.DISABLED,+ deleteReason,+ deletedAt: new Date(),+ deletedByAgentId: null,+ deletedByUserId: ctx.userId,+ })+ .where(+ and(+ agentDocOwnership(ctx),+ inArray(+ agentDocuments.id,+ subtree.map((item) => item.id),+ ),+ isNull(agentDocuments.deletedAt),+ ),+ );+}++/**+ * Restores a soft-deleted agent document binding to the live tree.+ *+ * Use when:+ * - Moving a deleted document back into active VFS visibility.+ * - Preserving the existing document row and agent document id.+ *+ * Expects:+ * - `documentId` may refer to a deleted binding owned by the current user.+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.+ *+ * Returns:+ * - Nothing; missing bindings are ignored.+ *+ */+export async function restore(ctx: AgentDocumentContext, documentId: string): Promise<void> {+ const existing = await findByIdWithOptions(ctx, documentId, { includeDeleted: true });++ if (!existing) return;++ await ctx.db+ .update(agentDocuments)+ .set({+ deleteReason: null,+ deletedAt: null,+ deletedByAgentId: null,+ deletedByUserId: null,+ policyLoad: PolicyLoad.PROGRESSIVE,+ })+ .where(and(eq(agentDocuments.id, documentId), agentDocOwnership(ctx)));+}++export async function restoreSubtreeByDocumentId(+ ctx: AgentDocumentContext,+ agentId: string,+ rootDocumentId: string,+): Promise<void> {+ const subtree = await listSubtreeByDocumentId(ctx, agentId, rootDocumentId, {+ includeDeleted: true,+ });++ if (subtree.length === 0) return;++ await ctx.db+ .update(agentDocuments)+ .set({+ deleteReason: null,+ deletedAt: null,+ deletedByAgentId: null,+ deletedByUserId: null,+ policyLoad: PolicyLoad.PROGRESSIVE,+ })+ .where(+ and(+ agentDocOwnership(ctx),+ inArray(+ agentDocuments.id,+ subtree.map((item) => item.id),+ ),+ ),+ );+}++/**+ * Hard-deletes agent document bindings by binding id.+ *+ * Use when:+ * - `AgentDocumentRepository` permanently deletes trash entries and then removes+ * the backing documents no other binding still references.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `agent_documents`.+ */+export async function deleteBindings(+ ctx: AgentDocumentContext,+ trx: Transaction,+ agentDocumentIds: string[],+): Promise<void> {+ await trx+ .delete(agentDocuments)+ .where(and(agentDocOwnership(ctx), inArray(agentDocuments.id, agentDocumentIds)));+}++/**+ * Removes only documents with no surviving agent binding and returns their backing files.+ *+ * Expects:+ * - `trx` is the caller-owned transaction; this helper writes only `documents`.+ */+export async function deleteUnboundDocuments(+ ctx: AgentDocumentContext,+ trx: Transaction,+ documentIds: string[],+): Promise<string[]> {+ // Serialize deletion with concurrent binding FK inserts before inspecting surviving owners.+ await trx+ .select({ id: documents.id })+ .from(documents)+ .where(and(documentOwnership(ctx), inArray(documents.id, documentIds)))+ .orderBy(documents.id)+ .for('update');+ // Removing one agent's binding must not cascade through another agent's shared document.+ const removed = await trx+ .delete(documents)+ .where(+ and(+ documentOwnership(ctx),+ inArray(documents.id, documentIds),+ notExists(+ trx+ .select({ id: agentDocuments.id })+ .from(agentDocuments)+ .where(eq(agentDocuments.documentId, documents.id)),+ ),+ ),+ )+ .returning({ fileId: documents.fileId });++ return [...new Set(removed.flatMap(({ fileId }) => (fileId ? [fileId] : [])))];+}++export async function deleteByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+ deleteReason?: string,+): Promise<void> {+ await ctx.db+ .update(agentDocuments)+ .set({+ policyLoad: PolicyLoad.DISABLED,+ deleteReason,+ deletedAt: new Date(),+ // NOTICE: mark for telling everyone that this should not ever marked as user id, no matter what circumstances+ deletedByAgentId: agentId,+ deletedByUserId: null,+ })+ .where(+ and(+ eq(agentDocuments.agentId, agentId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ );+}++export async function deleteByTemplate(+ ctx: AgentDocumentContext,+ agentId: string,+ templateId: string,+ deleteReason?: string,+): Promise<void> {+ await ctx.db+ .update(agentDocuments)+ .set({+ policyLoad: PolicyLoad.DISABLED,+ deleteReason,+ deletedAt: new Date(),+ deletedByAgentId: null,+ deletedByUserId: ctx.userId,+ })+ .where(+ and(+ eq(agentDocuments.agentId, agentId),+ eq(agentDocuments.templateId, templateId),+ agentDocOwnership(ctx),+ isNull(agentDocuments.deletedAt),+ ),+ );+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/loading.ts b/packages/database/src/models/agentDocuments/agentDocument/loading.tsnew file mode 100644index 00000000000..50d5d1490f3--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/loading.ts@@ -0,0 +1,67 @@+import { isLoadableDocument, resolveDocumentLoadPosition, sortByLoadRulePriority } from '../policy';+import type { AgentDocumentWithRules, DocumentLoadPosition } from '../types';+import type { AgentDocumentContext } from './context';+import { findByAgent } from './queries';++export async function getDocumentsByPosition(+ ctx: AgentDocumentContext,+ agentId: string,+): Promise<Map<DocumentLoadPosition, AgentDocumentWithRules[]>> {+ const docs = await getLoadableDocuments(ctx, agentId);+ const grouped = new Map<DocumentLoadPosition, AgentDocumentWithRules[]>();++ for (const doc of docs) {+ const position = resolveDocumentLoadPosition(doc);+ const existing = grouped.get(position) || [];++ existing.push(doc);+ grouped.set(position, sortByLoadRulePriority(existing));+ }++ return grouped;+}++export async function getLoadableDocuments(+ ctx: AgentDocumentContext,+ agentId: string,+ _context?: {+ currentTime?: Date;+ userMessage?: string;+ },+): Promise<AgentDocumentWithRules[]> {+ // Autoload gate: only documents explicitly marked as always-loadable are injected.+ // Agent access bits are enforced by caller/tool layer for interactive list/read/write actions.+ const docs = await findByAgent(ctx, agentId);+ return docs.filter((doc) => isLoadableDocument(doc));+}++export async function getInjectableDocuments(+ ctx: AgentDocumentContext,+ agentId: string,+ context?: {+ currentTime?: Date;+ userMessage?: string;+ },+): Promise<AgentDocumentWithRules[]> {+ return getLoadableDocuments(ctx, agentId, context);+}++export async function getAgentContext(ctx: AgentDocumentContext, agentId: string): Promise<string> {+ const docs = await getLoadableDocuments(ctx, agentId);++ if (docs.length === 0) {+ return '';+ }++ const contextParts: string[] = [];++ for (const doc of docs) {+ if (doc.content) {+ contextParts.push(`--- ${doc.filename} ---`);+ contextParts.push(doc.content);+ contextParts.push('');+ }+ }++ return contextParts.join('\n').trim();+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/queries.ts b/packages/database/src/models/agentDocuments/agentDocument/queries.tsnew file mode 100644index 00000000000..883d02a32a6--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/queries.ts@@ -0,0 +1,406 @@+import { and, asc, desc, eq, inArray, isNotNull, isNull, like, ne, or, sql } from 'drizzle-orm';++import { AGENT_SKILL_TEMPLATE_ID, agentDocuments, documents } from '../../../schemas';+import { deriveAgentDocumentFields } from '../deriveFields';+import { parseLoadRules } from '../policy';+import {+ type AgentDocument,+ type AgentDocumentContextRow,+ type AgentDocumentListItem,+ type AgentDocumentListSourceType,+ type AgentDocumentPolicy,+ type AgentDocumentWithRules,+ DocumentLoadFormat,+ PolicyLoad,+} from '../types';+import { agentDocOwnership, type AgentDocumentContext, documentOwnership } from './context';+import type { AgentDocumentQueryOptions } from './types';+import {+ buildDeletedAtFilters,+ listItemColumns,+ listSourceTypeFilter,+ toAgentDocument,+ toAgentDocumentListItem,+} from './utils';++export async function findById(+ ctx: AgentDocumentContext,+ documentId: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument | undefined> {+ return findByIdWithOptions(ctx, documentId, options);+}++export async function findByIdWithOptions(+ ctx: AgentDocumentContext,+ documentId: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument | undefined> {+ const [result] = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ eq(agentDocuments.id, documentId),+ agentDocOwnership(ctx),+ ...buildDeletedAtFilters(options),+ ),+ )+ .limit(1);++ if (!result) return undefined;++ return toAgentDocument(result.settings, result.doc);+}++export async function findByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+): Promise<AgentDocumentWithRules[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => {+ const item = toAgentDocument(settings, doc);+ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ loadRules: parseLoadRules(item),+ };+ });+}++export async function listByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+ options?: { excludeWeb?: boolean; parentId?: string; sourceType?: AgentDocumentListSourceType },+): Promise<AgentDocumentListItem[]> {+ const sourceType = options?.sourceType;+ const parentId = options?.parentId;+ const excludeWeb = options?.excludeWeb;+ const results = await ctx.db+ .select(listItemColumns)+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ ...listSourceTypeFilter(sourceType),+ ...(excludeWeb ? [ne(documents.sourceType, 'web')] : []),+ ...(parentId ? [eq(documents.parentId, parentId)] : []),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map((row) => toAgentDocumentListItem(row));+}++export async function findSkillDocsByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+): Promise<AgentDocumentWithRules[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ or(+ eq(agentDocuments.templateId, AGENT_SKILL_TEMPLATE_ID),+ like(documents.fileType, 'skills/%'),+ ),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => {+ const item = toAgentDocument(settings, doc);+ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ loadRules: parseLoadRules(item),+ };+ });+}++export async function findContextByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+): Promise<AgentDocumentContextRow[]> {+ const results = await ctx.db+ .select({+ doc: {+ content: sql<string>`+ CASE+ WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS}+ THEN COALESCE(${documents.content}, '')+ ELSE ''+ END+ `.as('content'),+ description: documents.description,+ editorData: sql<Record<string, any> | null>`+ CASE+ WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS} THEN ${documents.editorData}+ ELSE NULL+ END+ `.as('editor_data'),+ filename: documents.filename,+ fileType: documents.fileType,+ parentId: documents.parentId,+ sourceType: documents.sourceType,+ title: documents.title,+ totalCharCount: documents.totalCharCount,+ },+ settings: {+ agentId: agentDocuments.agentId,+ createdAt: agentDocuments.createdAt,+ documentId: agentDocuments.documentId,+ id: agentDocuments.id,+ policy: agentDocuments.policy,+ policyLoad: agentDocuments.policyLoad,+ policyLoadFormat: agentDocuments.policyLoadFormat,+ policyLoadPosition: agentDocuments.policyLoadPosition,+ policyLoadRule: agentDocuments.policyLoadRule,+ templateId: agentDocuments.templateId,+ updatedAt: agentDocuments.updatedAt,+ },+ })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => {+ const policy = (settings.policy as AgentDocumentPolicy | null) ?? null;+ const item: Omit<+ AgentDocumentContextRow,+ 'category' | 'isFolder' | 'isSkillBundle' | 'isSkillIndex' | 'loadRules'+ > = {+ content: doc.content,+ contentCharCount: doc.totalCharCount,+ createdAt: settings.createdAt,+ description: doc.description ?? null,+ documentId: settings.documentId,+ editorData: doc.editorData ?? null,+ filename: doc.filename ?? '',+ fileType: doc.fileType,+ id: settings.id,+ parentId: doc.parentId ?? null,+ policy,+ policyLoad: settings.policyLoad as PolicyLoad,+ policyLoadFormat:+ (settings.policyLoadFormat as DocumentLoadFormat | null) ??+ policy?.context?.policyLoadFormat ??+ DocumentLoadFormat.RAW,+ policyLoadPosition: settings.policyLoadPosition,+ policyLoadRule: settings.policyLoadRule,+ sourceType: doc.sourceType,+ templateId: settings.templateId ?? null,+ title: doc.title ?? doc.filename ?? '',+ updatedAt: settings.updatedAt,+ };+ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ loadRules: parseLoadRules(item),+ };+ });+}++export async function findByDocumentIds(+ ctx: AgentDocumentContext,+ agentId: string,+ documentIds: string[],+): Promise<AgentDocumentWithRules[]> {+ if (documentIds.length === 0) return [];++ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ inArray(agentDocuments.documentId, documentIds),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => {+ const item = toAgentDocument(settings, doc);+ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ loadRules: parseLoadRules(item),+ };+ });+}++export async function listByDocumentIds(+ ctx: AgentDocumentContext,+ agentId: string,+ documentIds: string[],+ options?: { sourceType?: AgentDocumentListSourceType },+): Promise<AgentDocumentListItem[]> {+ if (documentIds.length === 0) return [];++ const sourceType = options?.sourceType;+ const results = await ctx.db+ .select(listItemColumns)+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ inArray(agentDocuments.documentId, documentIds),+ isNull(agentDocuments.deletedAt),+ ...listSourceTypeFilter(sourceType),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map((row) => toAgentDocumentListItem(row));+}++export async function hasByAgent(ctx: AgentDocumentContext, agentId: string): Promise<boolean> {+ const [result] = await ctx.db+ .select({ id: agentDocuments.id })+ .from(agentDocuments)+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .limit(1);++ return !!result;+}++export async function findByTemplate(+ ctx: AgentDocumentContext,+ agentId: string,+ templateId: string,+): Promise<AgentDocumentWithRules[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(agentDocuments.templateId, templateId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => {+ const item = toAgentDocument(settings, doc);+ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ loadRules: parseLoadRules(item),+ };+ });+}++export async function findByFilename(+ ctx: AgentDocumentContext,+ agentId: string,+ filename: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument | undefined> {+ const [result] = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(documents.filename, filename),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))+ .limit(1);++ if (!result) return undefined;++ return toAgentDocument(result.settings, result.doc);+}++export async function findByDocumentId(+ ctx: AgentDocumentContext,+ agentId: string,+ documentId: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument | undefined> {+ const [result] = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(agentDocuments.documentId, documentId),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt))+ .limit(1);++ if (!result) return undefined;++ return toAgentDocument(result.settings, result.doc);+}++export async function listDeletedByAgent(+ ctx: AgentDocumentContext,+ agentId: string,+): Promise<AgentDocument[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ documentOwnership(ctx),+ isNotNull(agentDocuments.deletedAt),+ ),+ )+ .orderBy(desc(agentDocuments.deletedAt), desc(agentDocuments.updatedAt));++ return results.map(({ settings, doc }) => toAgentDocument(settings, doc));+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/tree.ts b/packages/database/src/models/agentDocuments/agentDocument/tree.tsnew file mode 100644index 00000000000..bf2db3b6f34--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/tree.ts@@ -0,0 +1,184 @@+import { and, asc, eq, inArray, isNotNull, isNull, sql } from 'drizzle-orm';++import { agentDocuments, documents } from '../../../schemas';+import type { AgentDocument } from '../types';+import { agentDocOwnership, type AgentDocumentContext } from './context';+import { findByDocumentId } from './queries';+import type { AgentDocumentQueryOptions } from './types';+import { buildDeletedAtFilters, normalizeListOffset, toAgentDocument } from './utils';++export async function listByParentIds(+ ctx: AgentDocumentContext,+ agentId: string,+ parentIds: string[],+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument[]> {+ if (parentIds.length === 0) return [];++ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ inArray(documents.parentId, parentIds),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id));++ return results.map(({ settings, doc }) => toAgentDocument(settings, doc));+}++/**+ * Counts live children per parent `documentId`, for listings that show which+ * entries (folders or documents) have something nested under them. Omit+ * `parentIds` to count every parent of the agent in one grouped query.+ * Parents without children are absent from the map.+ */+export async function countChildrenByParentIds(+ ctx: AgentDocumentContext,+ agentId: string,+ parentIds?: string[],+): Promise<Map<string, number>> {+ if (parentIds?.length === 0) return new Map();++ const rows = await ctx.db+ .select({ count: sql<number>`count(*)::int`, parentId: documents.parentId })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ parentIds ? inArray(documents.parentId, parentIds) : isNotNull(documents.parentId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .groupBy(documents.parentId);++ return new Map(+ rows.flatMap((row) => (row.parentId ? [[row.parentId, Number(row.count)] as const] : [])),+ );+}++export async function findByParentAndFilename(+ ctx: AgentDocumentContext,+ agentId: string,+ parentId: string | null,+ filename: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument | undefined> {+ const [result] = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(documents.filename, filename),+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))+ .limit(1);++ if (!result) return undefined;++ return toAgentDocument(result.settings, result.doc);+}++/**+ * Lists agent document bindings that share one tree segment.+ *+ * Use when:+ * - VFS callers need to choose the visible entry for a path segment+ * - Migration checks need to detect duplicate `parentId + filename` rows+ *+ * Expects:+ * - `parentId` is the canonical document row parent id, not the agent document id+ *+ * Returns:+ * - Matching bindings ordered oldest first so duplicate filename resolution is deterministic+ */+export async function listByParentAndFilename(+ ctx: AgentDocumentContext,+ agentId: string,+ parentId: string | null,+ filename: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ eq(documents.filename, filename),+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))+ .limit(options?.limit ?? 9999)+ .offset(normalizeListOffset(options?.cursor));++ return results.map(({ settings, doc }) => toAgentDocument(settings, doc));+}++export async function listByParent(+ ctx: AgentDocumentContext,+ agentId: string,+ parentId: string | null,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument[]> {+ const results = await ctx.db+ .select({ doc: documents, settings: agentDocuments })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ agentDocOwnership(ctx),+ eq(agentDocuments.agentId, agentId),+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),+ ...buildDeletedAtFilters(options),+ ),+ )+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))+ .limit(options?.limit ?? 9999)+ .offset(normalizeListOffset(options?.cursor));++ return results.map(({ settings, doc }) => toAgentDocument(settings, doc));+}++export async function listSubtreeByDocumentId(+ ctx: AgentDocumentContext,+ agentId: string,+ rootDocumentId: string,+ options?: AgentDocumentQueryOptions,+): Promise<AgentDocument[]> {+ const root = await findByDocumentId(ctx, agentId, rootDocumentId, options);++ if (!root) return [];++ const subtree = [root];+ const pendingParentIds = [root.documentId];++ while (pendingParentIds.length > 0) {+ const parentIds = pendingParentIds.splice(0, pendingParentIds.length);+ const children = await listByParentIds(ctx, agentId, parentIds, options);++ for (const child of children) {+ subtree.push(child);+ pendingParentIds.push(child.documentId);+ }+ }++ return subtree;+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/types.ts b/packages/database/src/models/agentDocuments/agentDocument/types.tsnew file mode 100644index 00000000000..361b77864f5--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/types.ts@@ -0,0 +1,72 @@+import type {+ AgentDocumentPolicy,+ AgentDocumentSourceType,+ DocumentLoadPosition,+ DocumentLoadRules,+ PolicyLoad,+} from '../types';++export interface AgentDocumentQueryOptions {+ cursor?: string;+ deletedOnly?: boolean;+ includeDeleted?: boolean;+ limit?: number;+}++export interface AgentDocumentCreateParams {+ createdAt?: Date;+ editorData?: Record<string, any>;+ fileId?: string;+ fileType?: string;+ loadPosition?: DocumentLoadPosition;+ loadRules?: DocumentLoadRules;+ metadata?: Record<string, any>;+ parentId?: string | null;+ policy?: AgentDocumentPolicy;+ policyLoad?: PolicyLoad;+ source?: string;+ sourceType?: AgentDocumentSourceType;+ templateId?: string;+ title?: string;+ updatedAt?: Date;+}++export interface AgentDocumentUpdateParams {+ content?: string;+ editorData?: Record<string, any> | null;+ fileType?: string;+ loadPosition?: DocumentLoadPosition;+ loadRules?: Partial<DocumentLoadRules>;+ metadata?: Record<string, any>;+ policy?: AgentDocumentPolicy;+ policyLoad?: PolicyLoad;+}++export interface ConvertAgentDocumentToSkillIndexParams {+ agentDocumentId: string;+ content: string;+ editorData?: Record<string, unknown>;+ filename: string;+ metadata: Record<string, unknown>;+ parentId: string;+ source: string;+ sourceType: AgentDocumentSourceType;+ title: string;+}++export interface AgentDocumentListQueryRow {+ createdAt: Date;+ description: string | null;+ documentId: string;+ documentUpdatedAt: Date;+ fileId: string | null;+ filename: string | null;+ fileType: string;+ id: string;+ parentId: string | null;+ policy: unknown;+ sourceType: AgentDocumentSourceType;+ templateId: string | null;+ title: string | null;+ updatedAt: Date;+}diff --git a/packages/database/src/models/agentDocuments/agentDocument/utils.ts b/packages/database/src/models/agentDocuments/agentDocument/utils.tsnew file mode 100644index 00000000000..13f28fed1d5--- /dev/null+++ b/packages/database/src/models/agentDocuments/agentDocument/utils.ts@@ -0,0 +1,157 @@+import { eq, isNotNull, isNull, ne } from 'drizzle-orm';++import { agentDocuments, type DocumentItem, documents } from '../../../schemas';+import { deriveAgentDocumentFields } from '../deriveFields';+import {+ type AgentDocument,+ type AgentDocumentListItem,+ type AgentDocumentListSourceType,+ type AgentDocumentPolicy,+ DocumentLoadFormat,+ type PolicyLoad,+} from '../types';+import type { AgentDocumentListQueryRow, AgentDocumentQueryOptions } from './types';++/** Columns of one document-tree row (agent binding joined to its document). */+export const listItemColumns = {+ createdAt: documents.createdAt,+ description: documents.description,+ documentId: agentDocuments.documentId,+ documentUpdatedAt: documents.updatedAt,+ fileId: documents.fileId,+ fileType: documents.fileType,+ filename: documents.filename,+ id: agentDocuments.id,+ parentId: documents.parentId,+ policy: agentDocuments.policy,+ sourceType: documents.sourceType,+ templateId: agentDocuments.templateId,+ title: documents.title,+ updatedAt: agentDocuments.updatedAt,+};++/**+ * Map the list API's source filter onto `documents.source_type`.+ *+ * The list contract has two buckets: `web` (crawled pages) and `file` (everything+ * authored or uploaded as an agent document). Authored docs are stored as+ * `agent` / `agent-signal` / `api`, so `file` means "not web" rather than the+ * literal `file` source type, which only covers uploaded originals.+ */+export const listSourceTypeFilter = (sourceType?: AgentDocumentListSourceType) => {+ if (sourceType === 'web') return [eq(documents.sourceType, 'web')];+ if (sourceType === 'file') return [ne(documents.sourceType, 'web')];+ return [];+};++export function getDocumentStats(content: string) {+ if (!content) return { totalCharCount: 0, totalLineCount: 0 };++ return {+ totalCharCount: content.length,+ totalLineCount: content.split('\n').length,+ };+}++export function getMetadataDescription(+ metadata?: Record<string, unknown> | null,+): string | undefined {+ if (!metadata) return undefined;++ if (typeof metadata.description === 'string') return metadata.description;++ const skill = metadata.skill;+ if (!skill || typeof skill !== 'object') return undefined;++ const frontmatter = (skill as Record<string, unknown>).frontmatter;+ if (!frontmatter || typeof frontmatter !== 'object') return undefined;++ const description = (frontmatter as Record<string, unknown>).description;+ return typeof description === 'string' ? description : undefined;+}++export function toAgentDocument(+ settings: typeof agentDocuments.$inferSelect,+ doc: DocumentItem,+): AgentDocument {+ const policy = (settings.policy as AgentDocumentPolicy | null) ?? null;+ const policyLoadFormat =+ (settings.policyLoadFormat as DocumentLoadFormat | null) ??+ policy?.context?.policyLoadFormat ??+ DocumentLoadFormat.RAW;++ return {+ accessPublic: settings.accessPublic,+ accessSelf: settings.accessSelf,+ accessShared: settings.accessShared,+ agentId: settings.agentId,+ policyLoad: settings.policyLoad as PolicyLoad,+ content: doc.content ?? '',+ createdAt: settings.createdAt,+ deleteReason: settings.deleteReason,+ deletedAt: settings.deletedAt,+ deletedByAgentId: settings.deletedByAgentId,+ deletedByUserId: settings.deletedByUserId,+ description: doc.description ?? null,+ documentId: settings.documentId,+ editorData: doc.editorData ?? null,+ fileType: doc.fileType,+ filename: doc.filename ?? '',+ id: settings.id,+ metadata: (doc.metadata as Record<string, any> | null) ?? null,+ parentId: doc.parentId ?? null,+ policy,+ policyLoadFormat,+ policyLoadPosition: settings.policyLoadPosition,+ policyLoadRule: settings.policyLoadRule,+ source: doc.source ?? null,+ sourceType: doc.sourceType,+ templateId: settings.templateId ?? null,+ title: doc.title ?? doc.filename ?? '',+ updatedAt: settings.updatedAt,+ userId: settings.userId,+ };+}++export function toAgentDocumentListItem(row: AgentDocumentListQueryRow): AgentDocumentListItem {+ const filename = row.filename ?? '';+ const policy = (row.policy as AgentDocumentPolicy | null) ?? null;+ const item = {+ createdAt: row.createdAt,+ description: row.description ?? null,+ documentId: row.documentId,+ documentUpdatedAt: row.documentUpdatedAt,+ fileId: row.fileId,+ fileType: row.fileType,+ filename,+ id: row.id,+ loadPosition: policy?.context?.position,+ parentId: row.parentId ?? null,+ sourceType: row.sourceType,+ templateId: row.templateId ?? null,+ title: row.title ?? filename,+ updatedAt: row.updatedAt,+ };++ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ };+}++export function buildDeletedAtFilters(options?: AgentDocumentQueryOptions) {+ if (options?.deletedOnly) return [isNotNull(agentDocuments.deletedAt)];+ if (options?.includeDeleted) return [];++ return [isNull(agentDocuments.deletedAt)];+}++export function normalizeListOffset(cursor?: string): number {+ if (!cursor) return 0;++ const parsed = Number.parseInt(cursor, 10);++ // Offset cursors keep the first VFS pagination pass storage-neutral.+ // Callers that need opaque cursors can wrap this model helper at the service layer later.+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;+}diff --git a/packages/database/src/repositories/agentDocument/__tests__/index.test.ts b/packages/database/src/repositories/agentDocument/__tests__/index.test.tsnew file mode 100644index 00000000000..1926d72f35e--- /dev/null+++ b/packages/database/src/repositories/agentDocument/__tests__/index.test.ts@@ -0,0 +1,111 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { PolicyLoad } from '../../../models/agentDocuments/types';+import { agentDocuments, agents, documents, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { AgentDocumentRepository } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-document-repository-user';+const agentId = 'agent-document-repository-agent';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, title: 'Agent', userId });+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentDocumentRepository', () => {+ it('creates the document row and its binding together', async () => {+ const repo = new AgentDocumentRepository(serverDB, userId);++ const created = await repo.create(agentId, 'notes.md', '# Notes');++ const [binding] = await serverDB+ .select()+ .from(agentDocuments)+ .where(eq(agentDocuments.id, created.id));+ const [document] = await serverDB+ .select()+ .from(documents)+ .where(eq(documents.id, created.documentId));++ expect(binding?.documentId).toBe(document?.id);+ expect(document?.content).toBe('# Notes');+ });++ it('rolls back the document row when the binding insert fails', async () => {+ const repo = new AgentDocumentRepository(serverDB, userId);++ await expect(repo.create('missing-agent', 'orphan.md', 'orphan')).rejects.toThrow();++ const orphans = await serverDB+ .select({ id: documents.id })+ .from(documents)+ .where(eq(documents.filename, 'orphan.md'));+ expect(orphans).toEqual([]);+ });++ it('updates the backing document and binding policy in one call', async () => {+ const repo = new AgentDocumentRepository(serverDB, userId);+ const created = await repo.create(agentId, 'rules.md', 'old');++ await repo.update(created.id, { content: 'new', policyLoad: PolicyLoad.DISABLED });++ const [row] = await serverDB+ .select({ content: documents.content, policyLoad: agentDocuments.policyLoad })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(eq(agentDocuments.id, created.id));+ expect(row).toEqual({ content: 'new', policyLoad: 'disabled' });+ });++ it('converts a binding into a skill index while keeping both ids', async () => {+ const repo = new AgentDocumentRepository(serverDB, userId);+ const bundle = await repo.create(agentId, 'my-skill', '');+ const doc = await repo.create(agentId, 'draft.md', 'draft');++ const converted = await repo.convertToSkillIndex({+ agentDocumentId: doc.id,+ content: 'skill body',+ filename: 'SKILL.md',+ metadata: {},+ parentId: bundle.documentId,+ source: 'agent-skill://my-skill/SKILL.md',+ sourceType: 'agent',+ title: 'My Skill',+ });++ expect(converted).toMatchObject({+ documentId: doc.documentId,+ fileType: 'skills/index',+ filename: 'SKILL.md',+ id: doc.id,+ templateId: 'agent-skill',+ });+ });++ it('permanently deletes a subtree and returns no files for file-less documents', async () => {+ const repo = new AgentDocumentRepository(serverDB, userId);+ const folder = await repo.create(agentId, 'folder', '');+ const child = await repo.create(agentId, 'child.md', 'child', {+ parentId: folder.documentId,+ });++ expect(await repo.permanentlyDeleteSubtree(agentId, folder.documentId)).toEqual([]);++ const remaining = await serverDB+ .select({ id: documents.id })+ .from(documents)+ .where(eq(documents.id, child.documentId));+ expect(remaining).toEqual([]);+ });+});diff --git a/packages/database/src/repositories/agentDocument/index.ts b/packages/database/src/repositories/agentDocument/index.tsnew file mode 100644index 00000000000..e64427e836d--- /dev/null+++ b/packages/database/src/repositories/agentDocument/index.ts@@ -0,0 +1,298 @@+import type { DocumentAccessScope } from '@lobechat/types';+import { ordinaryDocumentAccessScope } from '@lobechat/types';++import type { AgentDocumentContext } from '../../models/agentDocuments/agentDocument/context';+import {+ findLiveWithTx,+ insertBackingDocument,+ insertBinding,+ markBindingAsSkillIndex,+ updateBackingDocumentAsSkillIndex,+} from '../../models/agentDocuments/agentDocument/creation';+import {+ buildBackingDocumentUpdate,+ buildBindingSettingsUpdate,+ updateBackingDocument,+ updateBindingSettings,+} from '../../models/agentDocuments/agentDocument/edits';+import {+ deleteBindings,+ deleteUnboundDocuments,+} from '../../models/agentDocuments/agentDocument/lifecycle';+import {+ findByFilename,+ findById,+ findByIdWithOptions,+} from '../../models/agentDocuments/agentDocument/queries';+import { listSubtreeByDocumentId } from '../../models/agentDocuments/agentDocument/tree';+import type {+ AgentDocumentCreateParams,+ AgentDocumentUpdateParams,+ ConvertAgentDocumentToSkillIndexParams,+} from '../../models/agentDocuments/agentDocument/types';+import { buildCopyParams } from '../../models/agentDocuments/copyDocument';+import { buildDocumentFilename } from '../../models/agentDocuments/filename';+import { parseLoadRules } from '../../models/agentDocuments/policy';+import type {+ AgentDocument,+ AgentDocumentPolicy,+ DocumentLoadPosition,+ DocumentLoadRules,+ PolicyLoad,+} from '../../models/agentDocuments/types';+import type { LobeChatDatabase, Transaction } from '../../type';++export interface AgentDocumentUpsertParams {+ createdAt?: Date;+ editorData?: Record<string, any>;+ loadPosition?: DocumentLoadPosition;+ loadRules?: DocumentLoadRules;+ metadata?: Record<string, any>;+ policy?: AgentDocumentPolicy;+ policyLoad?: PolicyLoad;+ templateId?: string;+ updatedAt?: Date;+}++/**+ * Owns agent-document units of work that span the `documents` aggregate and the+ * `agent_documents` binding aggregate.+ *+ * Use when:+ * - Creating, copying, updating or upserting an agent document (document row + binding).+ * - Converting a binding into a managed skill index (document rewrite + binding policy).+ * - Permanently deleting bindings together with the documents they leave unbound.+ *+ * Expects:+ * - The same user, workspace and document-access scope as `AgentDocumentModel`.+ *+ * Returns:+ * - Scoped operations whose writes commit or roll back together.+ *+ * Call stack:+ *+ * AgentDocumentModel.create / copy / update / upsert / permanentlyDelete*+ * -> AgentDocumentRepository+ * -> single-table helpers in models/agentDocuments/agentDocument+ */+export class AgentDocumentRepository {+ private readonly ctx: AgentDocumentContext;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,+ ) {+ this.ctx = { db, documentAccessScope, userId, workspaceId };+ }++ /**+ * Creates a document row and links it to an agent in one transaction.+ */+ async create(+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentCreateParams,+ ): Promise<AgentDocument> {+ return this.ctx.db.transaction((trx) =>+ this.createWithTx(trx, agentId, filename, content, params),+ );+ }++ /**+ * Creates a document row and links it to an agent inside a caller-owned transaction.+ *+ * Expects:+ * - `trx` is the active transaction for every write in the caller's unit of work.+ */+ async createWithTx(+ trx: Transaction,+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentCreateParams,+ ): Promise<AgentDocument> {+ const document = await insertBackingDocument(this.ctx, trx, agentId, filename, content, params);++ return insertBinding(this.ctx, trx, agentId, document, params);+ }++ /**+ * Duplicates a live agent document under a new filename for the same agent.+ */+ async copy(documentId: string, newTitle?: string): Promise<AgentDocument | undefined> {+ const existing = await findById(this.ctx, documentId);+ if (!existing) return undefined;++ const title = newTitle?.trim();+ const filename = title+ ? buildDocumentFilename(title)+ : `copy-${Date.now()}-${existing.filename}`;++ // Empty-parse shells must not be duplicated as another shell (the clone+ // reads as Lexical error #38 and blocks cleanup); see `copyDocument.ts`+ // for the shell detection and raw-text downgrade.+ return this.create(+ existing.agentId,+ filename,+ existing.content,+ buildCopyParams(existing, title),+ );+ }++ /**+ * Updates a binding's load policy and, when content fields are given, its+ * backing document in one transaction.+ *+ * Expects:+ * - `documentId` is the agent document binding id; missing bindings are ignored.+ */+ async update(documentId: string, params?: AgentDocumentUpdateParams): Promise<void> {+ const existing = await findById(this.ctx, documentId);++ if (!existing) return;++ const settingsUpdate = buildBindingSettingsUpdate(existing, params);+ const documentUpdate = buildBackingDocumentUpdate(this.ctx, params);++ await this.ctx.db.transaction(async (trx) => {+ if (documentUpdate) {+ await updateBackingDocument(this.ctx, trx, existing.documentId, documentUpdate);+ }++ await updateBindingSettings(this.ctx, trx, documentId, settingsUpdate);+ });+ }++ /**+ * Updates an existing document by filename or creates a new one when missing.+ *+ * Expects:+ * - `filename` addresses the current agent's ordinary filename lookup.+ * - Duplicate filenames are allowed; the first matching filename is the oldest live binding.+ */+ async upsert(+ agentId: string,+ filename: string,+ content: string,+ params?: AgentDocumentUpsertParams,+ ): Promise<AgentDocument> {+ const {+ createdAt,+ editorData,+ loadPosition,+ loadRules,+ metadata,+ policy,+ policyLoad,+ templateId,+ updatedAt,+ } = params ?? {};++ const existing = await findByFilename(this.ctx, agentId, filename);++ if (existing) {+ const currentRules = parseLoadRules(existing);+ const mergedRules = loadRules ? { ...currentRules, ...loadRules } : currentRules;+ const mergedMetadata = metadata+ ? { ...existing.metadata, ...metadata }+ : (existing.metadata ?? undefined);++ await this.update(existing.id, {+ content,+ editorData,+ loadPosition,+ loadRules: mergedRules,+ metadata: mergedMetadata,+ policy,+ policyLoad,+ });++ return (await findByFilename(this.ctx, agentId, filename))!;+ }++ return this.create(agentId, filename, content, {+ createdAt,+ editorData,+ loadPosition,+ loadRules,+ metadata,+ policy,+ policyLoad,+ templateId,+ updatedAt,+ });+ }++ /**+ * Converts an existing ordinary agent document binding into a managed skill index.+ *+ * Returns:+ * - The same agent document binding after document identity and load metadata are updated.+ */+ async convertToSkillIndex(+ params: ConvertAgentDocumentToSkillIndexParams,+ ): Promise<AgentDocument | undefined> {+ return this.ctx.db.transaction((trx) => this.convertToSkillIndexWithTx(trx, params));+ }++ /**+ * Converts a live agent document binding into a managed skill index inside a+ * caller-owned transaction, preserving both `agent_documents.id` and `documents.id`.+ */+ async convertToSkillIndexWithTx(+ trx: Transaction,+ params: ConvertAgentDocumentToSkillIndexParams,+ ): Promise<AgentDocument | undefined> {+ const existing = await findLiveWithTx(this.ctx, trx, params.agentDocumentId);+ if (!existing) return undefined;++ await updateBackingDocumentAsSkillIndex(this.ctx, trx, existing.documentId, params);+ await markBindingAsSkillIndex(this.ctx, trx, params.agentDocumentId);++ return findLiveWithTx(this.ctx, trx, params.agentDocumentId);+ }++ /**+ * Removes a binding and its document when no other agent still owns that document.+ *+ * Returns:+ * - Backing file IDs for reference-safe cleanup by the storage service after commit.+ */+ async permanentlyDelete(documentId: string): Promise<string[]> {+ const existing = await findByIdWithOptions(this.ctx, documentId, { includeDeleted: true });++ if (!existing) return [];++ return this.ctx.db.transaction(async (trx) => {+ await deleteBindings(this.ctx, trx, [documentId]);++ return deleteUnboundDocuments(this.ctx, trx, [existing.documentId]);+ });+ }++ /**+ * Permanently removes a subtree's bindings and documents without deleting shared documents.+ *+ * Returns:+ * - Backing file IDs requiring reference-safe storage cleanup after commit.+ */+ async permanentlyDeleteSubtree(agentId: string, rootDocumentId: string): Promise<string[]> {+ const subtree = await listSubtreeByDocumentId(this.ctx, agentId, rootDocumentId, {+ includeDeleted: true,+ });++ if (subtree.length === 0) return [];++ const agentDocumentIds = subtree.map((item) => item.id);+ const documentIds = subtree.map((item) => item.documentId);++ return this.ctx.db.transaction(async (trx) => {+ await deleteBindings(this.ctx, trx, agentDocumentIds);++ return deleteUnboundDocuments(this.ctx, trx, documentIds);+ });+ }+}