import { QueryExecutor, type ConnectionConfig, type DatabaseConnector, type SQLParamSpec } from '@duckcodeailabs/dql-connectors';
import { type SemanticLayer, type SemanticLayerProviderConfig, type DashboardDocument, type ManifestBlock, type DomainInput } from '@duckcodeailabs/dql-core';
import type { ProviderId } from './llm/types.js';
import { type AgentSchemaTable, type ProposalResult, type ProposePlan, type ProposePlanCandidate, type ProposeConfigInput } from '@duckcodeailabs/dql-agent';
import { type InvariantResult } from '@duckcodeailabs/dql-governance';
import { type BlockStudioImportInputMode, type BlockStudioImportSource, type BlockStudioImportSourceKind, type DqlGenerationSession } from './block-studio-import.js';
export interface ProjectConfig {
    project?: string;
    defaultConnection?: ConnectionConfig;
    defaultConnectionName?: string;
    connections?: Record<string, ConnectionConfig & {
        path?: string;
        type?: string;
    }>;
    dataDir?: string;
    semanticLayer?: SemanticLayerProviderConfig;
    dbt?: {
        projectDir?: string;
        manifestPath?: string;
    };
    preview?: {
        port?: number;
        theme?: string;
        open?: boolean;
    };
    /** Optional `dql propose` conventions (classifier + bounded selection). */
    propose?: ProposeConfigInput;
}
export declare function resolveProjectSemanticConfig(projectConfig: ProjectConfig, projectRoot: string): SemanticLayerProviderConfig | undefined;
export interface DbtProfileConnectionCandidate {
    id: string;
    profileName: string;
    targetName: string;
    adapter: string;
    path: string;
    connection: ConnectionConfig;
    missingFields: string[];
    warnings: string[];
}
export interface ConnectorInstallStatus {
    driver: 'duckdb' | 'snowflake' | 'databricks';
    label: string;
    packageName?: string;
    packageSpec?: string;
    installed: boolean;
    builtIn: boolean;
    installPath: string;
    installCommand?: string;
}
export interface LocalServerOptions {
    rootDir: string;
    projectRoot?: string;
    executor: QueryExecutor;
    connection?: ConnectionConfig | null;
    preferredPort: number;
    /**
     * Host the HTTP server binds to. Defaults to `127.0.0.1` (loopback only)
     * for security. Set to `0.0.0.0` when running inside a container so the
     * port is reachable from the host. Honours `DQL_HOST` env var when unset.
     */
    host?: string;
    /**
     * Receives the underlying HTTP server once created, so short-lived callers
     * (e.g. `dql agent ask` starting an ephemeral runtime) can `close()` it and
     * let the process exit instead of hanging on an open listener.
     */
    captureServer?: (server: import('node:http').Server) => void;
}
export declare function startLocalServer(opts: LocalServerOptions): Promise<number>;
export declare function assertLocalQueryRuntimeReady(executor: QueryExecutor, connection: ConnectionConfig): Promise<void>;
export declare function formatLocalQueryRuntimeError(connection: ConnectionConfig, error: unknown): string;
export interface ConnectionTestResult {
    ok: boolean;
    message: string;
    details?: Record<string, unknown>;
}
export declare function validateConnectionForTest(connector: DatabaseConnector, connection: ConnectionConfig): Promise<ConnectionTestResult>;
export declare function resolveDefaultLLMProvider(projectRoot: string): ProviderId | null;
export declare function serializeJSON(value: unknown): string;
/** The Domain shape the frontend codes to (spec 17 shared contract). */
interface DomainDto {
    id: string;
    name: string;
    owner?: string;
    boundedContext?: string;
    sourceSystems?: string[];
    description?: string;
    sourcePath?: string;
    blockCount?: number;
    skillCount?: number;
    termCount?: number;
}
/** List authored domains with per-domain block/skill/term counts. */
export declare function listDomains(projectRoot: string): DomainDto[];
/** Validate + normalize an inbound `{ domain }` body into a DomainInput. */
export declare function parseDomainInput(raw: unknown, fallbackId?: string): DomainInput | null;
export declare function findProjectRoot(startDir: string): string;
export declare function loadProjectConfig(projectRoot: string): ProjectConfig;
/**
 * Shape returned by `/api/propose`. Drives the notebook Readiness surface:
 * a readiness summary plus a ranked queue of DRAFT proposals, each carrying its
 * stored Certifier verdict ("what's missing to certify"). The endpoint NEVER
 * certifies — proposals always render as AI-Generated drafts and route into the
 * existing human review/certify flow.
 */
