/**
 * @fileoverview Ralph Tracker - Detects Ralph Wiggum loops, todos, and completion phrases.
 *
 * Parses terminal output from Claude Code sessions to detect:
 * - Ralph loop state (active, completion phrase, iteration count)
 * - Todo items from the TodoWrite tool (with deduplication and expiry)
 * - Completion phrases signaling loop completion
 * - Circuit breaker state (CLOSED/HALF_OPEN/OPEN)
 *
 * DISABLED by default — auto-enables when Ralph-related patterns appear,
 * reducing overhead for non-autonomous sessions.
 *
 * Composed of four sub-modules:
 * - `RalphPlanTracker`: Plan task management, checkpoints, versioning
 * - `RalphFixPlanWatcher`: @fix_plan.md file watching and parsing
 * - `RalphStallDetector`: Iteration stall detection
 * - `RalphStatusParser`: RALPH_STATUS block parsing, circuit breaker
 *
 * Key exports:
 * - `RalphTracker` class — main tracker, extends EventEmitter
 * - `RalphTrackerEvents` interface — typed event map
 *
 * Key methods: `processData(data)` — feed terminal output, `getState()`,
 * `getTodos()`, `getCompletionHistory()`, `getPlanTasks()`, `reset()`
 *
 * @dependencies types (RalphTrackerState, RalphTodoItem, CircuitBreakerStatus),
 *   ralph-plan-tracker, ralph-fix-plan-watcher, ralph-stall-detector, ralph-status-parser,
 *   config/buffer-limits, config/map-limits
 * @consumedby session (owns one RalphTracker per session), web/server (SSE events)
 * @emits ralphStateChanged, todoUpdated, completionDetected, statusBlockParsed,
 *   circuitBreakerChanged, exitGateMet, planTaskUpdated, planCheckpoint
 *
 * @module ralph-tracker
 */
import { EventEmitter } from 'node:events';
import { RalphTrackerState, RalphTodoItem, RalphStatusBlock, CircuitBreakerStatus, RalphTodoProgress, CompletionConfidence, PlanTaskStatus, TddPhase } from './types.js';
import { RalphPlanTracker } from './ralph-plan-tracker.js';
import type { EnhancedPlanTask, CheckpointReview } from './ralph-plan-tracker.js';
import { RalphFixPlanWatcher } from './ralph-fix-plan-watcher.js';
import { RalphStallDetector } from './ralph-stall-detector.js';
import { RalphStatusParser } from './ralph-status-parser.js';
/**
 * Events emitted by RalphTracker
 * @event loopUpdate - Fired when loop state changes (active, iteration, completion phrase)
 * @event todoUpdate - Fired when todo list changes (items added, status changed)
 * @event completionDetected - Fired when completion phrase is detected (task complete)
 * @event enabled - Fired when tracker auto-enables due to Ralph pattern detection
 * @event statusBlockDetected - Fired when a RALPH_STATUS block is parsed
 * @event circuitBreakerUpdate - Fired when circuit breaker state changes
 * @event exitGateMet - Fired when dual-condition exit gate is met
 */
/**
 * RalphTracker - Parses terminal output to detect Ralph Wiggum loops and todos
 *
 * This class monitors Claude Code session output to detect:
 * 1. **Ralph Wiggum loop state** - Active loops, completion phrases, iteration counts
 * 2. **Todo list items** - From TodoWrite tool in various formats
 * 3. **Completion signals** - `<promise>PHRASE</promise>` tags
 *
 * ## Lifecycle
 *
 * The tracker is **DISABLED by default** and auto-enables when Ralph-related
 * patterns are detected (e.g., /ralph-loop:ralph-loop, <promise>, todos).
 * This reduces overhead for sessions not using autonomous loops.
 *
 * ## Completion Detection
 *
 * Uses occurrence-based detection to distinguish prompt from actual completion:
 * - 1st occurrence of `<promise>X</promise>`: Stored as expected phrase (likely in prompt)
 * - 2nd occurrence: Emits `completionDetected` event (actual completion)
 * - If loop already active: Emits immediately on first occurrence
 *
 * ## Sub-modules
 *
 * - `planTracker` - Plan task management, checkpoints, versioning
 * - `fixPlanWatcher` - @fix_plan.md file watching and parsing
 * - `stallDetector` - Iteration stall detection
 * - `statusParser` - RALPH_STATUS block parsing, circuit breaker
 *
 * ## Events
 *
 * - `loopUpdate` - Loop state changed (status, iteration, phrase)
 * - `todoUpdate` - Todo list modified (add, status change)
 * - `completionDetected` - Loop completion phrase detected
 * - `enabled` - Tracker auto-enabled from disabled state
 *
 * @extends EventEmitter
 * @example
 * ```typescript
 * const tracker = new RalphTracker();
 * tracker.on('completionDetected', (phrase) => {
 *   console.log('Loop completed with phrase:', phrase);
 * });
 * tracker.processTerminalData(ptyOutput);
 * ```
 */
