/**
 * Steward Scheduler Service
 *
 * This service executes stewards on schedule (cron) or in response to events.
 * It manages the lifecycle of scheduled steward executions and tracks execution history.
 *
 * Key features:
 * - Cron-based scheduling using node-cron
 * - Event-driven triggers with condition evaluation
 * - Execution history tracking
 * - Graceful shutdown support
 *
 * TB-O23: Steward Scheduler Service
 *
 * @module
 */
import type { EntityId, Timestamp } from '@stoneforge/core';
import type { StewardTrigger, CronTrigger, EventTrigger } from '../types/index.js';
import type { AgentRegistry, AgentEntity } from './agent-registry.js';
/**
 * Result of a steward execution
 */
export interface StewardExecutionResult {
    /** Whether the execution succeeded */
    readonly success: boolean;
    /** Error message if execution failed */
    readonly error?: string;
    /** Output from the steward (summary or relevant data) */
    readonly output?: string;
    /** Duration of execution in ms */
    readonly durationMs: number;
    /** Items processed (if applicable) */
    readonly itemsProcessed?: number;
}
/**
 * Entry in the execution history
 */
export interface StewardExecutionEntry {
    /** Unique execution ID */
    readonly executionId: string;
    /** The steward entity ID */
    readonly stewardId: EntityId;
    /** Steward name for convenience */
    readonly stewardName: string;
    /** The trigger that caused the execution */
    readonly trigger: StewardTrigger;
    /** Whether this was a manual execution */
    readonly manual: boolean;
    /** Timestamp when execution started */
    readonly startedAt: Timestamp;
    /** Timestamp when execution completed */
    readonly completedAt?: Timestamp;
    /** Execution result (set when completed) */
    readonly result?: StewardExecutionResult;
    /** Event context if triggered by event */
    readonly eventContext?: Record<string, unknown>;
}
/**
 * Filter options for querying execution history
 */
export interface ExecutionHistoryFilter {
    /** Filter by steward ID */
    readonly stewardId?: EntityId;
    /** Filter by trigger type */
    readonly triggerType?: 'cron' | 'event';
    /** Filter by success/failure */
    readonly success?: boolean;
    /** Filter by date range (start) */
    readonly startedAfter?: Timestamp;
    /** Filter by date range (end) */
    readonly startedBefore?: Timestamp;
    /** Maximum number of entries to return */
    readonly limit?: number;
}
/**
 * Configuration for the scheduler
 */
export interface StewardSchedulerConfig {
    /** Maximum execution history entries to keep per steward */
    readonly maxHistoryPerSteward?: number;
    /** Default timeout for steward execution in ms */
    readonly defaultTimeoutMs?: number;
    /** Whether to start scheduled stewards immediately */
    readonly startImmediately?: boolean;
}
/**
 * Information about a scheduled job
 */
export interface ScheduledJobInfo {
    /** The steward entity ID */
    readonly stewardId: EntityId;
    /** Steward name */
    readonly stewardName: string;
    /** The cron trigger */
    readonly trigger: CronTrigger;
    /** Whether the job is currently running */
    readonly isRunning: boolean;
    /** Next scheduled execution time (if available) */
    readonly nextRunAt?: Date;
    /** Last execution time */
    readonly lastRunAt?: Timestamp;
}
/**
 * Event subscription info
 */
export interface EventSubscriptionInfo {
    /** The steward entity ID */
    readonly stewardId: EntityId;
    /** Steward name */
    readonly stewardName: string;
    /** The event trigger */
    readonly trigger: EventTrigger;
    /** Whether currently listening */
    readonly isActive: boolean;
}
/**
 * Steward execution function type
 * This is what actually runs the steward's logic
 */