export interface ProposeReadinessResult {
    /** True when a dbt manifest was found and the engine ran. */
    ready: boolean;
    /**
     * Why the engine could not run (no dbt manifest). Present only when
     * `ready === false`; the UI shows this as a "what to do next" hint.
     */
    reason?: string;
    summary: {
        projectName?: string;
        /** dbt models the engine scanned (whole manifest). */
        modelsScanned: number;
        /** Models classified `business` by the cascade. */
        businessModels: number;
        /** Models classified `plumbing` and excluded from generation. */
        plumbingExcluded: number;
        /** Semantic metrics discovered in the manifest. */
        metricsFound: number;
        /** Selected (bounded, business-only) proposals the engine ranked. */
        proposalsRanked: number;
        /** Drafts already written to the project (skipped on re-run). */
        draftsExisting: number;
        /** Proposals with zero blocking certifier errors (closest to certifiable). */
        readyForReview: number;
        /** Total blocking certifier errors across the queue. */
        blockingTotal: number;
        /** Total certifier warnings across the queue. */
        warningTotal: number;
    };
    /**
     * Deterministic PLAN of the bounded, business-only seed (writes nothing).
     * Drives the plan/approve gate in the Get Started flow.
     */
    plan: ProposePlan;
    /** Ranked DRAFT proposals for the selected scope (engine order preserved). */
    proposals: ProposalResult[];
}
/**
 * Core of the `/api/propose` endpoint, factored out as a pure function so it can
 * be unit-tested without standing up an HTTP server.
 *
 * It reuses the existing `propose` engine from `@duckcodeailabs/dql-agent`
 * verbatim (no inference/ranking logic is duplicated here) in `dryRun` mode so a
 * readiness preview never mutates the project. Every returned proposal is a
 * `status: draft` block with the engine's stored Certifier verdict attached.
 */
export declare function buildProposeReadiness(projectRoot: string, projectConfig?: ProjectConfig, options?: {
    owner?: string;
    limit?: number;
}): ProposeReadinessResult;
/**
 * Materialize drafts for an APPROVED scope (selected slugs / domains). Reuses
 * the propose engine's `onlySlugs` path + the draft writer. Plumbing is never
 * generated even if an approved slug names a plumbing model. Returns the written
 * summary so the caller can route into the per-block review flow.
 */
export interface ProposeGenerateResult {
    ready: boolean;
    reason?: string;
    draftsWritten: number;
    draftsSkipped: number;
    proposals: ProposalResult[];
}
export declare function generateProposeDrafts(projectRoot: string, slugs: string[], projectConfig?: ProjectConfig, options?: {
    owner?: string;
}): Promise<ProposeGenerateResult>;
/**
 * Build the FILLED transparent preview for ONE proposed candidate slug (spec 14,
 * part A). Reuses the deterministic `buildProposePreview` engine (real SQL +
 * Certifier verdict) and best-effort AI enrichment (description/llmContext/
 * examples) when a provider is available. Writes NOTHING. Returns `undefined`
 * when the slug is not part of the bounded, business-only selection.
 */
export declare function buildProposeCandidatePreview(projectRoot: string, slug: string, owner?: string, projectConfig?: ProjectConfig): Promise<ProposePlanCandidate | undefined>;
export declare function getConnectorInstallStatuses(projectRoot: string): ConnectorInstallStatus[];
export declare function prepareLocalExecution(sql: string, connection: ConnectionConfig, projectRoot: string, projectConfig: ProjectConfig): {
    sql: string;
    connection: ConnectionConfig;
};
export interface DashboardFilterApplicationResult {
    sql: string;
    sqlParams: SQLParamSpec[];
    variables: Record<string, unknown>;
    appliedFilters: Array<{
        filter: string;
        binding?: string;
        mode: 'parameter' | 'predicate';
        paramNames: string[];
    }>;
    skippedFilters: Array<{
        filter: string;
        reason: string;
    }>;
}
export declare function dashboardRuntimeVariables(dashboard: Pick<DashboardDocument, 'filters' | 'params'>, overrides?: Record<string, unknown>): Record<string, unknown>;
export declare function applyDashboardFiltersToBlockExecution(input: {
    sql: string;
    sqlParams: SQLParamSpec[];
    variables: Record<string, unknown>;
    block: Pick<ManifestBlock, 'name' | 'allowedFilters' | 'filterBindings' | 'parameterPolicy'>;
    dashboard: Pick<DashboardDocument, 'filters'>;
}): DashboardFilterApplicationResult;
export declare function resolveDbtMacrosForExecution(sql: string, projectRoot: string, projectConfig?: ProjectConfig): string;
export declare function buildAgentPreviewSql(sql: string): string;
export interface PreparedSemanticSql {
    sql: string;
    semanticRefs: {
        metrics: string[];
        dimensions: string[];
    };
    unresolvedRefs: string[];
}
/**
 * Shared resolver for `@metric(name)` / `@dim(name)` refs in raw SQL.
 * Used by notebook SQL execution and Block Studio validation so both paths
 * behave identically. If the SQL has no refs, returns it unchanged.
 */
