/** * @claude-flow/memory - V3 Unified Memory System * * Provides a unified memory interface backed by AgentDB with HNSW indexing * for 150x-12,500x faster vector search compared to brute-force approaches. * * @module @claude-flow/memory * * @example * ```typescript * import { UnifiedMemoryService, query, QueryTemplates } from '@claude-flow/memory'; * * // Initialize the memory service * const memory = new UnifiedMemoryService({ * dimensions: 1536, * cacheEnabled: true, * embeddingGenerator: async (text) => embeddings.embed(text), * }); * * await memory.initialize(); * * // Store entries * await memory.store({ * key: 'auth-patterns', * content: 'OAuth 2.0 implementation patterns for secure authentication', * tags: ['auth', 'security', 'patterns'], * }); * * // Semantic search * const results = await memory.semanticSearch('user authentication best practices', 5); * * // Query with fluent builder * const entries = await memory.query( * query() * .semantic('security vulnerabilities') * .inNamespace('security') * .withTags(['critical']) * .threshold(0.8) * .limit(10) * .build() * ); * ``` */ export type { MemoryType, AccessLevel, ConsistencyLevel, DistanceMetric, MemoryEntry, MemoryEntryInput, MemoryEntryUpdate, QueryType, MemoryQuery, SearchResult, SearchOptions, HNSWConfig, HNSWStats, QuantizationConfig, IMemoryBackend, BackendStats, HealthCheckResult, ComponentHealth, CacheConfig, CacheStats, CachedEntry, MigrationSource, MigrationConfig, MigrationProgress, MigrationResult, MigrationError, MemoryEventType, MemoryEvent, MemoryEventHandler, SONAMode, LearningPattern, EmbeddingGenerator, } from './types.js'; export { generateMemoryId, createDefaultEntry, PERFORMANCE_TARGETS, } from './types.js'; export { AutoMemoryBridge, resolveAutoMemoryDir, findGitRoot } from './auto-memory-bridge.js'; export type { AutoMemoryBridgeConfig, MemoryInsight, InsightCategory, SyncDirection, SyncMode, PruneStrategy, SyncResult, ImportResult, } from './auto-memory-bridge.js'; export { LearningBridge } from './learning-bridge.js'; export type { LearningBridgeConfig, LearningStats, ConsolidateResult, PatternMatch, } from './learning-bridge.js'; export { RvfLearningStore } from './rvf-learning-store.js'; export type { RvfLearningStoreConfig, PatternRecord, LoraRecord, EwcRecord, TrajectoryRecord, } from './rvf-learning-store.js'; export { PersistentSonaCoordinator } from './persistent-sona.js'; export type { PersistentSonaConfig } from './persistent-sona.js'; export { RvfMigrator } from './rvf-migration.js'; export type { RvfMigrationOptions, RvfMigrationResult } from './rvf-migration.js'; export { MemoryGraph } from './memory-graph.js'; export type { MemoryGraphConfig, GraphNode, GraphEdge, GraphStats, RankedResult, EdgeType, } from './memory-graph.js'; export { resolveAgentMemoryDir, createAgentBridge, transferKnowledge, listAgentScopes, } from './agent-memory-scope.js'; export type { AgentMemoryScope, AgentScopedConfig, TransferOptions, TransferResult, } from './agent-memory-scope.js'; export { ControllerRegistry, INIT_LEVELS } from './controller-registry.js'; export type { AgentDBControllerName, CLIControllerName, ControllerName, InitLevel, ControllerHealth, RegistryHealthReport, RuntimeConfig, } from './controller-registry.js'; export { AgentDBAdapter } from './agentdb-adapter.js'; export type { AgentDBAdapterConfig } from './agentdb-adapter.js'; export { AgentDBBackend } from './agentdb-backend.js'; export type { AgentDBBackendConfig } from './agentdb-backend.js'; export { SQLiteBackend } from './sqlite-backend.js'; export type { SQLiteBackendConfig } from './sqlite-backend.js'; export { SqlJsBackend } from './sqljs-backend.js'; export type { SqlJsBackendConfig } from './sqljs-backend.js'; export { HybridBackend } from './hybrid-backend.js'; export type { HybridBackendConfig, StructuredQuery, SemanticQuery, HybridQuery, } from './hybrid-backend.js'; export { HNSWIndex } from './hnsw-index.js'; export { CacheManager, TieredCacheManager } from './cache-manager.js'; export { QueryBuilder, query, QueryTemplates } from './query-builder.js'; export type { SortDirection, SortField } from './query-builder.js'; export { MemoryMigrator, createMigrator, migrateMultipleSources } from './migration.js'; export { createDatabase, getPlatformInfo, getAvailableProviders } from './database-provider.js'; export type { DatabaseProvider, DatabaseOptions } from './database-provider.js'; export { smartSearch, defaultQueryExpansions } from './smart-retrieval.js'; export type { SearchCandidate, RawSearchRequest, RawSearchResponse, SearchFn, SmartSearchOptions, SmartSearchStats, SmartSearchResult, } from './smart-retrieval.js'; import { EventEmitter } from 'node:events'; import { IMemoryBackend, MemoryEntry, MemoryEntryInput, MemoryEntryUpdate, MemoryQuery, SearchResult, SearchOptions, BackendStats, HealthCheckResult, EmbeddingGenerator, MigrationSource, MigrationConfig, MigrationResult } from './types.js'; import { AgentDBAdapter, AgentDBAdapterConfig } from './agentdb-adapter.js'; /** * Configuration for UnifiedMemoryService */ export interface UnifiedMemoryServiceConfig extends Partial { /** Enable automatic embedding generation */ autoEmbed?: boolean; /** Default embedding dimensions */ dimensions?: number; /** Embedding generator function */ embeddingGenerator?: EmbeddingGenerator; /** * Take an HNSW + metadata snapshot every N successful `store()` calls. * Set to `0` (or `Infinity`) to disable interval-based snapshots — `close()` * still flushes. Default: 1000. * * Only takes effect when `persistenceEnabled === true` and `persistencePath` * is set. Added by ADR-125 Phase 3. */ snapshotInterval?: number; /** * Configuration for the background {@link MemoryConsolidator}. Added by * ADR-125 Phase 4. When `autoRun: true`, the service starts a `setInterval` * timer (default 6h) that runs sweep + dedup + compact and emits the * result via `'consolidation:complete'`. */ consolidator?: { autoRun?: boolean; intervalMs?: number; dedupStrategy?: 'keep-newest' | 'keep-oldest' | 'merge-tags'; }; } /** * Memory Service implementation (legacy class name). * * @deprecated Use {@link MemoryService} — the canonical name introduced by * ADR-125 Phase 1. `UnifiedMemoryService` is preserved as an alias and will * continue to work through `@claude-flow/memory@3.0.0-rc`. Both names refer * to the same class. * * High-level interface that provides: * - Simple API for common operations * - Automatic embedding generation * - Cross-agent memory sharing * - SONA integration for learning * - Event-driven notifications * - Performance monitoring * * @see {@link MemoryService} for the canonical alias. */ export declare class UnifiedMemoryService extends EventEmitter implements IMemoryBackend { private adapter; private config; private initialized; /** Total successful `store()` calls since last snapshot trigger (ADR-125 Phase 3). */ private storeCountSinceSnapshot; /** Resolved snapshot interval — see {@link UnifiedMemoryServiceConfig.snapshotInterval}. */ private readonly snapshotInterval; /** Background consolidator timer (ADR-125 Phase 4). */ private consolidatorTimer; /** Lazy-loaded consolidator instance (ADR-125 Phase 4). */ private consolidator; /** * The active memory backend. Defaults to the `AgentDBAdapter` created from * config, but can be any `IMemoryBackend` implementation (e.g. `HybridBackend` * when constructed via `createHybridService` per ADR-009 / ADR-125 Phase 2). * * Public so consumers can introspect the backend type without reaching for * `getAdapter()` (which is AgentDB-specific). */ backend: IMemoryBackend; constructor(config?: UnifiedMemoryServiceConfig); /** * Replace the active backend with a pre-built `IMemoryBackend`. * * Used by `createHybridService` (ADR-125 Phase 2) to wire `HybridBackend` * through `createDatabase` rather than instantiating `AgentDBAdapter` * directly. The legacy `AgentDBAdapter` instance is kept around for the * `storeEntry` / `semanticSearch` convenience methods that the IMemoryBackend * interface doesn't cover; those calls still flow through it. * * Returns `this` for chaining. * * @internal Prefer the factory functions (`createHybridService`, * `createPersistentService`, etc.) over calling this directly. */ withBackend(backend: IMemoryBackend): this; initialize(): Promise; shutdown(): Promise; /** * Alias for {@link shutdown}. Matches the lifecycle name expected by callers * who treat `MemoryService` like a connection — referenced from ADR-125 * Phase 3 (snapshot on close()) and Phase 4 (consolidator timer cleanup). */ close(): Promise; /** * Start the background consolidator timer if configured. * @internal */ private startConsolidatorTimer; /** * Run a single consolidator cycle on the active adapter. Emits a * `consolidation:complete` event with the {@link ConsolidationResult}. * @internal */ private runAutoConsolidation; /** * Get (and lazily construct) the {@link MemoryConsolidator} bound to this * service. Added by ADR-125 Phase 4. */ getConsolidator(): Promise; store(entry: MemoryEntry): Promise; /** * If a snapshot interval is configured and the threshold is hit, fire a * snapshot in the background. Only meaningful when the active backend is * the AgentDBAdapter with persistence enabled. * * @internal — ADR-125 Phase 3 */ private maybeSnapshot; get(id: string): Promise; getByKey(namespace: string, key: string): Promise; update(id: string, update: MemoryEntryUpdate): Promise; delete(id: string): Promise; query(query: MemoryQuery): Promise; search(embedding: Float32Array, options: SearchOptions): Promise; bulkInsert(entries: MemoryEntry[]): Promise; bulkDelete(ids: string[]): Promise; count(namespace?: string): Promise; listNamespaces(): Promise; clearNamespace(namespace: string): Promise; getStats(): Promise; healthCheck(): Promise; /** * Store an entry from simple input. * * When the active backend is the default AgentDBAdapter, delegates to its * native `storeEntry`. When a custom backend is wired (e.g. HybridBackend * via `createHybridService`), this builds a full `MemoryEntry` and stores * it through the IMemoryBackend interface. */ storeEntry(input: MemoryEntryInput): Promise; /** * Semantic search by content string. * * When the active backend is the default AgentDBAdapter, delegates to its * native `semanticSearch`. Otherwise generates an embedding via the * configured generator and calls `backend.search()`. */ semanticSearch(content: string, k?: number, threshold?: number): Promise; /** * Find similar entries to a given entry */ findSimilar(id: string, k?: number): Promise; /** * Get or create an entry */ getOrCreate(namespace: string, key: string, creator: () => MemoryEntryInput | Promise): Promise; /** * Append content to an existing entry */ appendContent(id: string, content: string): Promise; /** * Add tags to an existing entry */ addTags(id: string, tags: string[]): Promise; /** * Remove tags from an existing entry */ removeTags(id: string, tags: string[]): Promise; /** * Migrate from a legacy memory source. * * The migrator is AgentDB-specific (writes through `AgentDBAdapter`). * When a custom backend is wired (e.g. HybridBackend), migration still * targets the local AgentDB adapter; the hybrid backend can pick up the * migrated entries on next read via its own AgentDB index. */ migrateFrom(source: MigrationSource, sourcePath: string, options?: Partial): Promise; /** * Share an entry with another agent */ shareWith(id: string, agentId: string): Promise; /** * Get entries shared with a specific agent */ getSharedWith(agentId: string): Promise; /** * Get the underlying adapter for advanced operations */ getAdapter(): AgentDBAdapter; /** * Check if the service is initialized */ isInitialized(): boolean; } /** * Canonical memory service entry point (ADR-125). * * `MemoryService` is the preferred name as of `@claude-flow/memory@3.0.0-alpha.18`. * It is an alias of {@link UnifiedMemoryService}; both names refer to the same * class so existing callers continue working unchanged. * * @example * ```typescript * import { MemoryService } from '@claude-flow/memory'; * * const memory = new MemoryService({ dimensions: 1536 }); * await memory.initialize(); * ``` */ export declare const MemoryService: typeof UnifiedMemoryService; /** * @public * @typedef MemoryService * * Type alias matching the canonical {@link MemoryService} runtime export so that * `import type { MemoryService } from '@claude-flow/memory'` works alongside the * value import. */ export type MemoryService = UnifiedMemoryService; /** * Config type alias for {@link MemoryService}. */ export type MemoryServiceConfig = UnifiedMemoryServiceConfig; /** * Create a simple in-memory service (for testing) */ export declare function createInMemoryService(): UnifiedMemoryService; /** * Create a persistent memory service */ export declare function createPersistentService(path: string): UnifiedMemoryService; /** * Create a memory service with embedding support */ export declare function createEmbeddingService(embeddingGenerator: EmbeddingGenerator, dimensions?: number): UnifiedMemoryService; /** * Create a hybrid memory service (SQLite + AgentDB). * * This is the DEFAULT recommended configuration per ADR-009. ADR-125 Phase 2 * delivers the real wiring: the returned service's backend is a `HybridBackend` * created through `createDatabase({ provider: 'hybrid' })`, not an AgentDB-only * downgrade as in earlier versions. * * @example * ```typescript * const memory = await createHybridService('./data/memory.db', embeddingFn); * await memory.initialize(); * * // Structured queries go to SQLite * const user = await memory.getByKey('users', 'john@example.com'); * * // Semantic queries go to AgentDB * const similar = await memory.semanticSearch('authentication patterns', 10); * * // Verify the backend is actually hybrid * import { HybridBackend } from '@claude-flow/memory'; * memory.backend instanceof HybridBackend; // true * ``` */ export declare function createHybridService(databasePath: string, embeddingGenerator: EmbeddingGenerator, dimensions?: number): Promise; export default UnifiedMemoryService; //# sourceMappingURL=index.d.ts.map