/**
 * Shared orchestrator bootstrap logic.
 *
 * Both server.ts (platform/hybrid) and standalone.ts (independent) delegate to
 * bootstrapOrchestrator() for all startup/shutdown work that is identical
 * between the two modes. Mode-specific behavior is injected via the
 * OrchestratorHooks interface.
 *
 * This eliminates ~1300 lines of duplication that previously existed across
 * the two entry points.
 */
import { type ColdStore } from '@kici-dev/shared';
import type { AppConfig } from './config.js';
import { ConfigReloader } from './config/reload.js';
import { AgentRegistry } from './agent/registry.js';
import { JobQueue } from './queue/job-queue.js';
import { EventLogWriter } from './webhook/event-log.js';
import { AccessLogWriter } from './audit/access-log.js';
import { Dispatcher } from './agent/dispatcher.js';
import { LockFileCache } from './lockfile-cache.js';
import { DedupCache } from './webhook/dedup.js';
import { ObserverRegistry } from './ws/observer-registry.js';
import { AgentMetricsAggregator } from './metrics/agent-metrics-aggregator.js';
import { SourceLocationStore } from './app.js';
import { type PeerHeartbeat } from '@kici-dev/engine';
import { ScalerManager } from './scaler/index.js';
import type { ScalerConfig } from './scaler/index.js';
import type { CacheStorage } from './storage/index.js';
import { SourceCache, BuildCoordinator, DepCache, UserCache, DispatchCacheRefTracker, PendingBuildTracker, PendingInitTracker, PendingDynamicTracker } from './cache/index.js';
import { CheckRunReporter } from './reporting/check-run-reporter.js';
import { StepLogBuffer } from './reporting/step-log-buffer.js';
import { type LogStorage } from './reporting/log-storage.js';
import { ExecutionTracker, type ExecutionTrackerDeps } from './reporting/execution-tracker.js';
import { LogWriter } from './reporting/log-writer.js';
import { PeerRegistry, PeerClient, createPeerHandler, RaftNode, OrphanRecovery, RunCoordinator } from './cluster/index.js';
import { SourceStore, SourceManager } from './sources/index.js';
import { PgSecretStore, AuditLogger, SecretResolver } from './secrets/index.js';
import type { SecretStore } from '@kici-dev/engine';
import type { AdminRouteDeps } from './routes/admin.js';
import { AgentTokenStore } from './agent/token-store.js';
import { OwnershipTracker } from './agent/ownership-tracker.js';
import { EventStore } from './events/event-store.js';
import { EventRouter } from './events/event-router.js';
import { EventEmitter } from './events/event-emitter.js';
import { TrustStore } from './events/trust-store.js';
import { GenericSourceManager } from './webhook/generic-sources.js';
import { GenericSourcesChangeListener } from './webhook/generic-sources-listener.js';
import { RegistrationStore } from './registration/registration-store.js';
import { RegistrationIndex } from './registration/registration-index.js';
import { CronScheduler } from './cron/cron-scheduler.js';
import { ProviderRegistry } from './provider-registry.js';
import { JoinHandler } from './cluster/join-handler.js';
import type { Kysely } from 'kysely';
import type { Database } from './db/types.js';
import type pg from 'pg';
/**
 * All subsystems that are created during bootstrap.
 * Passed to hooks so mode-specific code can wire callbacks.
 */