export declare function prepareSemanticSql(sql: string, semanticLayer: SemanticLayer | undefined): PreparedSemanticSql;
export declare function normalizeProjectConnection(connection: ConnectionConfig, projectRoot: string): ConnectionConfig;
export declare function resolveProjectRelativeSqlPaths(sql: string, projectRoot: string, dataDir?: string): string;
export declare function openBlockStudioDocument(projectRoot: string, relativePath: string, semanticLayer?: SemanticLayer): {
    path: string;
    source: string;
    metadata: {
        name: string;
        path: string | null;
        domain: string;
        description: string;
        owner: string;
        tags: string[];
        reviewStatus?: string;
    };
    companionPath: string | null;
    validation: ReturnType<typeof validateBlockStudioSource>;
};
type BlockStudioDiagnostic = {
    severity: 'error' | 'warning' | 'info';
    message: string;
    code?: string;
};
export declare function resolveSemanticTableMapping(executor: QueryExecutor, connection: ConnectionConfig, semanticLayer?: SemanticLayer): Promise<Record<string, string> | undefined>;
export declare function buildSemanticTableMapping(semanticLayer: SemanticLayer, rows: Array<Record<string, unknown>>): Record<string, string> | undefined;
export declare function validateBlockStudioSource(source: string, semanticLayer?: SemanticLayer): {
    valid: boolean;
    diagnostics: BlockStudioDiagnostic[];
    semanticRefs: {
        metrics: string[];
        dimensions: string[];
        segments: string[];
    };
    chartConfig?: {
        chart?: string;
        x?: string;
        y?: string;
        color?: string;
        title?: string;
    };
    executableSql?: string | null;
};
export interface CreateDqlGenerationSessionForProjectOptions {
    inputPath?: string;
    inputMode?: BlockStudioImportInputMode;
    sources?: BlockStudioImportSource[];
    sourceKind?: BlockStudioImportSourceKind | 'raw-sql';
    domain?: string;
    owner?: string;
    tags?: string[];
    provider?: string;
}
export declare function createDqlGenerationSessionForProject(projectRoot: string, options: CreateDqlGenerationSessionForProjectOptions, semanticLayer?: SemanticLayer): Promise<DqlGenerationSession>;
export declare function saveBlockStudioArtifacts(projectRoot: string, options: {
    currentPath?: string;
    source: string;
    name: string;
    domain?: string;
    description?: string;
    owner?: string;
    tags?: string[];
    lineage?: string[];
    importMeta?: {
        importId?: string;
        candidateId?: string;
        sourceKind?: string;
        sourcePath?: string;
    };
}): string;
export declare function saveBlockStudioDraftArtifacts(projectRoot: string, options: {
    currentPath?: string;
    source: string;
    name: string;
    domain?: string;
    description?: string;
    owner?: string;
    tags?: string[];
    lineage?: string[];
    importMeta?: {
        importId?: string;
        candidateId?: string;
        sourceKind?: string;
        sourcePath?: string;
    };
    stableSuffix?: string;
}): string;
/**
 * Extract the declared `invariants` from a block's DQL source using the core
 * parser (the same path that populates the manifest). Returns an empty array
 * when the source has no invariants or cannot be parsed — invariant evaluation
 * is best-effort and must never break a run.
 */
export declare function extractBlockInvariants(source: string): string[];
/**
 * Evaluate a block's declared invariants against a normalized query result.
 * Returns `null` when the block declares no invariants so callers can omit the
 * field entirely (blocks without invariants behave exactly as before).
 */
