/**
 * Skill Executor
 *
 * 核心执行引擎，支持：
 * - Skill 组合（composite）
 * - Skill 迭代（iterator）
 * - AI 协作（ai_decision, ai_summary）
 * - 诊断推理（diagnostic）
 * - 展示控制（display）
 */
import { SkillDefinition, SkillExecutionContext, SkillExecutionResult, StepResult, SkillEvent, SynthesizeConfig } from './types';
import { DataEnvelope, DataEnvelopeTraceSide, ColumnDefinition } from '../../types/dataContract';
import type { IdentityResolutionV1 } from '../../types/identityContract';
import { DisplayLayer } from './types';
/**
 * Synthesize Data - 标记为 synthesize 的步骤数据
 * 用于最终总结时的数据聚合
 */
export interface SynthesizeData {
    /** 步骤 ID */
    stepId: string;
    /** 步骤名称 */
    stepName?: string;
    /** 步骤类型 */
    stepType: string;
    /** 数据层级 */
    layer?: string;
    /** 步骤数据 */
    data: any;
    /** 执行是否成功 */
    success: boolean;
    /** YAML 中定义的 synthesize 配置（数据驱动）*/
    config?: SynthesizeConfig;
}
/**
 * 分层结果结构
 *
 * 语义层级：
 * - overview: 顶层概览（聚合指标如 FPS、掉帧率）
 * - list: 列表数据（会话/事件列表）
 * - session: 会话详情（单个会话的详情）
 * - deep: 深度分析（帧级/调用级分析）
 * - diagnosis: 诊断结论与根因证据
 */
export interface LayeredResult {
    layers: {
        /** 概览层 - 聚合指标（如 FPS、掉帧率） */
        overview?: Record<string, StepResult>;
        /** 列表层 - 会话/事件列表 */
        list?: Record<string, StepResult>;
        /** 会话层 - 单个会话的详情 */
        session?: Record<string, Record<string, StepResult>>;
        /** 深度层 - 帧级/调用级分析 */
        deep?: Record<string, Record<string, StepResult>>;
        /** 诊断层 - 根因/结论证据 */
        diagnosis?: Record<string, StepResult>;
    };
    defaultExpanded: DisplayLayer[];
    metadata: {
        skillName: string;
        version: string;
        executedAt: string;
    };
    /** Raw step results, including hidden/no-layer steps. */
    stepResults?: StepResult[];
    /** YAML 中标记为 synthesize: true 的步骤数据，用于最终总结 */
    synthesizeData?: SynthesizeData[];
}
/**
 * 将 YAML 中的 layer 值规范化为语义名称
 */
