/**
 * Hono application factory for the customer orchestrator.
 *
 * Creates the HTTP + WebSocket application with:
 * - Agent WebSocket endpoint at /ws for agent connections
 * - Webhook endpoint for direct webhook ingestion (Hybrid/Independent)
 * - Source-tarball serve endpoint at /api/v1/cache/source/:hash
 * - Health/readiness check endpoints
 * - Prometheus metrics endpoint
 * - Request ID and logging middleware
 * - 25MB body size limit
 *
 * Pattern follows packages/platform/src/app.ts: returns { app, injectWebSocket }.
 */
import type { Kysely } from 'kysely';
import type pg from 'pg';
import { type ColdStore } from '@kici-dev/shared';
import type { AppConfig } from './config.js';
import type { Database } from './db/types.js';
import type { AgentRegistry } from './agent/registry.js';
import type { Dispatcher } from './agent/dispatcher.js';
import type { RunCoordinator } from './cluster/coordinator.js';
import type { PeerRegistry } from './cluster/peer-registry.js';
import type { JobQueue } from './queue/job-queue.js';
import type { DedupCache } from './webhook/dedup.js';
import type { LockFileCache } from './lockfile-cache.js';
import type { PlatformClient } from './ws/platform-client.js';
import type { ScalerManager } from './scaler/manager.js';
import type { ProviderRegistry } from './provider-registry.js';
import type { SourceCache } from './cache/index.js';
import type { BuildCoordinator } from './cache/index.js';
import type { DepCache } from './cache/index.js';
import type { UserCache } from './cache/index.js';
import type { DispatchCacheRefTracker } from './cache/index.js';
import type { PendingBuildTracker } from './cache/index.js';
import type { PendingInitTracker } from './cache/index.js';
import type { PendingDynamicTracker } from './cache/index.js';
import type { CacheStorage } from './storage/types.js';
import { type CheckRunReporter } from './reporting/check-run-reporter.js';
import type { ExecutionTracker } from './reporting/execution-tracker.js';
import type { LogWriter } from './reporting/log-writer.js';
import type { LogStorage } from './reporting/log-storage.js';
import type { StepLogBuffer } from './reporting/step-log-buffer.js';
import type { SourceLocationData } from './reporting/check-run-summary.js';
import type { Hono as HonoType } from 'hono';
import type { PeerWsLike } from './cluster/peer-handler.js';
import type { PeerToPeerMessage } from '@kici-dev/engine';
import type { AgentTokenStore } from './agent/token-store.js';
import type { OwnershipTracker } from './agent/ownership-tracker.js';
import type { ObserverRegistry } from './ws/observer-registry.js';
import type { TokenManager } from './secrets/token-manager.js';
import type { SecretResolver } from './secrets/secret-resolver.js';
import { type AdminRouteDeps } from './routes/admin.js';
import type { RegistrationStore } from './registration/registration-store.js';
import type { RegistrationIndex } from './registration/registration-index.js';
import type { CronScheduler } from './cron/cron-scheduler.js';
import { type ConfigRouteDeps } from './routes/admin-config.js';
import type { ConcurrencyGroupTracker } from './concurrency/group-tracker.js';
import type { ConcurrencyQueueManager } from './concurrency/queue-manager.js';
import type { EventRouter } from './events/event-router.js';
import type { EventStore } from './events/event-store.js';
import type { EventEmitter } from './events/event-emitter.js';
import type { GlobalWorkflowPolicy } from './security/global-workflow-policy.js';
import type { EventLogWriter } from './webhook/event-log.js';
import type { AccessLogWriter } from './audit/access-log.js';
import type { GenericSourceManager } from './webhook/generic-sources.js';
import type { TrustStore } from './events/trust-store.js';
import type { EnvironmentStore } from './environments/environment-store.js';
import type { VariableStore } from './environments/variable-store.js';
import type { HeldRunStore } from './environments/held-runs.js';
import type { ContributorCache } from './security/contributor-cache.js';
import { AgentMetricsAggregator } from './metrics/agent-metrics-aggregator.js';
/**
 * All dependencies needed to create the orchestrator Hono app.
 */