export declare function evaluateBlockInvariants(source: string, result: {
    columns: string[];
    rows: Array<Record<string, unknown>>;
}): {
    invariantResults: InvariantResult[];
    invariantViolation: boolean;
} | null;
export declare function parseBlockSourceMetadata(source: string): {
    name: string;
    domain: string;
    description: string;
    owner: string;
    tags: string[];
    status: string;
    blockType: string;
    llmContext: string;
    pattern: string;
    grain: string;
    entities: string[];
    outputs: string[];
    dimensions: string[];
    allowedFilters: string[];
    parameterPolicy: Array<{
        name: string;
        policy: string;
    }>;
    filterBindings: Array<{
        filter: string;
        binding: string;
    }>;
    sourceSystems: string[];
    replacementFor: string[];
    reviewCadence: string;
    metricRef: string;
    metricsRef: string[];
};
export declare function setBlockStudioStatus(projectRoot: string, blockPath: string, newStatus: string): void;
export interface BlockGitMetadata {
    commitSha: string;
    repo: string | null;
    branch: string | null;
}
export declare function readGitMetadata(projectRoot: string): BlockGitMetadata | null;
export declare function createBlockArtifacts(projectRoot: string, options: {
    name: string;
    domain?: string;
    owner?: string;
    content?: string;
    description?: string;
    tags?: string[];
    metricRefs?: string[];
    template?: string;
    blockType?: 'custom' | 'semantic';
    llmContext?: string;
    examples?: Array<{
        question: string;
        sql?: string;
    }>;
    invariants?: string[];
    gitMetadata?: BlockGitMetadata | null;
}): {
    path: string;
    content: string;
    companionPath: string;
};
export declare function createSemanticBuilderBlock(projectRoot: string, options: {
    name: string;
    domain?: string;
    description?: string;
    owner?: string;
    tags?: string[];
    metrics: string[];
    dimensions: string[];
    timeDimension?: {
        name: string;
        granularity: string;
    };
    chart?: string;
    blockType: 'semantic' | 'custom';
    sql: string;
    tables: string[];
    provider: string;
}): {
    path: string;
    content: string;
    companionPath: string;
};
export declare function discoverDbtProfileConnections(projectRoot: string, projectConfig: ProjectConfig): DbtProfileConnectionCandidate[];
export declare function buildDbtStatus(projectRoot: string, projectConfig: ProjectConfig, lastSyncTime: string | null): {
    configured: boolean;
    provider: "dql" | "dbt" | "cubejs" | "snowflake" | "lookml" | null;
    projectPath: string;
    projectName: any;
    artifacts: {
        manifest: {
            path: string;
            exists: boolean;
            count: number | undefined;
            generatedAt: string | null;
        };
        catalog: {
            path: string;
            exists: boolean;
            count: number | undefined;
            generatedAt: string | null;
        };
        semanticManifest: {
            path: string;
            exists: boolean;
            count: number | undefined;
            generatedAt: string | null;
        };
        runResults: {
            path: string;
            exists: boolean;
            count: number | undefined;
            generatedAt: string | null;
        };
    };
    counts: {
        models: number;
        sources: number;
        metrics: number;
        semanticModels: number;
        savedQueries: number;
    };
    lastSyncTime: string | null;
    setupHint: string;
};
export type SemanticLayerDiagnosticsIssueSeverity = 'info' | 'warning' | 'error';
export interface SemanticLayerDiagnosticsIssue {
    severity: SemanticLayerDiagnosticsIssueSeverity;
    code: string;
    message: string;
    action?: string;
    path?: string;
}
export declare function buildSemanticLayerDiagnostics(projectRoot: string, projectConfig: ProjectConfig, options: {
    semanticLayer?: SemanticLayer;
    semanticErrors?: string[];
    semanticConfig?: SemanticLayerProviderConfig;
    detectedProvider?: string;
    lastSyncTime: string | null;
}): {
    available: boolean;
    provider: string | null;
    sourceOfTruth: string;
    errors: string[];
    lastSyncTime: string | null;
    counts: {
        domains: number;
        metrics: number;
        measures: number;
        dimensions: number;
        timeDimensions: number;
        entities: number;
        hierarchies: number;
        semanticModels: number;
        savedQueries: number;
    };
    dbt: {
        configured: boolean;
        provider: "dql" | "dbt" | "cubejs" | "snowflake" | "lookml" | null;
        projectPath: string;
        projectName: any;
        artifacts: {
            manifest: {
                path: string;
                exists: boolean;
                count: number | undefined;
                generatedAt: string | null;
            };
            catalog: {
                path: string;
                exists: boolean;
                count: number | undefined;
                generatedAt: string | null;
            };
            semanticManifest: {
                path: string;
                exists: boolean;
                count: number | undefined;
                generatedAt: string | null;
            };
            runResults: {
                path: string;
                exists: boolean;
                count: number | undefined;
                generatedAt: string | null;
            };
        };
        counts: {
            models: number;
            sources: number;
            metrics: number;
            semanticModels: number;
            savedQueries: number;
        };
        lastSyncTime: string | null;
        setupHint: string;
    };
    issues: SemanticLayerDiagnosticsIssue[];
    warnings: string[];
};
export interface GitStatusResult {
    inRepo: boolean;
    branch: string | null;
    ahead: number;
    behind: number;
    changes: Array<{
        path: string;
        status: string;
    }>;
    error?: string;
}
export interface GitCommit {
    hash: string;
    author: string;
    date: string;
    subject: string;
}
export declare function buildAgentSchemaContext(question: string, rows: unknown[]): AgentSchemaTable[];
export declare function buildAgentValueProbeSql(table: AgentSchemaTable, column: string, searchTerms: string[], connection: ConnectionConfig): string;
export declare function extractAgentValueSearchTerms(question: string): string[];
export {};
//# sourceMappingURL=local-runtime.d.ts.map