export declare function normalizeLayer(layer: string | undefined): DisplayLayer | undefined;
export declare class SkillExecutor {
    private traceProcessor;
    private aiService;
    private skillRegistry;
    private eventEmitter?;
    private fragmentRegistry;
    private identityGate;
    private processIdentityCache;
    constructor(traceProcessor: any, aiService?: any, eventEmitter?: (event: SkillEvent) => void);
    /**
     * Set the SQL fragment registry (loaded by SkillRegistry).
     * Fragments are reusable CTE definitions injected into step SQL at runtime.
     */
    setFragmentRegistry(cache: Map<string, string>): void;
    /**
     * Inject SQL fragment CTEs into a step's SQL query.
     *
     * Fragment files contain bare CTE definitions (no WITH keyword), e.g.:
     *   target_threads AS (SELECT ...)
     *
     * Injection rules:
     * - If the SQL starts with WITH: insert fragments after WITH, before existing CTEs
     * - Otherwise: wrap as WITH <fragments>\n<sql>
     */
    private injectSqlFragments;
    /**
     * 注册 skill
     */
    registerSkill(skill: SkillDefinition): void;
    /**
     * 批量注册 skills
     */
    registerSkills(skills: SkillDefinition[]): void;
    /**
     * 发送事件到前端
     */
    private emit;
    private resolveTraceSide;
    private buildIdentityCacheKey;
    private toNumber;
    private splitSources;
    private rowToIdentityCandidate;
    private hasExactProcessIdTarget;
    private identityQualityWarnings;
    private normalizeIdentityStatus;
    private resolveProcessIdentityForGate;
    private applyIdentityGate;
    private buildIdentityBlockedResult;
    /**
     * Expand prerequisite module aliases to canonical stdlib module ids.
     */
    private resolvePrerequisiteModules;
    /**
     * Best-effort probe for prerequisite modules and return only available ones.
     * Note: some trace processor builds treat INCLUDE as statement-scoped, so
     * SQL execution still prepends INCLUDE per-step for determinism.
     */
    private resolveAvailableModules;
    /**
     * Prefix SQL with prerequisite INCLUDE statements.
     */
    private buildSqlWithModuleIncludes;
    /**
     * 执行 skill
     */
    execute(skillId: string, traceId: string, params?: Record<string, any>, inherited?: Record<string, any>): Promise<SkillExecutionResult>;
    /**
     * Execute a step-based skill (composite/iterator/diagnostic, and legacy atomic skills without root-level `sql`).
     * Mutates `context.results` / `context.variables` and appends into `displayResults` / `diagnostics` / `synthesizeData`.
     */
    private hasMeaningfulData;
    private extractSaveAsValue;
    private executeStepBasedSkill;
    /**
     * Apply expandableBindSource declarations: for each step that declares an expandableBindSource,
     * find the batch data in context.variables and bind it as expandableData on the target DisplayResult.
     */
    private applyExpandableBindSources;
    /**
     * Build expandableData by matching batch source rows to target list rows.
     *
     * Matching strategy: both datasets are ordered by (session_id, frame_start), so
     * we match by frame_index when available, falling back to start_ts, then positional index.
     *
     * Accepts two data shapes:
     * - Columnar: targetRows (any[][]) + targetColumns (string[]) — from executeStepBasedSkill DisplayResults
     * - Object array: targetObjects (Record<string, any>[]) — from executeCompositeSkill StepResults
     */
    private buildExpandableFromBatch;
    /**
     * Group a batch row into named sections for the expandable UI.
     * Uses a declarative registry for JSON columns + imperative handlers for scalar fields.
     */
    private groupBatchRowIntoSections;
    /** Safely parse a JSON string column from a batch row. */
    private parseJsonColumn;
    /**
     * Execute composite skill and return layered results
     * This is an alternative execution path that organizes output by layers (overview/list/session/deep)
     */
    executeCompositeSkill(skill: SkillDefinition, inputs: Record<string, any>, context: Partial<SkillExecutionContext>): Promise<LayeredResult>;
    /**
     * 执行原子 skill（单个 SQL）
     */
    private executeAtomicSkill;
    /**
     * 执行单个步骤
     */
    private executeStep;
    /**
     * 执行原子步骤
     */
    private executeAtomicStep;
    /**
     * 检查 prerequisites 条件 (required_tables, optional_tables)
     */
    private checkPrerequisites;
    /**
     * 执行 skill 引用步骤
     */
    private executeSkillRefStep;
    /**
     * 执行迭代步骤
     */
    private executeIteratorStep;
    /**
     * 执行并行步骤
     */
    private executeParallelStep;
    /**
     * 执行诊断步骤
     */
    private executeDiagnosticStep;
    /**
     * 收集诊断结论的数据依据
     * 从 rule.evidence_fields 或自动从 condition 解析引用的数据源
     */
    private collectDiagnosticEvidence;
    /**
     * 从表达式中提取数据源名称
     * 例如: "lock_data.data[0]?.wait_ms > 2" => ["lock_data"]
     */
    private extractDataSources;
    /**
     * 解析 evidence_fields 中的字段路径
     * 支持格式: "source.field" 或 "source.data[0].field"
     */
    private resolveEvidenceField;
    /**
     * 从对象中提取关键字段（排除大型嵌套对象）
     */
    private extractKeyFields;
    /**
     * 从输入数据中找到时间戳字段用于 Perfetto 跳转
     */
    private findTimestampField;
    /**
     * 执行 AI 决策步骤
     */
    private executeAIDecisionStep;
    /**
     * 执行 AI 总结步骤
     */
    private executeAISummaryStep;
    /**
     * 执行条件步骤
     */
    private executeConditionalStep;
    /**
     * 执行 pipeline 步骤
     *
     * 将渲染管线检测结果聚合为教学内容 + Pin 指令，作为 SkillEngine 一等步骤类型输出。
     */
    private executePipelineStep;
    private resolveStepResultFromSource;
    private resolveFirstObjectRowFromSource;
    private extractTraceRequirementHints;
    /**
     * 调用 AI 服务
     */
    private callAI;
    /**
     * Build a compact, deterministic payload for ai_summary/ai_decision steps.
     *
     * Note: step.inputs uses save_as names (preferred) or step ids.
     * We intentionally sample rows to avoid prompt bloat.
     */
    private buildAIInputsPayload;
    private resolveAIInputValue;
    private buildStructuredAIPrompt;
    private extractStructuredAIField;
    /**
     * 判断步骤是否需要展示
     */
    private shouldDisplay;
    /**
     * 获取步骤的展示配置
     */
    private getDisplayConfig;
    /**
     * 创建展示结果
     */
    private createDisplayResult;
    /**
     * Build a deterministic "insight summary" DisplayResult from synthesize configs.
     *
     * Motivation:
     * - Skills already carry `synthesize:` configs (role/fields/insights)
     * - Agents need compact, citeable KPIs + insights without relying on ai_summary
     *
     * Current scope (v2):
     * - Processes config.role in {'overview', 'conclusion', 'list', 'clusters'}
     * - overview/conclusion: uses first row/object as the KPI row
     * - list/clusters: summarizes group distributions + top items (best-effort)
     */
    private buildSynthesizeSummaryDisplayResult;
    /**
     * 创建 DataEnvelope (v2.0 数据契约格式)
     *
     * DataEnvelope 是自描述的数据容器，包含:
     * - meta: 数据来源和版本信息
     * - data: 实际数据内容
     * - display: 显示配置（包括列定义）
     *
     * 前端可以根据 display.columns 配置进行通用渲染，无需硬编码字段名。
     */
    private buildDataEnvelope;
    /**
     * 将 SkillExecutionResult 转换为 DataEnvelope 数组
     *
     * 用于 v2.0 数据契约，统一 SSE 事件格式
     */
    static toDataEnvelopes(result: SkillExecutionResult, columnDefinitions?: Record<string, Partial<ColumnDefinition>[]>, provenance?: {
        traceId?: string;
        traceSide?: DataEnvelopeTraceSide;
    }): DataEnvelope[];
    static attachTraceProvenanceToEnvelope(envelope: DataEnvelope, provenance?: {
        traceId?: string;
        traceSide?: DataEnvelopeTraceSide;
    }): DataEnvelope;
    static attachIdentityResolutionToEnvelope(envelope: DataEnvelope, identityResolution?: IdentityResolutionV1): DataEnvelope;
    /**
     * 检查数据是否是迭代器结果
     */
    private isIteratorResult;
    /**
     * 将迭代器结果展平为可显示的表格
     */
    private flattenIteratorResults;
    /**
     * 生成迭代器结果的汇总报告
     */
    private generateIteratorSummary;
    /**
     * 将 displayResults 转换为 sections 格式（用于 iterator 结果）
     */
    private convertDisplayResultsToSections;
    /**
     * 格式化单元格值用于显示
     */
    private formatCellValue;
    /**
     * 将行数组转换为对象数组
     */
    private rowsToObjects;
}
import { FindingSchema, SuggestionSchema } from './types';
/**
 * Structured finding extracted from module skill execution
 */
