/**
 * @fileoverview Persistent JSON state storage for Codeman.
 *
 * Persists application state with debounced writes (500ms) to prevent excessive disk I/O.
 * State is split into two files:
 * - `~/.codeman/state.json` — main app state (sessions, tasks, config, global stats)
 * - `~/.codeman/state-inner.json` — Ralph loop state per session (changes rapidly)
 *
 * Key exports:
 * - `StateStore` class — singleton store with circuit breaker for save failures
 * - `getStore(filePath?)` — factory/singleton accessor
 *
 * Key methods: `getState()`, `getSessions()`, `setSession()`, `getConfig()`,
 * `setConfig()`, `getGlobalStats()`, `getAggregateStats()`, `getTokenStats()`,
 * `getDailyStats()`, `getRalphState()`, `setRalphState()`, `save()`, `saveNow()`
 *
 * Auto-migrates legacy `~/.claudeman/` → `~/.codeman/` on first load.
 *
 * @dependencies types (AppState, RalphSessionState, GlobalStats, TokenStats),
 *   utils (Debouncer, MAX_SESSION_TOKENS)
 * @consumedby session-manager, ralph-loop, web/server, respawn-controller,
 *   hooks-config, and most subsystems
 *
 * @module state-store
 */
import { AppState, RalphSessionState, GlobalStats, TokenStats, TokenUsageEntry } from './types.js';
export declare class StateStore {
    private state;
    private filePath;
    private saveDeb;
    private dirty;
    private dirtySessions;
    private cachedSessionJsons;
    private ralphStates;
    private ralphStatePath;
    private ralphStateSaveDeb;
    private ralphStateDirty;
    private consecutiveSaveFailures;
    private circuitBreakerOpen;
    private _saveInFlight;
    constructor(filePath?: string);
    private _mergeWithInitialState;
    private _resetCircuitBreaker;
    private ensureDir;
    private load;
    /**
     * Schedules a debounced save.
     * Multiple calls within 500ms are batched into a single disk write.
     * Uses async I/O to avoid blocking the event loop.
     */
    save(): void;
    /**
     * Async version of saveNow — used by the debounced save() path.
     * Uses non-blocking fs.promises to avoid blocking the event loop during
     * the debounced write cycle. For synchronous shutdown flush, use saveNow().
     *
     * Guards against concurrent execution: if a save is already in flight,
     * waits for it to complete then re-checks dirty flag before starting another.
     */
    saveNowAsync(): Promise<void>;
    /**
     * Assemble JSON string with incremental per-session caching.
     * Only dirty sessions are re-serialized; clean sessions use cached JSON fragments.
     */
    private assembleStateJson;
    private updateDirtySessionCache;
    private pruneStaleCacheEntries;
    private buildPartialJson;
    private serializeState;
    private _doSaveAsync;
    /**
     * Synchronous immediate write to disk using atomic write pattern.
     * Used by flushAll() during shutdown when async is not appropriate.
     * Prefer saveNowAsync() for normal operation.
     */
    saveNow(): void;
    /**
     * Attempt to recover state from backup file.
     * Call this if main state file is corrupt.
     */
    recoverFromBackup(): boolean;
    /**
     * Reset the circuit breaker (for manual intervention).
     */
    resetCircuitBreaker(): void;
    /** Flushes any pending main state save. Call before shutdown. */
    flush(): void;
    /** Returns the full application state object. */
    getState(): AppState;
    /** Returns all session states keyed by session ID. */
    getSessions(): Record<string, import("./types.js").SessionState>;
    /** Returns a session state by ID, or null if not found. */
    getSession(id: string): import("./types.js").SessionState;
    /** Sets a session state and triggers a debounced save. */
    setSession(id: string, session: AppState['sessions'][string]): void;
    /** Removes a session state and triggers a debounced save. */
    removeSession(id: string): void;
    /**
     * Cleans up stale sessions from state that don't have corresponding active sessions.
     * @param activeSessionIds - Set of currently active session IDs
     * @returns Number of sessions cleaned up
     */
    cleanupStaleSessions(activeSessionIds: Set<string>): {
        count: number;
        cleaned: Array<{
            id: string;
            name?: string;
        }>;
    };
    /** Returns all task states keyed by task ID. */
    getTasks(): Record<string, import("./types.js").TaskState>;
    /** Returns a task state by ID, or null if not found. */
    getTask(id: string): import("./types.js").TaskState;
    /** Sets a task state and triggers a debounced save. */
    setTask(id: string, task: AppState['tasks'][string]): void;
    /** Removes a task state and triggers a debounced save. */
    removeTask(id: string): void;
    /** Returns the Ralph Loop state. */
    getRalphLoopState(): import("./types.js").RalphLoopState;
    /** Updates Ralph Loop state (partial merge) and triggers a debounced save. */
    setRalphLoopState(ralphLoop: Partial<AppState['ralphLoop']>): void;
    /** Returns the orchestrator loop state, or null if never initialized. */
    getOrchestratorState(): import("./types.js").OrchestratorPersistState | null;
    /** Updates orchestrator loop state (partial merge) and triggers a debounced save. */
    setOrchestratorState(orchestrator: Partial<NonNullable<AppState['orchestrator']>>): void;
    /** Clears orchestrator state and triggers a debounced save. */
    clearOrchestratorState(): void;
    /** Returns the application configuration. */
    getConfig(): import("./types.js").AppConfig;
    /** Updates configuration (partial merge) and triggers a debounced save. */
    setConfig(config: Partial<AppState['config']>): void;
    /** Resets all state to initial values and saves immediately. */
    reset(): void;
    /** Returns global stats, creating initial stats if needed. */
    getGlobalStats(): GlobalStats;
    /**
     * Adds tokens and cost to global stats.
     * Call when a session is deleted to preserve its usage in lifetime stats.
     */
    addToGlobalStats(inputTokens: number, outputTokens: number, cost: number): void;
    /** Increments the total sessions created counter. */
    incrementSessionsCreated(): void;
    /**
     * Returns aggregate stats combining global (deleted sessions) + active sessions.
     * @param activeSessions Map of active session states
     */
    getAggregateStats(activeSessions: Record<string, {
        inputTokens?: number;
        outputTokens?: number;
        totalCost?: number;
    }>): {
        totalInputTokens: number;
        totalOutputTokens: number;
        totalCost: number;
        totalSessionsCreated: number;
        activeSessionsCount: number;
    };
    /** Maximum days to keep in daily history */
    private static readonly MAX_DAILY_HISTORY;
    /**
     * Get or initialize token stats from state.
     */
    getTokenStats(): TokenStats;
    /**
     * Get today's date string in YYYY-MM-DD format.
     */
    private getTodayDateString;
    /**
     * Calculate estimated cost from tokens using Claude Opus pricing.
     * Input: $15/M tokens, Output: $75/M tokens
     */
    private calculateEstimatedCost;
    private dailySessionIds;
    private dailySessionDate;
    /**
     * Record token usage for today.
     * Accumulates tokens to today's entry, creating it if needed.
     * @param inputTokens Input tokens to add
     * @param outputTokens Output tokens to add
     * @param sessionId Optional session ID for unique session counting
     */
    recordDailyUsage(inputTokens: number, outputTokens: number, sessionId?: string): void;
    /**
     * Get daily stats for display.
     * @param days Number of days to return (default: 30)
     * @returns Array of daily entries, most recent first
     */
    getDailyStats(days?: number): TokenUsageEntry[];
    private loadRalphStates;
    private saveRalphStates;
    /**
     * Immediate save for inner states using atomic write pattern.
     * Writes to temp file first, then renames to prevent corruption on crash.
     */
    private saveRalphStatesNow;
    /** Returns inner state for a session, or null if not found. */
    getRalphState(sessionId: string): RalphSessionState | null;
    /** Sets inner state for a session and triggers a debounced save. */
    setRalphState(sessionId: string, state: RalphSessionState): void;
    /**
     * Updates inner state for a session (partial merge).
     * Creates initial state if none exists.
     * @returns The updated inner state.
     */
    updateRalphState(sessionId: string, updates: Partial<RalphSessionState>): RalphSessionState;
    /** Removes inner state for a session and triggers a debounced save. */
    removeRalphState(sessionId: string): void;
    /** Returns a copy of all inner states as a Map. */
    getAllRalphStates(): Map<string, RalphSessionState>;
    /** Flushes all pending saves (main and inner state). Call before shutdown. */
    flushAll(): void;
}
/**
 * Gets or creates the singleton StateStore instance.
 * @param filePath Optional custom file path (only used on first call).
 */
export declare function getStore(filePath?: string): StateStore;
//# sourceMappingURL=state-store.d.ts.map