/** * Database Client * * SQLite database operations for AI context storage. * Handles CRUD operations, queries, and vector search. */ import Database from 'better-sqlite3'; import { type ContextType, type RelationType, type SyncStatus, type AITool } from './schema.js'; /** * Context item structure */ export interface ContextItem { id: string; type: ContextType; name: string; content: string; metadata?: Record; filePath?: string; contentHash?: string; createdAt?: string; updatedAt?: string; } /** * Knowledge graph edge */ export interface GraphEdge { id?: number; sourceId: string; targetId: string; relationType: RelationType; weight?: number; metadata?: Record; } /** * Git commit record */ export interface GitCommit { sha: string; message: string; authorName?: string; authorEmail?: string; timestamp: string; filesChanged?: string[]; stats?: { additions: number; deletions: number; }; } /** * Sync state record */ export interface SyncState { id: string; tool: string; contentHash?: string; lastSync: string; filePath?: string; status: SyncStatus; metadata?: Record; k0ntextVersion?: string; userModified?: number; lastChecked?: string; } /** * AI tool configuration record */ export interface AIToolConfig { id: string; toolName: AITool; configPath: string; content: string; contentHash?: string; lastSync: string; status: SyncStatus; metadata?: Record; } /** * Version tracking record */ export interface VersionTracking { tool: string; k0ntextVersion: string; userModified?: boolean; lastChecked?: string; filePath?: string; contentHash?: string; } /** * Generated file record */ export interface GeneratedFile { id: string; tool: string; filePath: string; contentHash: string; backupPath?: string; generatedAt: string; lastVerifiedAt?: string; userModified: boolean; metadata?: Record; } /** * Search result with similarity score */ export interface SearchResult { item: ContextItem; similarity: number; } /** * Database client for AI context storage */ export declare class DatabaseClient { private db; private dbPath; /** * Create a new DatabaseClient with async initialization * This is the recommended way to create a DatabaseClient as it handles migrations */ static create(projectRoot: string, dbFileName?: string): Promise; /** * Legacy synchronous constructor * @deprecated Use DatabaseClient.create() instead for proper migration support */ constructor(projectRoot: string, dbFileName?: string, skipInit?: boolean); /** * Synchronous schema initialization for legacy constructor */ private initSchemaSync; /** * Migrate legacy database */ private migrateLegacyDatabase; /** * Initialize database schema with migration support */ private initSchema; /** * Execute callback within a transaction (sync) */ transaction(callback: () => T): T; /** * Execute callback within a transaction (async) */ transaction(callback: () => Promise): Promise; /** * Begin a manual transaction (returns rollback/commit functions) */ beginTransaction(): { rollback: () => void; commit: () => void; }; /** * Check database connection health */ healthCheck(): { healthy: boolean; error?: string; }; /** * Generate content hash for deduplication (public for modification detection) */ hashContent(content: string): string; /** * Generate a unique ID for a context item */ private generateId; /** * Insert or update a context item */ upsertItem(item: Omit): ContextItem; /** * Get a context item by ID */ getItem(id: string): ContextItem | null; /** * Get items by type */ getItemsByType(type: ContextType): ContextItem[]; /** * Get all items */ getAllItems(): ContextItem[]; /** * Delete a context item */ deleteItem(id: string): boolean; /** * Delete items older than specified days */ deleteStaleItems(daysOld: number, type?: ContextType): number; /** * Search items by text (full-text grep-style) */ searchText(query: string, type?: ContextType): ContextItem[]; /** * Convert database row to ContextItem */ private rowToItem; /** * Calculate relevance score for a search result */ private calculateRelevance; /** * Upsert an AI tool configuration */ upsertToolConfig(config: Omit): AIToolConfig; /** * Get tool configs by tool name */ getToolConfigs(toolName: AITool): AIToolConfig[]; /** * Get all tool configs */ getAllToolConfigs(): AIToolConfig[]; /** * Add a relationship to the knowledge graph */ addRelation(edge: Omit): GraphEdge; /** * Get relations from a source item */ getRelationsFrom(sourceId: string, relationType?: RelationType): GraphEdge[]; /** * Get relations to a target item */ getRelationsTo(targetId: string, relationType?: RelationType): GraphEdge[]; /** * Traverse the graph from a starting point */ traverseGraph(startId: string, maxDepth?: number): Map; /** * Insert or update a git commit */ upsertCommit(commit: GitCommit): void; /** * Get recent commits */ getRecentCommits(limit?: number): GitCommit[]; /** * Update sync state for a tool */ updateSyncState(state: SyncState): void; /** * Get sync state for a tool */ getSyncState(tool: string): SyncState[]; /** * Get all version tracking records */ getAllVersionTracking(): VersionTracking[]; /** * Update version tracking for a tool */ updateVersionTracking(tracking: VersionTracking): void; /** * Get version tracking for a specific tool */ getVersionTracking(tool: string): VersionTracking | null; /** * Upsert a generated file record */ upsertGeneratedFile(record: { tool: string; filePath: string; contentHash: string; backupPath?: string; metadata?: Record; }): GeneratedFile; /** * Get generated file info by tool and path */ getGeneratedFileInfo(tool: string, filePath: string): GeneratedFile | null; /** * Mark a generated file as user modified */ markUserModified(tool: string, filePath: string): void; /** * Get all generated files for a tool */ getGeneratedFiles(tool: string): GeneratedFile[]; /** * Store an embedding */ storeEmbedding(contextId: string, embedding: number[]): void; /** * Search by embedding similarity */ searchByEmbedding(queryEmbedding: number[], limit?: number): SearchResult[]; /** * Hybrid search combining vector and text search */ hybridSearch(query: string, queryEmbedding: number[] | null, options?: { limit?: number; type?: ContextType; vectorWeight?: number; }): SearchResult[]; /** * Delete an embedding */ deleteEmbedding(contextId: string): boolean; /** * Insert or update an embedding for a file by path */ insertEmbedding(filePath: string, embedding: number[]): void; /** * Get item ID by file path */ private getItemIdByPath; /** * Log a usage event */ logUsage(toolName: string, query?: string, resultCount?: number, latencyMs?: number): void; /** * Get usage statistics */ getUsageStats(days?: number): { toolName: string; count: number; avgLatency: number; }[]; /** * Get database path */ getPath(): string; /** * Get database statistics */ getStats(): { items: number; relations: number; commits: number; embeddings: number; toolConfigs: number; path: string; }; /** * Get raw database instance (for advanced operations) */ getRawDb(): Database.Database; /** * Vacuum database to reclaim space */ vacuum(): void; /** * Reindex database for optimization */ reindex(): void; /** * Backup database to specified path */ backup(backupPath: string): void; /** * Prepare a SQL statement * Exposes the underlying Database.prepare() method for external use */ prepare(sql: string): Database.Statement; /** * Close database connection */ close(): void; } //# sourceMappingURL=client.d.ts.map