/**
 * ReconcilerService — The "CPU" of Crewly V3
 *
 * The Reconciler periodically and on-demand recomputes system truth from
 * durable state. It does NOT trust event delivery — it reads state and
 * determines what should be true.
 *
 * Two-level loop:
 * - Fast loop (10s): Lease expiry + agent health only
 * - Full loop (60s): Complete scan of all Requests, WorkItems, Claims
 *
 * Performance budget: single reconcile < 3s (CEO requirement).
 *
 * @module services/reconciler/reconciler.service
 */
import type { ReconcileResult, ReconcileCorrection, ReconcilerConfig, ReconcilerStatus, WakeAction, WorkItem, Request, TaskClaim } from '../../types/v2/index.js';
import type { AgentHealth } from './reconcile-rules.js';
/**
 * Interface for providing data to the Reconciler.
 * Abstracts over the actual storage/service layer so the Reconciler
 * can be tested independently.
 */
export interface ReconcilerDataProvider {
    /** Get all non-terminal WorkItems */
    getActiveWorkItems(): Promise<WorkItem[]>;
    /** Get all WorkItems for a specific Request */
    getWorkItemsForRequest(requestId: string): Promise<WorkItem[]>;
    /** Get all non-terminal Requests */
    getActiveRequests(): Promise<Request[]>;
    /** Get all active TaskClaims */
    getActiveClaims(): Promise<TaskClaim[]>;
    /** Get health info for all known agents */
    getAgentHealthMap(): Promise<Map<string, AgentHealth>>;
    /** Apply a correction — update an entity's status */
    applyCorrection(correction: ReconcileCorrection): Promise<void>;
    /** Release a WorkItem back to the task pool */
    releaseToPool(workItemId: string, reason: string): Promise<void>;
    /** Re-queue a WorkItem (increment retryCount, set status to queued) */
    requeueWorkItem(workItemId: string): Promise<void>;
    /** Mark a claim as 'expiring' (lease expired, within grace period) */
    markClaimExpiring(claimId: string): Promise<void>;
    /** Revoke a claim and release its work item back to the pool */
    revokeClaimAndRelease(claimId: string, reason: string): Promise<void>;
    /** Get all available (queued, unclaimed) WorkItems from the task pool */
    getAvailablePoolItems?(): Promise<WorkItem[]>;
    /** Execute a wake action — rehydrate a suspended agent or start an inactive one */
    executeWakeAction?(action: WakeAction): Promise<boolean>;
    /** Backfill token usage data on completed WorkItems that have 0 tokens */
    backfillTokenUsage?(): Promise<number>;
    /**
     * Emit `task:queued_too_long` events for WIs that have crossed the
     * staleness threshold. Per-WI dedup is the provider's responsibility.
     * Self-heal fix #2 (2026-05-20).
     */
    broadcastStaleQueuedWIs?(staleWorkItems: ReadonlyArray<{
        id: string;
        target?: string;
        owner?: string;
        createdAt: string;
    }>): void;
    /**
     * Release the dedup entry for any WI in the provider's internal map
     * that is no longer in the currently-queued set. Called by the
     * reconciler each pass so a WI that became un-stuck (claimed,
     * completed, cancelled) and later re-becomes stuck gets a fresh
     * first-fire instead of being silenced by stale dedup state.
     */
    clearResolvedStuckWiDedup?(currentlyQueuedIds: ReadonlySet<string>): void;
}
export declare class ReconcilerService {
    private config;
    private dataProvider;
    private fastLoopTimer;
    private fullLoopTimer;
    private history;
    private isRunning;
    private totalPasses;
    private totalCorrections;
    /**
     * Creates a new ReconcilerService.
     *
     * @param dataProvider - Provides data access and mutation capabilities
     * @param config - Optional configuration override
     */
    constructor(dataProvider: ReconcilerDataProvider, config?: Partial<ReconcilerConfig>);
    /**
     * Start the reconciliation loops (fast + full).
     * Called during backend startup.
     */
    start(): void;
    /**
     * Stop the reconciliation loops. Called during graceful shutdown.
     */
    stop(): void;
    /**
     * Full reconciliation pass — scans all entities.
     * Called on startup, periodically (60s), and manually via API.
     *
     * @returns The reconciliation result
     */
    runFull(): Promise<ReconcileResult>;
    /**
     * Fast reconciliation pass — checks leases, agent health, and Hybrid Wake.
     * Called frequently (every 10s) with minimal overhead.
     *
     * @returns The reconciliation result
     */
    runFast(): Promise<ReconcileResult>;
    /**
     * Targeted reconciliation for a single Request.
     * Called when a specific Request's state may have changed.
     *
     * @param requestId - The Request ID to reconcile
     */
    reconcileRequest(requestId: string): Promise<ReconcileResult>;
    /**
     * Returns current Reconciler status for API exposure.
     *
     * @returns Current status including last result, config, and counters
     */
    getStatus(): ReconcilerStatus;
    /**
     * Returns recent reconciliation history.
     *
     * @param limit - Maximum number of results to return
     * @returns Array of recent ReconcileResults (newest first)
     */
    getHistory(limit?: number): ReconcileResult[];
    /**
     * Updates the Reconciler configuration at runtime.
     *
     * @param updates - Partial configuration to merge
     */
    updateConfig(updates: Partial<ReconcilerConfig>): void;
    /**
     * Executes a reconciliation pass with timing, error handling, and history tracking.
     *
     * @param type - The type of reconciliation
     * @param logic - The reconciliation logic to execute
     * @returns The completed ReconcileResult
     */
    private executeReconcile;
    /**
     * Applies corrections by calling the data provider.
     * Handles errors gracefully — a failed correction doesn't stop the pass.
     *
     * @param corrections - Corrections to apply
     * @param result - The ReconcileResult to accumulate errors into
     */
    private applyCorrections;
    /**
     * Runs Hybrid Wake logic: detects unclaimed tasks in the pool and
     * wakes dormant agents (suspended → rehydrate, inactive → start).
     *
     * Only runs if the data provider supports pool item retrieval and wake execution.
     *
     * @param workItems - All active WorkItems (used as fallback if no pool provider)
     * @param agentHealthMap - Map of agent session → health info
     * @param result - The ReconcileResult to accumulate wake actions into
     */
    private runHybridWake;
}
//# sourceMappingURL=reconciler.service.d.ts.map