/** * State Persistence Service * * Manages saving and restoring orchestrator state for * continuous operation across restarts. * * @module services/orchestrator/state-persistence */ import { OrchestratorState, ConversationState, TaskState, AgentState, ProjectState, SelfImprovementState, CheckpointReason, OrchestratorMode, ResumeInstructions } from '../../types/orchestrator-state.types.js'; /** * StatePersistenceService class * * Handles all state persistence operations including: * - Saving/loading orchestrator state * - Creating and restoring backups * - Generating resume instructions after restart * - Periodic checkpointing * * @example * ```typescript * const service = getStatePersistenceService(); * const previousState = await service.initialize(); * * if (previousState) { * const instructions = service.generateResumeInstructions(previousState); * // Resume tasks and conversations * } * ``` */ export declare class StatePersistenceService { private stateDir; private currentState; private checkpointTimer; private startTime; private restartCount; private initialized; private logger; /** * Create a new StatePersistenceService * * @param baseDir - Base directory for state storage (defaults to home directory) */ constructor(baseDir?: string); /** * Initialize the state persistence service * * Creates state directories and loads previous state if available. * * @returns Previous state if available, null otherwise */ initialize(): Promise; /** * Check if service is initialized * * @returns True if initialized */ isInitialized(): boolean; /** * Create empty state structure * * @returns A new empty orchestrator state */ private createEmptyState; /** * Create metadata for state * * @returns Metadata object with current system info */ private createMetadata; /** * Load state from disk * * @returns Previous state or null if not found */ private loadState; /** * Save current state to disk * * Uses atomic file write (temp file + rename) to prevent corruption. * * @param reason - Reason for this checkpoint */ saveState(reason?: CheckpointReason): Promise; /** * Create backup before risky operations * * @param label - Label for the backup (e.g., 'before-upgrade') * @returns Backup ID for restoration */ createBackup(label: string): Promise; /** * Restore from backup * * @param backupId - ID of backup to restore * @returns True if restoration succeeded */ restoreFromBackup(backupId: string): Promise; /** * List available backups * * @returns Array of backup IDs sorted by date (newest first) */ listBackups(): Promise; /** * Update conversation state * * Adds new conversation or updates existing one. * Automatically trims messages to MAX_PERSISTED_MESSAGES. * * @param conversation - Conversation state to update */ updateConversation(conversation: ConversationState): void; /** * Remove a conversation * * @param conversationId - ID of conversation to remove */ removeConversation(conversationId: string): void; /** * Update task state * * @param task - Task state to update */ updateTask(task: TaskState): void; /** * Remove a task * * @param taskId - ID of task to remove */ removeTask(taskId: string): void; /** * Update agent state * * @param agent - Agent state to update */ updateAgent(agent: AgentState): void; /** * Remove an agent * * @param sessionName - Session name of agent to remove */ removeAgent(sessionName: string): void; /** * Update project state * * @param project - Project state to update */ updateProject(project: ProjectState): void; /** * Remove a project * * @param projectId - ID of project to remove */ removeProject(projectId: string): void; /** * Update self-improvement state * * @param state - Self-improvement state to set */ updateSelfImprovement(state: SelfImprovementState): void; /** * Set the orchestrator's runtime mode (Onboarding v3 — B2). * * Called by the orc bootstrap path (`crewly-agent-runtime.service`) * after cold-start detection. Idempotent — repeated calls with the same * mode are no-ops aside from a debug log. The mode is persisted on the * next checkpoint (`saveState`), which the bootstrap path triggers * explicitly so a restart mid-conversation resumes in the right mode. * * @param mode - The new orchestrator mode */ setMode(mode: OrchestratorMode): void; /** * Get the orchestrator's current runtime mode. * * Returns `DEFAULT_ORCHESTRATOR_MODE` when state is uninitialized or the * field is missing; never returns undefined so callers can branch * unambiguously on the union value. * * @returns Current orchestrator mode (defaults to `'normal'`) */ getMode(): OrchestratorMode; /** * Clear self-improvement state */ clearSelfImprovement(): void; /** * Generate resume instructions from previous state * * Creates instructions for the orchestrator to resume work * after a restart. * * @param previousState - The state from before restart * @returns Instructions for resuming work */ generateResumeInstructions(previousState: OrchestratorState): ResumeInstructions; /** * Start periodic checkpoint timer */ private startPeriodicCheckpoint; /** * Stop periodic checkpointing */ stopPeriodicCheckpoint(): void; /** * Get current state (for inspection) * * @returns Current orchestrator state or null */ getState(): OrchestratorState | null; /** * Get state directory path * * @returns Path to state directory */ getStateDir(): string; /** * Prepare for shutdown * * Stops periodic checkpointing and saves final state. */ prepareForShutdown(): Promise; /** * Migrate state from older version * * @param oldState - State from older version * @returns Migrated state or null if migration failed */ private migrateState; /** * Clean up old backups * * Keeps the most recent backups and deletes older ones. * * @param keepCount - Number of backups to keep (default: 10) */ cleanupOldBackups(keepCount?: number): Promise; } /** * Get singleton instance * * @returns StatePersistenceService instance */ export declare function getStatePersistenceService(): StatePersistenceService; /** * Reset instance (for testing) */ export declare function resetStatePersistenceService(): void; //# sourceMappingURL=state-persistence.service.d.ts.map