export interface ExtractedFinding {
    id: string;
    severity: 'info' | 'warning' | 'critical';
    title: string;
    description?: string;
    evidence: Record<string, any>;
    sourceModule: string;
    confidence: number;
}
/**
 * Structured suggestion for follow-up analysis
 */
export interface ExtractedSuggestion {
    id: string;
    targetModule: string;
    questionTemplate: string;
    params: Record<string, any>;
    priority: number;
    reason: string;
}
/**
 * Complete response from a module skill invocation
 * Used by cross-domain experts to understand module analysis results
 */
export interface ModuleSkillResponse {
    success: boolean;
    data: Record<string, any>;
    findings: ExtractedFinding[];
    suggestions: ExtractedSuggestion[];
    executionTimeMs: number;
    error?: string;
}
/**
 * Extract findings from skill execution results based on findingsSchema
 */
export declare function extractFindings(skillName: string, findingsSchema: FindingSchema[] | undefined, executionContext: SkillExecutionContext, stepResults: Record<string, StepResult>): ExtractedFinding[];
/**
 * Extract suggestions from skill execution results based on suggestionsSchema
 */
export declare function extractSuggestions(skillName: string, suggestionsSchema: SuggestionSchema[] | undefined, executionContext: SkillExecutionContext, stepResults: Record<string, StepResult>): ExtractedSuggestion[];
export declare function createSkillExecutor(traceProcessor: any, aiService?: any, eventEmitter?: (event: SkillEvent) => void): SkillExecutor;
//# sourceMappingURL=skillExecutor.d.ts.map