import { AxAIService, AxFunction } from '@ax-llm/ax';
import { T as TraceAnalysisStore } from './store-C1YxJDEK.js';
import { z } from 'zod';
import { g as AnalystCost, a as AnalystContext, A as Analyst } from './types-B5x54y6n.js';

/**
 * Typed Ax output for analyst findings.
 *
 * Replaces the legacy `findings:string[]` pattern (where every bullet
 * became a flat-severity `AnalystFinding`) with a structured object
 * array. Ax binds the field as `findings:json[]` so the provider emits
 * native structured output; at the kind-factory boundary we Zod-validate
 * each emitted finding so malformed rows fail loud instead of being
 * silently lifted with default severity.
 *
 * Why not `f.object().array()` directly in the signature? The Ax
 * signature string `question:string -> findings:json[]` already lets
 * the provider emit JSON arrays. A Zod boundary is required either
 * way (the provider can return any JSON), and Zod gives us a single
 * validation surface independent of which Ax version is installed.
 */

declare const ANALYST_SEVERITIES: readonly ["critical", "high", "medium", "low", "info"];
declare const RawAnalystFindingSchema: z.ZodObject<{
    severity: z.ZodEnum<{
        info: "info";
        critical: "critical";
        medium: "medium";
        low: "low";
        high: "high";
    }>;
    claim: z.ZodString;
    subject: z.ZodOptional<z.ZodString>;
    evidence_uri: z.ZodString;
    evidence_excerpt: z.ZodOptional<z.ZodString>;
    confidence: z.ZodNumber;
    rationale: z.ZodOptional<z.ZodString>;
    recommended_action: z.ZodOptional<z.ZodString>;
}, z.core.$strict>;
type RawAnalystFinding = z.infer<typeof RawAnalystFindingSchema>;
/**
 * Description embedded into the actor prompt so the LLM knows what
 * shape to emit. Kept here so kinds share one source of truth rather
 * than restating the schema in every prompt.
 */
declare const RAW_FINDING_SCHEMA_PROMPT = "Each finding MUST be a JSON object with these fields:\n  - severity: one of \"critical\" | \"high\" | \"medium\" | \"low\" | \"info\"\n  - claim: one-sentence statement (max 2000 chars)\n  - subject?: the routing locus this finding is about. It MUST be one of the exact subject forms listed in this kind's instructions above (e.g. `system-prompt:<section>`, `agent-knowledge:wiki:<slug>`, `tool-doc:<tool>`). A free phrase, a bare noun, or any form not in that list is REJECTED at parse time and the finding is discarded \u2014 omit subject entirely rather than guess a form.\n  - evidence_uri: REQUIRED, never blank. Exactly one of \"span://<trace_id>/<span_id>\" (trace evidence), \"artifact://<relative-path>\" (files), \"metric://<name>\" (named scalars) \u2014 ALWAYS cite a real id surfaced by the tools. If you have no citable id, do not emit the finding.\n  - evidence_excerpt?: short quote (<=2000 chars) from the cited span/artifact\n  - confidence: number 0..1 \u2014 0.9+ when backed by exact quotes, 0.6-0.8 for inferred patterns, <0.5 for speculative\n  - rationale?: one or two sentences explaining the reasoning\n  - recommended_action?: concrete change phrased as an imperative (\"Add ...\", \"Replace ...\", \"Stop ...\") \u2014 omit when the finding is purely descriptive\n\nEmit an empty array when the question has no findings to report. Do not fabricate evidence.";
/**
 * Validate one row emitted by the LLM. Returns the typed finding on
 * success; returns `null` and logs the reason on failure so the kind
 * factory can skip-and-count rather than abort the whole analyst run.
 */
declare function parseRawFinding(row: unknown, log?: (msg: string, fields?: Record<string, unknown>) => void): RawAnalystFinding | null;

/**
 * Analyst-kind factory — the typed way to define trace analysts.
 *
 * A "kind" is a specialized analyst whose actor prompt, tool subset,
 * and Ax recursion config target one failure-mode lens (failure-mode
 * classification, knowledge gap discovery, knowledge poisoning, recursive
 * self-improvement, ...). Kinds emit findings in the typed `RawAnalystFinding`
 * shape via a JSON-array Ax output; the factory validates each row with
 * Zod and lifts it into `AnalystFinding[]` with no shape guessing.
 *
 * Composition rules:
 *   - Each kind owns its actor description. No generic "answer this
 *     question" prompt — the prompt names the failure lens.
 *   - Each kind picks a narrow tool subset from `ANALYST_TOOL_GROUPS`.
 *     A kind that never needs full-trace dumps can drop `viewTrace` /
 *     `viewSpans` and stay cheap.
 *   - Each kind declares its recursion + parallelism budget. Discovery-
 *     heavy kinds (failure-mode) get higher `maxDepth`; lens kinds
 *     (poisoning) usually stay at 0 since they have a tighter brief.
 *
 * Optimizer hook: kinds may declare `goldens` — labeled examples used
 * by `AxMiPRO` / `AxBootstrapFewShot` / `AxGEPA` to fit the actor
 * description programmatically. Stored on the kind, not the registry,
 * because the right metric is kind-specific.
 */