export interface OrchestratorSubsystems {
    config: AppConfig;
    db: Kysely<Database>;
    pool: pg.Pool;
    providerRegistry: ProviderRegistry;
    agentRegistry: AgentRegistry;
    dispatcher: Dispatcher;
    queue: JobQueue;
    scalerManager: ScalerManager | null;
    scalerConfig: ScalerConfig | null;
    cacheStorage: CacheStorage | undefined;
    sourceCache: SourceCache | undefined;
    depCache: DepCache | undefined;
    userCache: UserCache | undefined;
    /** Server-side jobId -> user-cache-namespace store, written at dispatch, read by the agent-WS handler. */
    dispatchCacheRefs: DispatchCacheRefTracker;
    buildCoordinator: BuildCoordinator | undefined;
    pendingBuilds: PendingBuildTracker | undefined;
    pendingInits: PendingInitTracker;
    pendingDynamics: PendingDynamicTracker;
    checkRunReporter: CheckRunReporter;
    stepLogBuffer: StepLogBuffer;
    sourceLocationStore: SourceLocationStore;
    logStorage: LogStorage;
    logWriter: LogWriter;
    observerRegistry: ObserverRegistry;
    executionTracker: ExecutionTracker;
    secretResolver: SecretResolver | null;
    adminDeps: AdminRouteDeps | undefined;
    pgSecretStore: PgSecretStore | undefined;
    tokenStore: AgentTokenStore;
    ownershipTracker: OwnershipTracker;
    lockFileCache: LockFileCache;
    dedup: DedupCache;
    eventRouter: EventRouter;
    /**
     * Event store for custom internal events (system + custom). Exposed
     * here so the dashboard handler can serve the per-org DLQ surface
     * (list / count / retry / discard) over the WS relay.
     */
    eventStore: EventStore;
    eventEmitter: EventEmitter;
    genericSourceManager: GenericSourceManager;
    trustStore: TrustStore;
    registrationStore: RegistrationStore;
    registrationIndex: RegistrationIndex;
    cronScheduler: CronScheduler;
    peerRegistry: PeerRegistry;
    raft: RaftNode;
    coordinator: RunCoordinator;
    orphanRecovery: OrphanRecovery;
    peerHandler: ReturnType<typeof createPeerHandler>;
    peerClients: Map<string, PeerClient>;
    getLocalInventory: () => Omit<PeerHeartbeat, 'type'>;
    broadcastHeartbeatToAllPeers: () => void;
    broadcastAgentTokenRevoke: (tokenId: string) => void;
    joinHandler: JoinHandler;
    configReloader: ConfigReloader;
    localConfigVersion: number;
    sourceStore: SourceStore;
    sourceManager: SourceManager;
    /**
     * Generic-webhook-source hot-reload listener. Exposed so the platform-mode
     * boot can wire its `onChange` to re-push the full source list to the
     * Platform when a generic source is added/removed at runtime.
     */
    genericSourcesChangeListener: GenericSourcesChangeListener;
    /** Inbound webhook delivery log writer (event_log table + object-storage payloads). */
    eventLogWriter: EventLogWriter;
    /** Access log writer (read + mutation attribution for dashboard + admin). */
    accessLogWriter: AccessLogWriter;
    /**
     * Long-lived cold-store handle. Read paths (dashboard, CLI) use this
     * for transparent fallback to S3 when a row has aged out of PG. The
     * scheduled archive cycle constructs its own ephemeral instance per
     * tick (so SIGHUP-driven config reload picks up new bucket / prefix
     * values without a restart) — these two instances are independent.
     * `null` when cold-store is not enabled in the env.
     */
    coldStore: ColdStore | null;
    /**
     * In-memory aggregator for agent-pushed metrics. Constructed once at
     * subsystem-build time so both the HTTP `/metrics` exposition path
     * (orchestrator-side) and the Platform-bound MetricsReporter (which
     * concatenates the agent snapshot before WS push so agent metrics
     * land in Mimir per-org alongside `kici_orch_*`) reference the same
     * store. the metrics enforcement plan.
     */
    agentMetricsAggregator: AgentMetricsAggregator;
}
/**
 * Mode-specific hooks injected by each entry point.
 */
export interface OrchestratorHooks {
    /** Logger prefix for mode-specific messages */
    logPrefix: string;
    /**
     * Extra ExecutionTracker callbacks (e.g., Platform-mode forwards execution
     * status and step status to the relay).
     */
    executionTrackerExtras?: (subsystems: OrchestratorSubsystems) => {
        onExecutionStatusChange?: ExecutionTrackerDeps['onExecutionStatusChange'];
        onStepStatusForward?: ExecutionTrackerDeps['onStepStatusForward'];
        onJobStatusChange?: ExecutionTrackerDeps['onJobStatusChange'];
        onRunEventEmit?: ExecutionTrackerDeps['onRunEventEmit'];
        orgId?: string;
    };
    /**
     * Called after the secrets subsystem is initialized.
     * Server.ts uses this to create SecretResolver; standalone doesn't.
     */
    onSecretsInitialized?: (ctx: {
        pgSecretStore: PgSecretStore;
        backendStores: Map<string, SecretStore>;
        db: Kysely<Database>;
        auditLogger: AuditLogger;
    }) => SecretResolver | null;
    /**
     * Called after all subsystems are built, before HTTP server starts.
     * Mode-specific wiring (PlatformClient creation, peer client setup, etc.)
     *
     * Returns mode-specific dependencies to pass to createApp() and
     * additional shutdown steps.
     */
    onSubsystemsReady: (subsystems: OrchestratorSubsystems) => Promise<{
        /** Extra dependencies to merge into createApp() */
        appDepsExtras?: Record<string, unknown>;
        /** Extra ConfigReloader deps beyond shared ones */
        configReloaderExtras?: {
            onProviderChange?: (newConfig: AppConfig, oldConfig: AppConfig, subsystems: OrchestratorSubsystems) => Promise<void>;
            onPlatformReconnect?: (newConfig: AppConfig) => Promise<void>;
        };
        /** Extra shutdown steps in order (run before shared shutdown) */
        shutdownExtras?: Array<{
            label: string;
            fn: () => Promise<void> | void;
        }>;
        /** Called after HTTP server starts (e.g., PlatformClient.connect) */
        onServerStarted?: () => Promise<void>;
    }>;
    /**
     * Mode startup log message.
     */
    startupLogMessage: (port: number) => string;
}
export declare function bootstrapOrchestrator(config: AppConfig, hooks: OrchestratorHooks, options?: {
    otelSdk?: {
        shutdown(): Promise<void>;
    };
}): Promise<void>;
//# sourceMappingURL=orchestrator-core.d.ts.map