export type StewardExecutor = (steward: AgentEntity, context: {
    trigger: StewardTrigger;
    eventContext?: Record<string, unknown>;
}) => Promise<StewardExecutionResult>;
/**
 * Steward Scheduler Service interface for executing stewards on schedule or events.
 *
 * The service provides methods for:
 * - Starting/stopping scheduled executions
 * - Publishing events for event-triggered stewards
 * - Manual steward execution
 * - Execution history queries
 */
export interface StewardScheduler {
    /**
     * Starts the scheduler, activating all cron jobs and event listeners
     * for registered stewards.
     */
    start(): Promise<void>;
    /**
     * Stops the scheduler, cleaning up all cron jobs and event listeners.
     * Running executions are allowed to complete.
     */
    stop(): Promise<void>;
    /**
     * Whether the scheduler is currently running
     */
    isRunning(): boolean;
    /**
     * Registers a steward with the scheduler.
     * This sets up cron jobs and event subscriptions based on the steward's triggers.
     *
     * @param stewardId - The steward entity ID
     * @returns True if registered successfully
     */
    registerSteward(stewardId: EntityId): Promise<boolean>;
    /**
     * Unregisters a steward from the scheduler.
     * This removes cron jobs and event subscriptions.
     *
     * @param stewardId - The steward entity ID
     * @returns True if unregistered successfully
     */
    unregisterSteward(stewardId: EntityId): Promise<boolean>;
    /**
     * Refreshes a steward's registration (useful if triggers changed).
     *
     * @param stewardId - The steward entity ID
     */
    refreshSteward(stewardId: EntityId): Promise<void>;
    /**
     * Registers all stewards from the agent registry.
     */
    registerAllStewards(): Promise<number>;
    /**
     * Manually triggers a steward execution.
     *
     * @param stewardId - The steward to execute
     * @param context - Optional context data
     * @returns The execution result
     */
    executeSteward(stewardId: EntityId, context?: Record<string, unknown>): Promise<StewardExecutionResult>;
    /**
     * Publishes an event that may trigger stewards.
     * Stewards with matching event triggers will be executed.
     *
     * @param eventName - The event name (e.g., 'task_completed')
     * @param eventData - Event data for condition evaluation
     * @returns Number of stewards triggered
     */
    publishEvent(eventName: string, eventData: Record<string, unknown>): Promise<number>;
    /**
     * Gets scheduled job information for a steward.
     */
    getScheduledJobs(stewardId?: EntityId): ScheduledJobInfo[];
    /**
     * Gets event subscription information.
     */
    getEventSubscriptions(stewardId?: EntityId): EventSubscriptionInfo[];
    /**
     * Gets execution history.
     */
    getExecutionHistory(filter?: ExecutionHistoryFilter): StewardExecutionEntry[];
    /**
     * Gets the last execution for a steward.
     */
    getLastExecution(stewardId: EntityId): StewardExecutionEntry | undefined;
    /**
     * Gets statistics about steward executions.
     */
    getStats(): StewardSchedulerStats;
    /**
     * Subscribe to scheduler events.
     */
    on(event: 'execution:started', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'execution:completed', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'execution:failed', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'steward:registered', listener: (stewardId: EntityId) => void): void;
    on(event: 'steward:unregistered', listener: (stewardId: EntityId) => void): void;
    /**
     * Unsubscribe from scheduler events.
     */
    off(event: string, listener: (...args: unknown[]) => void): void;
}
/**
 * Statistics about steward executions
 */
export interface StewardSchedulerStats {
    /** Number of registered stewards */
    readonly registeredStewards: number;
    /** Number of active cron jobs */
    readonly activeCronJobs: number;
    /** Number of active event subscriptions */
    readonly activeEventSubscriptions: number;
    /** Total executions */
    readonly totalExecutions: number;
    /** Successful executions */
    readonly successfulExecutions: number;
    /** Failed executions */
    readonly failedExecutions: number;
    /** Currently running executions */
    readonly runningExecutions: number;
}
/**
 * Validates a cron expression.
 * This is a basic validation - we check the format but not all edge cases.
 */