export interface AppDependencies {
    config: AppConfig;
    db: Kysely<Database>;
    pool: pg.Pool;
    registry: AgentRegistry;
    dispatcher: Dispatcher;
    jobQueue: JobQueue;
    dedup: DedupCache;
    lockFileCache: LockFileCache;
    providerRegistry: ProviderRegistry;
    platformClient?: PlatformClient;
    scalerManager?: ScalerManager;
    /** Bundle cache for compiled workflow bundles. Optional — requires S3 storage. */
    sourceCache?: SourceCache;
    /** Build coordinator for deduplicating concurrent builds. Optional — requires bundle cache. */
    buildCoordinator?: BuildCoordinator;
    /** Dep cache for dependency tarballs. Optional — requires S3 storage. */
    depCache?: DepCache;
    /** User-facing cache (ctx.cache / declarative job-step cache). Optional — requires cache storage. */
    userCache?: UserCache;
    /**
     * Server-side jobId -> user-cache-namespace store. Written at dispatch time
     * (orchestrator-core's buildOnDispatch); read by the agent-WS handler to
     * resolve the cache ref for `cache.user.*` requests WITHOUT trusting the wire
     * message. Optional — absent for modes that never serve the user cache.
     */
    dispatchCacheRefs?: DispatchCacheRefTracker;
    /** Cache storage backend (S3) for metadata operations on upload completion. */
    cacheStorage?: CacheStorage;
    /**
     * Filesystem cache backend handle. Only set when KICI_STORAGE_TYPE is
     * `filesystem`. Drives the /api/v1/cache/blob/* HTTP route that serves and
     * receives signed-URL blob traffic the filesystem backend mints.
     */
    fsCache?: {
        basePath: string;
        signingSecret: string;
        ttlMs: number;
    };
    /** Pending build tracker for build-then-execute coordination. Optional — requires bundle cache. */
    pendingBuilds?: PendingBuildTracker;
    /** Pending init tracker for init-then-execute coordination. */
    pendingInits?: PendingInitTracker;
    /** Pending dynamic tracker for DynamicJobFn evaluation coordination. */
    pendingDynamics?: PendingDynamicTracker;
    /** Commit status reporter for setting pending/success/failure/error on commits. Optional. */
    checkRunReporter?: CheckRunReporter;
    /** Execution tracker for DB persistence of execution state. Optional — requires database. */
    executionTracker?: ExecutionTracker;
    /** Log writer for persisting agent log chunks. Optional — requires database. */
    logWriter?: LogWriter;
    /** Log storage backend for persisting webhook payloads and step logs. Optional — requires S3 storage. */
    logStorage?: LogStorage;
    /** Step log buffer for enriched check run summaries. Optional — requires execution tracker. */
    stepLogBuffer?: StepLogBuffer;
    /** Agent token store for validating agent auth tokens. Required when agentAuth='token'. */
    tokenStore?: AgentTokenStore;
    /** Job ownership tracker for validating agent messages. Optional — requires database. */
    ownershipTracker?: OwnershipTracker;
    /** Admin API route dependencies. Optional -- only mounted when secrets management is configured. */
    adminDeps?: AdminRouteDeps;
    /**
     * Resolves the public webhook URL for a newly added source (for
     * `kici-admin source add` output). Built by the entry point where the
     * Platform client + config are in scope; passed into the admin source routes.
     */
    resolveSourceWebhookUrl?: AdminRouteDeps['resolveSourceWebhookUrl'];
    /** Config admin API route dependencies. Optional -- mounted when config management is available. */
    configRouteDeps?: ConfigRouteDeps;
    /** Event router for internal event delivery. Optional -- if not set, event routing is inactive. */
    eventRouter?: EventRouter;
    /** Event store. Optional -- mounted when admin DLQ admin route should be available. */
    eventStore?: EventStore;
    /** Event emitter for system events (workflow/job complete). Optional -- if not set, system events are skipped. */
    eventEmitter?: EventEmitter;
    /** Generic webhook source manager. Optional -- if not set, generic webhooks are disabled. */
    genericSourceManager?: GenericSourceManager;
    /** Trust store for cross-repo event trust. Optional -- if not set, trust management admin routes are unavailable. */
    trustStore?: TrustStore;
    /** Observer registry for broadcasting status/log updates to CLI observers. Optional -- if not set, observer features are inactive. */
    observerRegistry?: ObserverRegistry;
    /** Token manager for authenticating test trigger and observer connections. Optional -- requires secrets subsystem. */
    tokenManager?: TokenManager;
    /** Secret resolver for test run secret context resolution. Optional -- if not set, test runs have no secret access. */
    secretResolver?: SecretResolver;
    /** Cron scheduler for refreshing last-fired cache after registration changes. Optional — requires database. */
    cronScheduler?: CronScheduler;
    /** Registration store for admin registration routes. Optional -- mounted when registration system is initialized. */
    registrationStore?: RegistrationStore;
    /** Registration index for admin registration routes. Optional -- mounted when registration system is initialized. */
    registrationIndex?: RegistrationIndex;
    /** Environment store for resolving environment configs. Optional -- if not set, environment resolution is inactive. */
    environmentStore?: EnvironmentStore;
    /** Variable store for resolving environment variables. Optional -- if not set, environment vars are not merged. */
    variableStore?: VariableStore;
    /** Held run store for persisting protection rule holds. Optional -- if not set, holds are not persisted. */
    heldRunStore?: HeldRunStore;
    /** Global workflow policy for org-level permission enforcement. Optional -- if not set, global workflows are dispatched without permission checks. */
    globalWorkflowPolicy?: GlobalWorkflowPolicy;
    /** Inbound webhook delivery log writer. Optional -- if not set, deliveries are not persisted to event_log. */
    eventLogWriter?: EventLogWriter;
    /** Cold-store handle (Phase E). Optional -- when present, admin event-log routes can serve archived rows. */
    coldStore?: ColdStore | null;
    /** Read + mutation attribution log writer. Optional -- if not set, access_log rows are not written. */
    accessLogWriter?: AccessLogWriter;
    /** In-memory concurrency group tracker. Optional -- if not set, concurrency is disabled. */
    concurrencyTracker?: ConcurrencyGroupTracker;
    /** DB-backed concurrency queue manager. Optional -- if not set, concurrency is disabled. */
    concurrencyQueueManager?: ConcurrencyQueueManager;
    /** Optional callback when agent sends encrypted secret outputs on job success. */
    onSecretOutputs?: (runId: string, jobId: string, secretOutputs: Record<string, {
        agentPublicKey: string;
        encrypted: string;
    }>) => Promise<void>;
    /** Cluster health routes (Hono app). Always mounted (cluster always on). */
    clusterHealthRoutes: HonoType;
    /** Peer WS handler for incoming peer connections. Always mounted (cluster always on). */
    peerHandler: {
        handleConnection: (ws: PeerWsLike, remoteIp?: string) => void;
        sendToPeer: (targetInstanceId: string, msg: PeerToPeerMessage) => boolean;
        getConnectionCount: () => number;
    };
    /** Optional join handler for direct peer join requests. */
    onJoinRequest?: (msg: import('@kici-dev/engine').JoinRequest) => Promise<import('@kici-dev/engine').JoinResponse>;
    /** Optional callback when agent inventory changes (connect/disconnect). Triggers peer heartbeat broadcast. */
    onAgentInventoryChanged?: () => void;
    /** Run coordinator for multi-orch claim/reroute. Optional -- if not set, jobs dispatch locally. */
    coordinator?: RunCoordinator;
    /** Peer registry for aggregating infrastructure across cluster. Optional. */
    peerRegistry?: PeerRegistry;
    /** Contributor permission cache. Optional -- threaded through from server.ts
     *  so membership-related webhooks invalidate matching entries immediately
     *  (instead of waiting for the 15-minute TTL). */
    contributorCache?: ContributorCache;
    /**
     * Shared aggregator for agent-pushed metrics. When omitted, app.ts
     * constructs its own — kept optional so existing tests still work
     * without touching every call site. Production wiring threads the
     * subsystem-built instance through so the Platform-bound MetricsReporter
     * can read the same store and Mimir gets agent metrics per-org.
     */
    agentMetricsAggregator?: AgentMetricsAggregator;
}
/**
 * In-memory cache for step source locations extracted from lock files.
 * Keyed by `workflowName:jobName`, stores source location arrays indexed by step index.
 * Populated during webhook processing, used by CheckRunReporter for annotations.
 */
export declare class SourceLocationStore {
    private readonly cache;
    private key;
    set(workflowName: string, jobName: string, locations: Array<SourceLocationData | undefined>): void;
    get(workflowName: string, jobName: string): SourceLocationData[] | undefined;
}
/**
 * Create Hono application with all routes and middleware.
 *
 * @param deps - Application dependencies (injected for testability)
 * @returns Object with Hono app instance and injectWebSocket function
 */
export declare function createApp(deps: AppDependencies): {
    app: import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema, string, string>;
    injectWebSocket: (server: import("http").Server | import("http2").Http2Server | import("http2").Http2SecureServer) => void;
    onSourceLocationsExtracted: (workflowName: string, jobName: string, locations: Array<{
        file: string;
        line: number;
        column: number;
    } | undefined>) => void;
    /**
     * Wake up the FIFO-next queued concurrency waiter for `(group, routingKey)`.
     * Called by orchestrator-core when a slot is released (run completion,
     * cancellation, supersession). No-op when concurrency is disabled.
     */
    tryDispatchNextQueued: ((group: string, routingKey: string) => Promise<void>) | undefined;
};
//# sourceMappingURL=app.d.ts.map