export declare class RalphTracker extends EventEmitter {
    /** Plan task management sub-module */
    readonly planTracker: RalphPlanTracker;
    /** @fix_plan.md file watcher sub-module */
    readonly fixPlanWatcher: RalphFixPlanWatcher;
    /** Iteration stall detector sub-module */
    readonly stallDetector: RalphStallDetector;
    /** RALPH_STATUS block parser and circuit breaker sub-module */
    readonly statusParser: RalphStatusParser;
    /** Current state of the detected loop */
    private _loopState;
    /** Map of todo items by ID for O(1) lookup */
    private _todos;
    /** Buffer for incomplete lines from terminal data */
    private _lineBuffer;
    /**
     * Tracks occurrences of completion phrases.
     * Used to distinguish prompt echo (1st) from actual completion (2nd+).
     */
    private _completionPhraseCount;
    /** Timestamp of last cleanup check for throttling */
    private _lastCleanupTime;
    /** Debouncer for todoUpdate events */
    private _todoDeb;
    /** Debouncer for loopUpdate events */
    private _loopDeb;
    /** When true, prevents auto-enable on pattern detection */
    private _autoEnableDisabled;
    /** Maps task numbers from "✔ Task #N" format to their content for status updates */
    private _taskNumberToContent;
    /**
     * Buffer for partial promise tags split across PTY chunks.
     * Holds content after '<promise>' when closing tag hasn't arrived yet.
     * Max 256 chars to prevent unbounded growth from malformed tags.
     */
    private _partialPromiseBuffer;
    /** Maximum size of partial promise buffer */
    private static readonly MAX_PARTIAL_PROMISE_SIZE;
    /** Alternate completion phrases (P1-003: multi-phrase support) - Set for O(1) lookup */
    private _alternateCompletionPhrases;
    /** History of todo completion times (ms) for averaging */
    private _completionTimes;
    /** Maximum number of completion times to track */
    private static readonly MAX_COMPLETION_TIMES;
    /** Timestamp when todos started being tracked for this session */
    private _todosStartedAt;
    /** Map of todo ID to timestamp when it started (for duration tracking) */
    private _todoStartTimes;
    /** Last calculated completion confidence */
    private _lastCompletionConfidence;
    /** Manages periodic cleanup timers (todo expiry) */
    private cleanup;
    /** Confidence threshold for triggering completion (0-100) */
    private static readonly COMPLETION_CONFIDENCE_THRESHOLD;
    /**
     * Creates a new RalphTracker instance.
     * Starts in disabled state until Ralph patterns are detected.
     */
    constructor();
    /**
     * Forward all sub-module events through RalphTracker
     * so external consumers don't need to know about the split.
     */
    private _wireSubModuleEvents;
    /**
     * Initialize plan tasks from generated plan items.
     */
    initializePlanTasks(items: Array<{
        id?: string;
        content: string;
        priority?: 'P0' | 'P1' | 'P2' | null;
        verificationCriteria?: string;
        testCommand?: string;
        dependencies?: string[];
        tddPhase?: TddPhase;
        pairedWith?: string;
        complexity?: 'low' | 'medium' | 'high';
    }>): void;
    /**
     * Update a specific plan task's status, attempts, or error.
     */
    updatePlanTask(taskId: string, update: {
        status?: PlanTaskStatus;
        error?: string;
        incrementAttempts?: boolean;
    }): {
        success: boolean;
        task?: EnhancedPlanTask;
        error?: string;
    };
    /**
     * Add a new task to the plan.
     */
    addPlanTask(task: {
        content: string;
        priority?: 'P0' | 'P1' | 'P2';
        verificationCriteria?: string;
        dependencies?: string[];
        insertAfter?: string;
    }): {
        task: EnhancedPlanTask;
    };
    /**
     * Get all plan tasks.
     */
    getPlanTasks(): EnhancedPlanTask[];
    /**
     * Generate a checkpoint review.
     */
    generateCheckpointReview(): CheckpointReview;
    /**
     * Get plan version history.
     */
    getPlanHistory(): Array<{
        version: number;
        timestamp: number;
        summary: string;
        stats: {
            total: number;
            completed: number;
            failed: number;
        };
    }>;
    /**
     * Rollback to a previous plan version.
     */
    rollbackToVersion(version: number): {
        success: boolean;
        plan?: EnhancedPlanTask[];
        error?: string;
    };
    /**
     * Check if checkpoint review is due.
     */
    isCheckpointDue(): boolean;
    /**
     * Get current plan version.
     */
    get planVersion(): number;
    /**
     * Set the working directory and start watching @fix_plan.md.
     * @param workingDir - The session's working directory
     */
    setWorkingDir(workingDir: string): void;
    /**
     * Load @fix_plan.md from disk if it exists.
     */
    loadFixPlanFromDisk(): Promise<number>;
    /**
     * Stop watching @fix_plan.md.
     */
    stopWatchingFixPlan(): void;
    /**
     * When @fix_plan.md is active, treat it as the source of truth for todo status.
     */
    get isFileAuthoritative(): boolean;
    /**
     * Generate @fix_plan.md content from current todos.
     */
    generateFixPlanMarkdown(): string;
    /**
     * Parse @fix_plan.md content and import todos.
     * Replaces current todos with imported ones.
     *
     * @param content - Markdown content from @fix_plan.md
     * @returns Number of todos imported
     */
    importFixPlanMarkdown(content: string): number;
    /**
     * Start iteration stall detection timer.
     */
    startIterationStallDetection(): void;
    /**
     * Stop iteration stall detection timer.
     */
    stopIterationStallDetection(): void;
    /**
     * Get iteration stall metrics for monitoring.
     */
    getIterationStallMetrics(): {
        lastIterationChangeTime: number;
        stallDurationMs: number;
        warningThresholdMs: number;
        criticalThresholdMs: number;
        isWarned: boolean;
        currentIteration: number;
    };
    /**
     * Configure iteration stall thresholds.
     */
    configureIterationStallThresholds(warningMs: number, criticalMs: number): void;
    /**
     * Manually reset circuit breaker to CLOSED state.
     * @fires circuitBreakerUpdate
     */
    resetCircuitBreaker(): void;
    /**
     * Get current circuit breaker status.
     */
    get circuitBreakerStatus(): CircuitBreakerStatus;
    /**
     * Get last parsed RALPH_STATUS block.
     */
    get lastStatusBlock(): RalphStatusBlock | null;
    /**
     * Get cumulative stats from status blocks.
     */
    get cumulativeStats(): {
        filesModified: number;
        tasksCompleted: number;
        completionIndicators: number;
    };
    /**
     * Whether dual-condition exit gate has been met.
     */
    get exitGateMet(): boolean;
    /**
     * Add an alternate completion phrase (P1-003: multi-phrase support).
     */
    addAlternateCompletionPhrase(phrase: string): void;
    /**
     * Remove an alternate completion phrase.
     */
    removeAlternateCompletionPhrase(phrase: string): void;
    /**
     * Check if a phrase matches any valid completion phrase (primary or alternate).
     */
    isValidCompletionPhrase(phrase: string): boolean;
    /**
     * Find which completion phrase (primary or alternate) matches the given phrase.
     */
    private findMatchingCompletionPhrase;
    /**
     * Prevent auto-enable from pattern detection.
     */
    disableAutoEnable(): void;
    /**
     * Allow auto-enable from pattern detection.
     */
    enableAutoEnable(): void;
    /**
     * Whether auto-enable is disabled.
     */
    get autoEnableDisabled(): boolean;
    /**
     * Whether the tracker is enabled and actively monitoring output.
     */
    get enabled(): boolean;
    /**
     * Enable the tracker to start monitoring terminal output.
     * @fires enabled
     * @fires loopUpdate
     */
    enable(): void;
    /**
     * Disable the tracker to stop monitoring terminal output.
     * @fires loopUpdate
     */
    disable(): void;
    /**
     * Soft reset - clears state but keeps enabled status.
     * @fires loopUpdate
     * @fires todoUpdate
     */
    reset(): void;
    /**
     * Full reset - clears all state including enabled status.
     * @fires loopUpdate
     * @fires todoUpdate
     */
    fullReset(): void;
    /**
     * Clear all debounce timers.
     */
    private clearDebounceTimers;
    /**
     * Emit todoUpdate event with debouncing.
     */
    private emitTodoUpdateDebounced;
    /**
     * Emit loopUpdate event with debouncing.
     */
    private emitLoopUpdateDebounced;
    /**
     * Flush all pending debounced events immediately.
     */
    flushPendingEvents(): void;
    /**
     * Get a copy of the current loop state.
     */
    get loopState(): RalphTrackerState;
    /**
     * Calculate confidence score for a potential completion signal.
     */
    calculateCompletionConfidence(phrase: string, context?: string): CompletionConfidence;
    /**
     * Get all tracked todo items as an array.
     */
    get todos(): RalphTodoItem[];
    /**
     * Process raw terminal data to detect inner loop patterns.
     */
    processTerminalData(data: string): void;
    /**
     * Process pre-stripped terminal data (ANSI codes already removed).
     */
    processCleanData(cleanData: string): void;
    /**
     * Check if data contains patterns that should auto-enable the tracker.
     */
    private shouldAutoEnable;
    /**
     * Process a single line of terminal output.
     */
    private processLine;
    /**
     * Mark all tracked todos as completed and emit todoUpdate if any changed.
     * @returns true if any todo was updated
     */
    private completeAllTodos;
    /**
     * Detect "all tasks complete" messages.
     */
    private detectAllTasksComplete;
    /**
     * Detect individual task completion signals.
     */
    private detectTaskCompletion;
    /**
     * Check for multi-line patterns that might span line boundaries.
     */
    private checkMultiLinePatterns;
    /**
     * Detect completion phrases in a line.
     */
    private detectCompletionPhrase;
    /**
     * Handle a bare completion phrase (without XML tags).
     */
    private handleBareCompletionPhrase;
    /**
     * Handle a detected completion phrase.
     */
    private handleCompletionPhrase;
    /**
     * Check if two phrases match with fuzzy tolerance.
     */
    private isFuzzyPhraseMatch;
    /**
     * Validate a completion phrase and emit warnings if it's risky.
     */
    private validateCompletionPhrase;
    /**
     * Emit a phrase validation warning with a console message and event.
     */
    private emitValidationWarning;
    /**
     * Activate the loop if not already active.
     */
    private activateLoopIfNeeded;
    /**
     * Detect loop start and status indicators.
     */
    private detectLoopStatus;
    /**
     * Detect todo items in various formats from Claude Code output.
     */
    private detectTodoItems;
    /**
     * Convert a todo icon character to its corresponding status.
     */
    private iconToStatus;
    /**
     * Parse priority from todo content.
     */
    private parsePriority;
    /**
     * Add a new todo item or update an existing one.
     */
    private upsertTodo;
    /**
     * Normalize todo content for consistent matching.
     */
    private normalizeTodoContent;
    /**
     * Calculate similarity between two strings.
     */
    private calculateSimilarity;
    /**
     * Calculate bigram (Dice coefficient) similarity.
     */
    private calculateBigramSimilarity;
    /**
     * Find an existing todo that is similar to the given content.
     */
    private findSimilarTodo;
    /**
     * Estimate complexity of a todo based on content keywords.
     */
    private estimateComplexity;
    /**
     * Get estimated duration for a complexity level (ms).
     */
    private getEstimatedDuration;
    /**
     * Get average completion time from historical data.
     */
    private getAverageCompletionTime;
    /**
     * Record a todo completion for progress tracking.
     */
    private recordTodoCompletion;
    /**
     * Start tracking a todo for duration estimation.
     */
    private startTrackingTodo;
    /**
     * Get progress estimation for the todo list.
     */
    getTodoProgress(): RalphTodoProgress;
    /**
     * Generate a stable ID from todo content using content hashing.
     */
    private generateTodoId;
    /**
     * Find the todo item with the oldest detectedAt timestamp.
     */
    private findOldestTodo;
    /**
     * Conditionally run cleanup, throttled to CLEANUP_THROTTLE_MS.
     */
    private maybeCleanupExpiredTodos;
    /**
     * Remove todo items older than TODO_EXPIRY_MS.
     */
    private cleanupExpiredTodos;
    /**
     * Programmatically start a loop (external API).
     */
    startLoop(completionPhrase?: string, maxIterations?: number): void;
    /**
     * Update the maximum iteration count (external API).
     */
    setMaxIterations(maxIterations: number | null): void;
    /**
     * Configure the tracker from external state.
     */
    configure(config: {
        enabled?: boolean;
        completionPhrase?: string;
        maxIterations?: number;
    }): void;
    /**
     * Programmatically stop the loop (external API).
     */
    stopLoop(): void;
    /**
     * Enforce size limit on _taskNumberToContent map.
     */
    private enforceTaskMappingLimit;
    /**
     * Clear all state and disable the tracker.
     */
    clear(): void;
    /**
     * Get aggregated statistics about tracked todos.
     */
    getTodoStats(): {
        total: number;
        pending: number;
        inProgress: number;
        completed: number;
    };
    /**
     * Restore tracker state from persisted data.
     */
    restoreState(loopState: RalphTrackerState, todos: RalphTodoItem[]): void;
    /**
     * Clean up all resources and release memory.
     */
    destroy(): void;
}
//# sourceMappingURL=ralph-tracker.d.ts.map