export declare function isValidCronExpression(schedule: string): boolean;
/**
 * Calculates the next run time for a cron expression.
 * This is a simplified implementation - for production use node-cron handles this.
 */
export declare function getNextCronRunTime(_schedule: string): Date | undefined;
/**
 * Evaluates a simple condition expression against event data.
 * Supports basic JavaScript-like expressions with property access.
 *
 * Examples:
 * - "task.status === 'closed'"
 * - "task.assignedAgent?.role === 'worker'"
 * - "branch.tests === 'passing'"
 */
export declare function evaluateCondition(condition: string, context: Record<string, unknown>): boolean;
/**
 * Implementation of the Steward Scheduler Service.
 */
export declare class StewardSchedulerImpl implements StewardScheduler {
    private readonly agentRegistry;
    private readonly config;
    private readonly executor;
    private readonly emitter;
    private running;
    private cronJobs;
    private eventSubscriptions;
    private executionHistory;
    private runningExecutions;
    private executionCounter;
    constructor(agentRegistry: AgentRegistry, executor: StewardExecutor, config?: StewardSchedulerConfig);
    start(): Promise<void>;
    stop(): Promise<void>;
    isRunning(): boolean;
    registerSteward(stewardId: EntityId): Promise<boolean>;
    unregisterSteward(stewardId: EntityId): Promise<boolean>;
    refreshSteward(stewardId: EntityId): Promise<void>;
    registerAllStewards(): Promise<number>;
    executeSteward(stewardId: EntityId, context?: Record<string, unknown>): Promise<StewardExecutionResult>;
    publishEvent(eventName: string, eventData: Record<string, unknown>): Promise<number>;
    getScheduledJobs(stewardId?: EntityId): ScheduledJobInfo[];
    getEventSubscriptions(stewardId?: EntityId): EventSubscriptionInfo[];
    getExecutionHistory(filter?: ExecutionHistoryFilter): StewardExecutionEntry[];
    getLastExecution(stewardId: EntityId): StewardExecutionEntry | undefined;
    getStats(): StewardSchedulerStats;
    on(event: 'execution:started', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'execution:completed', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'execution:failed', listener: (entry: StewardExecutionEntry) => void): void;
    on(event: 'steward:registered', listener: (stewardId: EntityId) => void): void;
    on(event: 'steward:unregistered', listener: (stewardId: EntityId) => void): void;
    off(event: string, listener: (...args: unknown[]) => void): void;
    private startCronJob;
    private scheduleNextRun;
    private stopCronJob;
    /**
     * Calculates the next fire time for a cron expression after the given date.
     * Supports 5-field cron (minute hour dom month dow) with optional 6th seconds field (ignored).
     * Supports: *, specific values, step (* /N), range (N-M), and lists (N,M).
     * Returns null for invalid expressions.
     */
    getNextCronTime(schedule: string, after?: Date): Date | null;
    /**
     * Parses a single cron field into a set of valid values.
     * Supports: *, N, N-M, N,M, * /N, N-M/S
     */
    private parseCronField;
    private runExecution;
    private addHistoryEntry;
    private updateHistoryEntry;
    private pruneHistory;
}
/**
 * Creates a StewardScheduler instance
 *
 * @param agentRegistry - The agent registry for looking up stewards
 * @param executor - Function to execute steward logic
 * @param config - Optional configuration
 */
export declare function createStewardScheduler(agentRegistry: AgentRegistry, executor: StewardExecutor, config?: StewardSchedulerConfig): StewardScheduler;
/**
 * Creates a default steward executor that delegates to the appropriate
 * service based on the steward's focus.
 *
 * This is a placeholder - the actual executor would integrate with:
 * - MergeStewardService for 'merge' focus
 * - HealthStewardService for 'health' focus (TB-O24)
 * - etc.
 */
export declare function createDefaultStewardExecutor(): StewardExecutor;
//# sourceMappingURL=steward-scheduler.d.ts.map