/**
 * Memory Engine — Persistent Zettelkasten
 *
 * Three-tier memory system backed by SQLite for cross-session persistence.
 * Memories link to each other (Zettelkasten) — recall returns context networks,
 * not just isolated facts. High-value memories trigger fission (broadcast).
 *
 * Persistence: ~/.nexus-prime/memory.db
 * Load on MCP start. Flush on exit.
 */
import Database from 'better-sqlite3';
import { GraphMemoryEngine } from './graph-memory.js';
import { NgramIndex } from './ngram-index.js';
import { type MemoryMaintenanceResult, type MemoryProvenance, type MemoryReconciliationSummary } from './memory-control-plane.js';
export * from './memory/types.js';
import { type MemoryItem, type MemoryStats, type MemoryStorageStatus, type MemoryContainerLane, type MemoryLayerId, type MemoryLayerContractEntry, type MemoryRecallFilters, type MemoryRetentionHint, type MemoryHistoryEntry, type MemoryUpdateResult, type MemoryDeleteResult, type MemoryFeedbackResult, type MemoryRecallMatch, type MemorySearchMatch, type MemoryContainerSummary, type MemoryBackupSnapshot, type MemoryEntityReference, type MemorySnapshot, type MemoryDetail, type MemoryTraceDetail, type MemoryNetworkSnapshot, type MemoryCheckResult, type MemoryConfig, type MemoryAuditResult, type MemoryHealthSummary, type MemoryHygieneResult, type MemoryExportBundle, type MemoryImportResult, type TokenTelemetryEntry } from './memory/types.js';
export declare class MemoryEngine {
    db: Database.Database;
    private dbPath;
    private requestedDbPath;
    private stateRoot;
    private graphDbPath;
    private storageFallbackApplied;
    private storageFallbackReason?;
    private graphMirror?;
    private ngramIndex?;
    private sessionId;
    private vaultDir;
    private vaultItemsDir;
    private vaultExportsDir;
    private vaultNotesDir;
    private vaultEntityNotesDir;
    private vaultRunNotesDir;
    private vaultSessionNotesDir;
    private backupMetadataPath;
    private lastReconciliationSummary;
    private lastPreCompactionBackup;
    private config;
    private incrementAccessStmt;
    private incrementAccessTxn;
    private vaultDirty;
    private vaultFlushTimer?;
    private vaultNeedsFullSync;
    private vaultWriteQueue;
    private vaultIndexChain;
    private lastDatabaseVacuumAt;
    private prefrontal;
    private maxPrefrontal;
    private maxHippocampus;
    private embedder;
    private readonly extractor;
    private vectorIdToMemoryId;
    private memoryIdToVectorId;
    private nextVectorId;
    private readonly sqliteRetryAttempts;
    private readonly sqliteRetryDelayMs;
    constructor(dbPath?: string, config?: MemoryConfig);
    getNgramIndex(): NgramIndex | undefined;
    getCurrentRepoId(): string;
    /** Returns true when the first-run demo seed has already been applied. */
    isFirstRunSeen(): boolean;
    /** Mark first-run seed as applied and record DEMO_SEEDED flag. */
    markFirstRunSeen(): void;
    getStorageStatus(): MemoryStorageStatus;
    private initSchema;
    private prepareStatements;
    private getSchemaVersion;
    private getRuntimeMeta;
    private setRuntimeMeta;
    private getLastHygieneAt;
    private countPurgeEligible;
    private withSqliteRetry;
    private isSqliteBusyError;
    private runMigrations;
    /** Record token telemetry to local sqlite ledger */
    insertTokenTelemetry(entry: Omit<TokenTelemetryEntry, 'id' | 'timestamp'>): void;
    /** Restore hippocampus + cortex from DB on startup */
    load(): void;
    private loadBackupMetadata;
    private ensurePersistentVocabulary;
    private fitVocabularyWithRecovery;
    private repairCorruptedVocabularyPersistence;
    private captureMemoryDbSnapshot;
    private captureMemoryRowsForRepair;
    private rotateCorruptedMemoryFiles;
    private reopenMemoryDatabase;
    private restoreMemoryDbSnapshot;
    private createMemoryDbLoadError;
    private manualRecoveryHint;
    /** Flush prefrontal to DB (called on MCP shutdown) */
    flush(): void;
    /** Alias for flush() that delegates to SQLite transaction immediately, tracking stats */
    preCompactionFlush(reason: string): void;
    store(content: string, priority?: number, tags?: string[], parentId?: string, depth?: number, options?: {
        sessionId?: string;
        timestamp?: number;
        tier?: MemoryItem['tier'];
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        source?: MemoryItem['source'];
        trust?: number;
        expiresAt?: number;
        purgeAt?: number;
        retentionHint?: MemoryRetentionHint;
        supersedes?: string;
        supersededBy?: string;
        provenance?: Partial<MemoryProvenance>;
        /** When true, skip eager compression. Tag stored as #verbatim so
         *  downstream compaction/summarization passes leave the item intact. */
        verbatim?: boolean;
    }): string;
    /** Expose the underlying graph memory engine for temporal and structural queries. */
    getGraphMemory(): GraphMemoryEngine | undefined;
    storeWithControlPlane(content: string, priority?: number, tags?: string[], parentId?: string, depth?: number, options?: {
        sessionId?: string;
        timestamp?: number;
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        source?: MemoryItem['source'] | 'rag';
        provenance?: Partial<MemoryProvenance>;
        defaultTtlMs?: number;
        retentionHint?: MemoryRetentionHint;
        maxCandidates?: number;
        verbatim?: boolean;
    }): {
        storedIds: string[];
        summary: MemoryReconciliationSummary;
    };
    recall(query: string, k?: number, filters?: MemoryRecallFilters): Promise<string[]>;
    /** Recall with quality metadata for token budget allocation */
    recallWithMetadata(query: string, k?: number, filters?: MemoryRecallFilters): Promise<MemoryRecallMatch[]>;
    /**
     * Compute file relevance boosts from memory content.
     * Scans recent active memories for file path mentions and returns boost scores.
     */
    getFileBoosts(candidateFiles: string[]): Map<string, number>;
    /** Promote a memory to 'shared' scope so it becomes visible across all repos */
    shareMemory(id: string): boolean;
    /** Compact vault by merging individual item files into a single snapshot */
    compactVault(items?: MemoryItem[]): {
        itemsMerged: number;
        snapshotPath: string;
    } | null;
    checkContent(content: string, options?: {
        tags?: string[];
        priority?: number;
        parentId?: string;
    }): MemoryCheckResult;
    audit(limit?: number): MemoryAuditResult;
    listQuarantined(limit?: number): MemorySnapshot[];
    getLastReconciliationSummary(): MemoryReconciliationSummary;
    maintain(): MemoryMaintenanceResult;
    runHygiene(options?: {
        mode?: 'report' | 'apply';
        batchSize?: number;
        states?: Array<MemoryItem['state']>;
        auditLimit?: number;
    }): MemoryHygieneResult;
    private trimNoisyActiveBatch;
    private expireStateBatch;
    private prepareScrapPurgeBatch;
    trace(id: string): MemoryTraceDetail | undefined;
    updateMemory(id: string, patch?: {
        content?: string;
        priority?: number;
        tags?: string[];
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        trust?: number;
        expiresAt?: number | null;
        purgeAt?: number | null;
        retentionHint?: MemoryRetentionHint;
        provenance?: Partial<MemoryProvenance>;
    }): MemoryUpdateResult;
    deleteMemory(id: string, options?: {
        hardDelete?: boolean;
        reason?: string;
        provenance?: Partial<MemoryProvenance>;
    }): MemoryDeleteResult;
    getMemoryHistory(id: string, limit?: number): MemoryHistoryEntry[];
    submitMemoryFeedback(id: string, input?: {
        reaction?: 'positive' | 'negative' | 'promote' | 'demote' | 'quarantine';
        rating?: number;
        note?: string;
        provenance?: Partial<MemoryProvenance>;
    }): MemoryFeedbackResult;
    private vectorEmbeddings;
    private indexMemory;
    /**
     * Upgrade a memory's embedding to a higher-quality vector (e.g. Ollama 768-dim).
     * Called fire-and-forget after store() when an async embedder is available.
     */
    private upgradeEmbeddingAsync;
    /**
     * Reindex all memory embeddings using the current (best available) embedder.
     * Use for migrating existing TF-IDF embeddings to Ollama/API embeddings.
     */
    reindexEmbeddings(batchSize?: number): Promise<{
        upgraded: number;
        failed: number;
        total: number;
    }>;
    private autoLink;
    autoLinkBatch(items: MemoryItem[]): void;
    /** Get a memory's connected context network */
    getNetwork(id: string, depth?: number): MemoryItem[];
    private fission;
    /** Periodic cooling cycle: increases entropy and decays priority with tier-specific rates */
    coolDown(): void;
    /** Maintenance cycle: runs coolDown() then expires memories where entropy > threshold AND accessCount < 2 AND age > 7 days */
    maintenanceCycle(): void;
    backgroundLinkMaintenance(): void;
    private consolidate;
    private inferScope;
    private normalizeProjectScopedTags;
    private extractProjectId;
    private inferState;
    private inferSource;
    private inferLane;
    private isHiddenMemory;
    private matchesContainerFilters;
    private matchesRecallFilters;
    private classifyMemoryLayer;
    private shouldCreatePreCompactionBackup;
    private createPreCompactionBackup;
    private parseRawTags;
    private estimateTrust;
    private relevanceScore;
    private importanceScore;
    private freshnessScore;
    private ensureVaultDirs;
    private readVaultDir;
    private syncVault;
    flushVaultSync(): void;
    /**
     * Awaits every in-flight vault write that was kicked off by flushVaultSync,
     * writeVaultItem, writeVaultNote, compactVault, or loadBackupMetadata.
     * Callers that need to inspect vault files on disk immediately (tests,
     * backup verification, etc.) must await this to avoid a write/read race.
     */
    awaitVaultFlush(): Promise<void>;
    private trackVaultWrite;
    private markVaultDirty;
    private flushDirtyVault;
    private writeVaultIndex;
    private syncVaultFull;
    private writeVaultItem;
    private writeVaultNote;
    private removeVaultItem;
    private renderMemoryNote;
    private projectEntityNotes;
    private projectSessionNotes;
    private parseProvenance;
    private rowToHistory;
    private appendHistory;
    private resolveRetentionExpiresAt;
    private resolveRetentionPurgeAt;
    private extractReferenceIds;
    private reconcileCandidate;
    private expireMemories;
    private wordOverlap;
    private estimateEntropy;
    private rowToItem;
    private getById;
    private getTotalMemoryCount;
    private getStateCounts;
    private listVaultIndexItems;
    private listContentCheckCandidates;
    private listReconciliationCandidates;
    private clamp01;
    private qmdComponents;
    private computeQmdScore;
    private getFeedbackStats;
    private buildDecayProfile;
    private buildReinforcementProfile;
    private applyRecallRerankerHint;
    private getAllItems;
    private getItemsByIds;
    private listVaultLiveItems;
    private toSnapshot;
    private getLinkCount;
    private getLinkedMemories;
    private buildLineage;
    private buildTimeline;
    private extractEntityReferences;
    getStats(): MemoryStats;
    snapshot(limit?: number): MemoryItem[];
    listSnapshots(limit?: number, filters?: {
        tier?: MemoryItem['tier'];
        tag?: string;
        recencyMs?: number;
        linkedType?: MemoryEntityReference['type'];
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        source?: MemoryItem['source'];
        sessionId?: string;
        repoId?: string;
        workspaceId?: string;
        projectId?: string;
        lane?: MemoryContainerLane;
        includeHidden?: boolean;
    }): MemorySnapshot[];
    getSnapshot(id: string): MemorySnapshot | undefined;
    getDetail(id: string): MemoryDetail | undefined;
    getNetworkSnapshot(id?: string, depth?: number, limit?: number, options?: {
        includeQuarantined?: boolean;
    }): MemoryNetworkSnapshot;
    clear(): void;
    getHealthSummary(): MemoryHealthSummary;
    /**
     * Tier promotion sweep: promote memories that have been accessed enough
     * and have aged out of their current tier.
     *
     * Rules (per CLAUDE.md §3 v6 roadmap):
     *   prefrontal  (access_count >= 3, age > 60 min)  → hippocampus
     *   hippocampus (access_count >= 5, age > 7 days)  → cortex
     *
     * Called at session end (nexus_session_dna generate) so memory naturally
     * migrates toward long-term storage over multiple sessions.
     */
    runTierPromotion(): {
        toHippocampus: number;
        toCortex: number;
        durationMs: number;
    };
    getScopeUsageSummary(sessionId?: string): {
        generatedAt: number;
        byScope: Record<string, number>;
        byState: Record<string, number>;
        byLayer: Record<MemoryLayerId, number>;
        sharedContextCount: number;
        contract: Record<MemoryLayerId, MemoryLayerContractEntry>;
    };
    getContainerSummary(sessionId?: string): MemoryContainerSummary;
    getLastPreCompactionBackup(): MemoryBackupSnapshot | null;
    listSharedSnapshots(limit?: number, sessionId?: string): MemorySnapshot[];
    private deriveExportOrigin;
    exportBundle(options?: {
        limit?: number;
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        sessionId?: string;
    }): MemoryExportBundle;
    backupBundle(options?: {
        limit?: number;
        scope?: MemoryItem['scope'];
        state?: MemoryItem['state'];
        sessionId?: string;
    }): {
        path: string;
        bundle: MemoryExportBundle;
    };
    importBundle(input: {
        path?: string;
        bundle?: MemoryExportBundle;
    }): Promise<MemoryImportResult>;
    /**
     * Query memories by tag using direct SQL — precise, no fuzzy matching.
     * Returns memories that contain ANY of the specified tags.
     */
    queryByTags(tags: string[], limit?: number): MemoryItem[];
    /**
     * Search memories by free text + tags with optional fuzzy matching.
     * Combines n-gram overlap and vector similarity to rank candidates.
     */
    searchByTagsAndContent(query: string, tags?: string[], options?: {
        fuzzy?: boolean;
        scope?: MemoryItem['scope'];
        limit?: number;
        fuzzyThreshold?: number;
        /** Memory states to include. Defaults to ['active'] for backward compatibility. */
        states?: Array<MemoryItem['state']>;
    }): MemorySearchMatch[];
    close(): void;
    private listVaultSnapshotPaths;
    private buildVaultItemPayload;
    private purgeExpiredMemories;
    private optimizeDatabase;
    private mirrorIntoGraph;
    private primeGraphMirror;
    private checkGraphCoverage;
    private rebuildPersistentVocabularyStatsIfNeeded;
}
export declare const createMemoryEngine: (dbPath?: string) => MemoryEngine;
export * from './memory/schema.js';
export * from './memory/store.js';
export * from './memory/recall.js';
export * from './memory/tier-promotion.js';
export * from './memory/entropy-decay.js';
