/** * Integrity Engine Module * * Provides periodic integrity checking to fix drift from missed file watcher events. * Compares stored fingerprints with current filesystem state and queues necessary updates. * Runs on MCP server startup and periodically (24 hours default). * * Features: * - Drift detection: Identifies added, modified, and removed files * - Reconciliation: Processes drift categories to update the index * - Scheduling: Startup checks and periodic background checks * - Non-blocking operations: Startup check runs in background */ import { IndexManager } from './indexManager.js'; import { IndexingPolicy } from './indexPolicy.js'; import { FingerprintsManager } from '../storage/fingerprints.js'; /** * Report of drift between filesystem and index */ export interface DriftReport { /** Files on disk but not in index */ added: string[]; /** Files with different content hash than stored */ modified: string[]; /** Files in index but not on disk */ removed: string[]; /** Count of files that are unchanged */ inSync: number; /** Timestamp of when check was performed */ lastChecked: Date; } /** * Result of a reconciliation operation */ export interface ReconcileResult { /** Whether reconciliation completed successfully */ success: boolean; /** Number of files added to index */ filesAdded: number; /** Number of files updated in index */ filesModified: number; /** Number of files removed from index */ filesRemoved: number; /** Total duration in milliseconds */ durationMs: number; /** Errors encountered during reconciliation */ errors?: string[]; } /** * Progress callback for reconciliation operations */ export type ReconcileProgressCallback = (progress: ReconcileProgress) => void; /** * Progress information during reconciliation */ export interface ReconcileProgress { /** Current phase of reconciliation */ phase: 'scanning' | 'adding' | 'modifying' | 'removing'; /** Current item number being processed */ current: number; /** Total items to process in this phase */ total: number; /** Current file being processed */ currentFile?: string; } /** * Default interval for periodic integrity checks (24 hours in milliseconds) */ export declare const DEFAULT_CHECK_INTERVAL: number; /** * Scan the current filesystem state for indexable files * * Returns a map of relative paths to their content hashes for all files * that pass the indexing policy. * * DoS Protection: * - Limits glob results to MAX_GLOB_RESULTS * - Limits directory depth to MAX_DIRECTORY_DEPTH * - Applies timeout to glob operations (GLOB_TIMEOUT_MS) * * @param projectPath - Absolute path to the project root * @param policy - Initialized IndexingPolicy instance * @param maxResults - Maximum number of files to return (default: MAX_GLOB_RESULTS) * @param maxDepth - Maximum directory depth (default: MAX_DIRECTORY_DEPTH) * @returns Map of relative path to SHA256 content hash * @throws ResourceLimitError if glob returns too many files */ export declare function scanCurrentState(projectPath: string, policy: IndexingPolicy, maxResults?: number, maxDepth?: number): Promise>; /** * Calculate drift between filesystem and stored fingerprints * * Compares the current filesystem state with stored fingerprints to identify: * - Added files: Present on disk but not in fingerprints * - Modified files: Different hash than stored * - Removed files: In fingerprints but not on disk * * @param projectPath - Absolute path to the project root * @param fingerprints - FingerprintsManager instance (must be loaded) * @param policy - Initialized IndexingPolicy instance * @returns DriftReport with categorized files */ export declare function calculateDrift(projectPath: string, fingerprints: FingerprintsManager, policy: IndexingPolicy): Promise; /** * Reconcile drift between filesystem and index * * Processes all drift categories: * - Added: Chunk, embed, insert into index, add to fingerprints * - Modified: Delete old chunks, re-chunk/embed/insert, update fingerprint * - Removed: Delete chunks from index, remove from fingerprints * * @param projectPath - Absolute path to the project root * @param indexPath - Absolute path to the index directory * @param indexManager - IndexManager instance for updates * @param fingerprints - FingerprintsManager instance * @param policy - Initialized IndexingPolicy instance * @param onProgress - Optional progress callback * @returns ReconcileResult with operation details */ export declare function reconcile(projectPath: string, indexPath: string, indexManager: IndexManager, fingerprints: FingerprintsManager, policy: IndexingPolicy, onProgress?: ReconcileProgressCallback): Promise; /** * Scheduler for periodic integrity checks * * Manages background periodic checks and provides manual trigger capability. * * @example * ```typescript * const scheduler = new IntegrityScheduler(engine, 24 * 60 * 60 * 1000); * scheduler.start(); * * // Later, to run a check immediately * const report = await scheduler.runNow(); * * // When done * scheduler.stop(); * ``` */ export declare class IntegrityScheduler { private readonly engine; private readonly checkInterval; private timer; private isRunning; private lastCheckTime; /** Reference to cleanup handler for unregistration */ private cleanupHandler; /** * Create a new IntegrityScheduler * * @param engine - IntegrityEngine instance to use for checks * @param checkInterval - Interval between checks in milliseconds (default: 24 hours) */ constructor(engine: IntegrityEngine, checkInterval?: number); /** * Start periodic integrity checks * * Schedules checks to run at the configured interval. * Does not run an immediate check - use runNow() for that. * * BUG #16 FIX: Added explicit timer check to prevent potential leak. * If isRunning is true but timer is set (edge case), the existing timer * is cleared before creating a new one. */ start(): void; /** * Stop periodic integrity checks */ stop(): void; /** * Run an integrity check immediately * * @returns DriftReport from the check */ runNow(): Promise; /** * Check if the scheduler is currently running */ isSchedulerRunning(): boolean; /** * Get the time of the last check */ getLastCheckTime(): Date | null; /** * Get the check interval */ getCheckInterval(): number; /** * Internal method to run a scheduled check */ private runScheduledCheck; } /** * Integrity Engine for managing index integrity * * Provides drift detection and reconciliation capabilities for keeping * the search index in sync with the filesystem. * * @example * ```typescript * const engine = new IntegrityEngine( * projectPath, * indexPath, * indexManager, * fingerprints, * policy * ); * * // Check for drift * const drift = await engine.checkDrift(); * if (drift.added.length + drift.modified.length + drift.removed.length > 0) { * // Reconcile changes * const result = await engine.reconcile(); * } * * // Start periodic checks * engine.startPeriodicCheck(); * * // Stop when done * engine.stopPeriodicCheck(); * ``` */ export declare class IntegrityEngine { private readonly projectPath; private readonly indexPath; private readonly indexManager; private readonly fingerprints; private readonly policy; private scheduler; private _isIndexingActive; /** * Create a new IntegrityEngine * * @param projectPath - Absolute path to the project root * @param indexPath - Absolute path to the index directory * @param indexManager - IndexManager instance for updates * @param fingerprints - FingerprintsManager instance (should be loaded) * @param policy - IndexingPolicy instance (should be initialized) */ constructor(projectPath: string, indexPath: string, indexManager: IndexManager, fingerprints: FingerprintsManager, policy: IndexingPolicy); /** * Check for drift between filesystem and index * * Performs a full scan of the filesystem and compares with stored fingerprints. * * @returns DriftReport with categorized files */ checkDrift(): Promise; /** * Reconcile drift between filesystem and index * * Calculates drift and applies necessary updates to bring the index in sync. * * @param onProgress - Optional callback for progress updates * @returns ReconcileResult with operation details */ reconcile(onProgress?: ReconcileProgressCallback): Promise; /** * Start periodic integrity checks * * @param intervalMs - Interval between checks in milliseconds (default: 24 hours) */ startPeriodicCheck(intervalMs?: number): void; /** * Stop periodic integrity checks */ stopPeriodicCheck(): void; /** * Check if periodic checks are running */ isPeriodicCheckRunning(): boolean; /** * Check if indexing is currently active * * Used by scheduler to avoid running checks during active indexing. */ isIndexingActive(): boolean; /** * Set indexing active state * * Should be called by IndexManager when starting/finishing indexing operations. */ setIndexingActive(active: boolean): void; /** * Get the project path */ getProjectPath(): string; /** * Get the index path */ getIndexPath(): string; /** * Get the scheduler (if periodic checks are running) */ getScheduler(): IntegrityScheduler | null; } /** * Run a quick startup integrity check * * This function performs a non-blocking drift check on startup. * It logs the drift summary at INFO level but does not automatically reconcile. * * @param engine - IntegrityEngine instance * @returns Promise that resolves to the DriftReport */ export declare function runStartupCheck(engine: IntegrityEngine): Promise; /** * Run startup check in background (non-blocking) * * Starts the startup check without waiting for it to complete. * Logs results when done. * * BUG #21 FIX: Wraps in try-catch to handle synchronous errors that may occur * before the promise is returned. Uses Promise.resolve().then() pattern to * ensure all errors (sync and async) are caught. * * @param engine - IntegrityEngine instance */ export declare function runStartupCheckBackground(engine: IntegrityEngine): void; /** * Create an IntegrityEngine for a project * * Convenience function to create an IntegrityEngine with all required dependencies. * * @param projectPath - Absolute path to the project root * @param indexPath - Absolute path to the index directory * @param indexManager - IndexManager instance * @param fingerprints - FingerprintsManager instance * @param policy - IndexingPolicy instance * @returns IntegrityEngine instance */ export declare function createIntegrityEngine(projectPath: string, indexPath: string, indexManager: IndexManager, fingerprints: FingerprintsManager, policy: IndexingPolicy): IntegrityEngine; //# sourceMappingURL=integrity.d.ts.map