/**
 * Per-kind specification. The factory turns this into a regular
 * `Analyst<TraceAnalysisStore>` ready for `AnalystRegistry.register()`.
 */
interface TraceAnalystKindSpec {
    /** Stable id. Appears in finding_id, telemetry, and registry exclusions. */
    id: string;
    /** One-sentence description shown in `registry.list()`. */
    description: string;
    /** Coarse classification stamped on every emitted finding (`failure-mode`, `knowledge-gap`, ...). */
    area: string;
    /** Bump on any breaking change to the actor prompt or output schema. */
    version: string;
    /** Actor system prompt. Must instruct the LLM to emit `findings` per the schema. */
    actorDescription: string;
    /** Responder system prompt; falls back to a minimal "format the findings" instruction. */
    responderDescription?: string;
    /** Tool functions the actor may call. Pick narrow subsets via `ANALYST_TOOL_GROUPS`. */
    buildTools: (store: TraceAnalysisStore) => AxFunction[];
    /** Recursion budget. `maxDepth: 0` disables subagents. */
    recursion?: {
        maxDepth: number;
        maxParallelSubagents?: number;
    };
    /** Actor turn cap. Default 12. */
    maxTurns?: number;
    /** Runtime char cap. Default 6000. */
    maxRuntimeChars?: number;
    /** Cost classification surfaced in `registry.list()` and budget enforcement. */
    cost: AnalystCost;
    /** Per-finding-row hook — kinds may reject / rewrite before lifting. */
    postProcess?: (row: RawAnalystFinding, ctx: AnalystContext) => RawAnalystFinding | null;
    /** Optional optimizer hook — populated when a kind wants to fit its prompt against labeled examples. */
    goldens?: TraceAnalystGolden[];
}
/**
 * One labeled example consumed by Ax optimizers (MIPRO / GEPA / Bootstrap).
 * Each input is the same `{question}` an analyst would receive; `expected`
 * is the ground-truth finding set a fitted prompt should produce on this
 * input. Metric: kind-specific (default: F1 on `finding_id` overlap).
 */
interface TraceAnalystGolden {
    question: string;
    expected: ReadonlyArray<Omit<RawAnalystFinding, 'confidence'>>;
}
interface CreateTraceAnalystKindOpts {
    /** AxAIService bound at registration time. */
    ai: AxAIService;
    /** Optional model override; falls back to the AI service's default. */
    model?: string;
    /** Override the spec's `version` (e.g. when an optimizer has fitted a new prompt). */
    versionSuffix?: string;
    /**
     * Optional two-phase recovery: when the agentic harvest is empty but the
     * actor produced a substantive free-form `report`, extract findings from that
     * prose via a tolerant chat-completions pass (`structureFindings`) — no
     * strict-emission contract, so it works on weak models. Omit to leave the
     * actor's harvest as-is (the report is still surfaced fail-loud either way).
     */
    recovery?: {
        baseUrl: string;
        apiKey?: string;
        model?: string;
        fetchImpl?: typeof fetch;
    };
}
/**
 * Build an `Analyst<TraceAnalysisStore>` from a kind spec.
 *
 * Lifts the Ax pipeline once at registration time so the registry
 * gets a stateless analyst. The Ax agent is freshly constructed per
 * `analyze()` call (the agent carries chat-log + usage state we don't
 * want shared across analyst runs).
 */
declare function createTraceAnalystKind(spec: TraceAnalystKindSpec, opts: CreateTraceAnalystKindOpts): Analyst<TraceAnalysisStore>;
/**
 * Render a compact prior-findings block the actor reads alongside its
 * brief. Each row is one line so the actor can scan dozens cheaply.
 * The kind's prompt instructs the actor to (a) check whether a new
 * cluster matches a prior `finding_id` (carry the id forward via
 * `id_basis` to keep diffs stable) and (b) raise severity / confidence
 * when a prior finding has reappeared without remediation.
 *
 * Returns the empty string when there are no prior findings — most
 * runs are "first-of-its-kind" and the prompt stays unchanged.
 *
 * Exported for tests + for consumers that build their own actor
 * prompts (e.g. specialized analysts living outside the default kinds).
 */
declare function renderPriorFindings(prior: AnalystContext['priorFindings']): string;

export { ANALYST_SEVERITIES as A, type CreateTraceAnalystKindOpts as C, RAW_FINDING_SCHEMA_PROMPT as R, type TraceAnalystKindSpec as T, type RawAnalystFinding as a, RawAnalystFindingSchema as b, type TraceAnalystGolden as c, createTraceAnalystKind as d, parseRawFinding as p, renderPriorFindings as r };
