type RunStatus = 'running' | 'completed' | 'failed' | 'aborted';
interface BudgetSpec {
    tokens?: number;
    wallMs?: number;
    calls?: number;
    usd?: number;
}
interface RunOutcome {
    score?: number;
    pass?: boolean;
    failureClass?: FailureClass;
    notes?: string;
}
/**
 * Layer — optional classification in a nested build workflow.
 * `builder`: the meta-agent editing a project (e.g. agent-builder Forge chat).
 * `app-build`: sandbox harness that compiled + tested the generated scaffold.
 * `app-runtime`: a run of the generated agent against a domain scenario.
 * `meta`: any meta-eval (judge replay, correlation analysis).
 */
type RunLayer = 'builder' | 'app-build' | 'app-runtime' | 'meta' | 'custom';
interface Run {
    runId: string;
    /**
     * Stable identifier of the scenario being executed.
     *
     * Always populated on the persisted Run — but `TraceEmitter.startRun` accepts
     * input WITHOUT this field, substituting a sensible default
     * (`run.layer ?? run.tags?.['kind'] ?? 'runtime'`) when the caller has no
     * curated scenario to anchor to (runtime / operator / meta-eval runs). This
     * keeps the persisted shape unambiguous for downstream filters + aggregations
     * while removing the boilerplate of inventing placeholder ids at the call site.
     */
    scenarioId: string;
    variantId?: string;
    datasetVersion?: string;
    /** Git SHA of agent code at run time. */
    codeSha?: string;
    /** Hash of the prompt template + any system prompt. */
    promptSha?: string;
    /** Model id + date + system-prompt hash, concatenated. */
    modelFingerprint?: string;
    seed?: number;
    /** Arbitrary environment markers (shell, docker version, tz). */
    envFingerprint?: Record<string, string>;
    /** Version of the redaction rules applied to this run. */
    redactionVersion?: string;
    /** Parent run in a nested build workflow. A builder run's children are
     *  app-build runs; those children are app-runtime runs. */
    parentRunId?: string;
    /** Stable project identifier — groups runs across chats + sessions. */
    projectId?: string;
    /** Chat/conversation identifier within a project. */
    chatId?: string;
    /** Layer classification — hint for aggregation; not enforced. */
    layer?: RunLayer;
    startedAt: number;
    endedAt?: number;
    status: RunStatus;
    outcome?: RunOutcome;
    budget?: BudgetSpec;
    /** Free-form labels for downstream grouping. */
    tags?: Record<string, string>;
}
type SpanKind = 'agent' | 'llm' | 'tool' | 'retrieval' | 'judge' | 'sandbox' | 'custom';
type SpanStatus = 'ok' | 'error';
interface SpanBase {
    spanId: string;
    parentSpanId?: string;
    runId: string;
    kind: SpanKind;
    name: string;
    startedAt: number;
    endedAt?: number;
    status?: SpanStatus;
    error?: string;
    /** Anything not covered by typed fields. Kept deliberately free-form. */
    attributes?: Record<string, unknown>;
}
interface Message {
    role: 'system' | 'user' | 'assistant' | 'tool';
    content: string;
    tokens?: number;
    /** Multi-modal content descriptors; blobs themselves live in Artifacts. */
    images?: Array<{
        artifactId?: string;
        url?: string;
        mime?: string;
    }>;
}
interface LlmSpan extends SpanBase {
    kind: 'llm';
    model: string;
    messages: Message[];
    output?: string;
    inputTokens?: number;
    /** All generated tokens, including the reasoning subset when present. */
    outputTokens?: number;
    cachedTokens?: number;
    cacheWriteTokens?: number;
    /** Reasoning-token subset of `outputTokens`. */
    reasoningTokens?: number;
    costUsd?: number;
    finishReason?: string;
}
interface ToolSpan extends SpanBase {
    kind: 'tool';
    toolName: string;
    args: unknown;
    /** False when the source observed the call but did not capture its arguments. */
    argsCaptured?: boolean;
    result?: unknown;
    latencyMs?: number;
}
interface RetrievalSpan extends SpanBase {
    kind: 'retrieval';
    query: string;
    hits: Array<{
        docId: string;
        score: number;
        content?: string;
    }>;
}
interface JudgeSpan extends SpanBase {
    kind: 'judge';
    judgeId: string;
    /** Span this judgment applies to. */
    targetSpanId: string;
    dimension: string;
    /** Numeric score (free-range; interpretation up to the judge). */
    score: number;
    rationale?: string;
    evidence?: string;
}
interface SandboxSpan extends SpanBase {
    kind: 'sandbox';
    image?: string;
    command?: string;
    exitCode?: number;
    testsTotal?: number;
    testsPassed?: number;
    stdoutHash?: string;
    stderrHash?: string;
    /** Duration in ms; the harness fills this explicitly (endedAt - startedAt may miss setup). */
    wallMs?: number;
}
interface GenericSpan extends SpanBase {
    kind: 'agent' | 'custom';
}
type Span = LlmSpan | ToolSpan | RetrievalSpan | JudgeSpan | SandboxSpan | GenericSpan;
type EventKind = 'log' | 'error' | 'budget_decrement' | 'budget_breach' | 'state_mutation' | 'policy_violation' | 'redaction_applied' | 'custom';
interface TraceEvent {
    eventId: string;
    runId: string;
    spanId?: string;
    kind: EventKind;
    timestamp: number;
    payload: Record<string, unknown>;
}
interface BudgetLedgerEntry {
    runId: string;
    dimension: keyof BudgetSpec;
    limit: number;
    consumed: number;
    remaining: number;
    timestamp: number;
    breached: boolean;
    /** Span that triggered this entry, if any. */
    spanId?: string;
}
interface Artifact {
    artifactId: string;
    runId: string;
    spanId?: string;
    contentType: string;
    sizeBytes: number;
    /** sha256 in hex. */
    hash: string;
    /** External storage URL (R2, S3, filesystem path). */
    storageUrl?: string;
    /** Inline content for small blobs — keep under ~64KB. */
    inlineContent?: string;
}
type FailureClass = 'success' | 'reasoning_error' | 'tool_selection_error' | 'tool_argument_error' | 'tool_recovery_failure' | 'hallucination' | 'instruction_following' | 'safety_refusal_miss' | 'policy_violation' | 'budget_exceeded' | 'format_drift' | 'permission_escalation' | 'pii_leak' | 'cost_overrun' | 'timeout' | 'sandbox_failure' | 'missing_user_data' | 'missing_domain_data' | 'missing_codebase_context' | 'missing_runtime_context' | 'missing_credentials' | 'missing_integration_connection' | 'missing_integration_scope' | 'integration_approval_required' | 'integration_auth_expired' | 'integration_provider_failure' | 'bad_integration_manifest' | 'unsafe_integration_write_denied' | 'stale_external_data' | 'bad_retrieval' | 'insufficient_evidence' | 'contradictory_evidence' | 'ambiguous_user_intent' | 'knowledge_readiness_blocked' | 'unknown';

interface RunFilter {
    scenarioId?: string;
    variantId?: string;
    status?: RunStatus;
    since?: number;
    until?: number;
    tag?: {
        key: string;
        value: string;
    };
    parentRunId?: string;
    projectId?: string;
    chatId?: string;
    layer?: RunLayer;
}
interface SpanFilter {
    runId?: string;
    parentSpanId?: string;
    kind?: SpanKind;
    name?: string;
    toolName?: string;
    judgeId?: string;
    since?: number;
    until?: number;
}
interface EventFilter {
    runId?: string;
    spanId?: string;
    kind?: EventKind;
    since?: number;
    until?: number;
}
interface TraceStore {
    appendRun(run: Run): Promise<void>;
    updateRun(runId: string, patch: Partial<Run>): Promise<void>;
    appendSpan(span: Span): Promise<void>;
    updateSpan(spanId: string, patch: Partial<Span>): Promise<void>;
    appendEvent(event: TraceEvent): Promise<void>;
    appendArtifact(artifact: Artifact): Promise<void>;
    appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>;
    getRun(runId: string): Promise<Run | undefined>;
    listRuns(filter?: RunFilter): Promise<Run[]>;
    spans(filter?: SpanFilter): Promise<Span[]>;
    events(filter?: EventFilter): Promise<TraceEvent[]>;
    budget(runId: string): Promise<BudgetLedgerEntry[]>;
    artifacts(runId: string): Promise<Artifact[]>;
}

/**
 * BudgetBreachView — aggregates breach events across the corpus.
 *
 * Answers: which dimensions get hit most often? Which scenarios are
 * underbudgeted? Which variants trigger the most breaches?
 */

interface BudgetBreachFinding {
    runId: string;
    scenarioId: string;
    variantId?: string;
    dimension: keyof BudgetSpec;
    limit: number;
    consumed: number;
    excessRatio: number;
    timestamp: number;
}
interface BudgetBreachReport {
    findings: BudgetBreachFinding[];
    byDimension: Record<string, number>;
    byScenario: Record<string, number>;
    byVariant: Record<string, number>;
    totalRuns: number;
    breachedRunRatio: number;
}
declare function budgetBreachView(store: TraceStore, options?: {
    scenarioId?: string;
    variantId?: string;
}): Promise<BudgetBreachReport>;

/**
 * Failure taxonomy — canonical classes + a default classifier.
 *
 * Every failed run should end up in a named class. The classifier here
 * is rule-based (fast, deterministic); an LLM fallback can be added by
 * the consumer for novel cases and trained into the rule base over time.
 *
 * Consumers call `classifyFailure(run, spans, events)` and persist the
 * returned class as `Run.outcome.failureClass`.
 */

interface FailureContext {
    run: Run;
    spans: Span[];
    events: TraceEvent[];
}
/** Ordered rules — first match wins. */
interface FailureRule {
    id: string;
    match: (ctx: FailureContext) => {
        failureClass: FailureClass;
        reason: string;
        triggerSpanId?: string;
        triggerEventId?: string;
    } | null;
}

/**
 * FailureClusterView — groups failed runs by (failureClass, triggerTool,
 * argHash-prefix) so weekly reviews can prioritize the top-N clusters.
 *
 * Each cluster includes: N runs, scenarios affected, representative
 * error message, a proposed mitigation hint (rule → action table).
 */

interface FailureCluster {
    failureClass: FailureClass;
    /** Tool name when the trigger was a tool span, else undefined. */
    toolName?: string;
    /** First 16 chars of argHash — clusters similar args. */
    argPrefix?: string;
    /**
     * Source dimension when the trigger was a judge span (e.g. `'format'`,
     * `'safety'`, `'correctness'`). Lets cross-template aggregators
     * group failures by the dimension that fired without overloading
     * `argPrefix`. Optional — clusters without this field deserialize cleanly.
     */
    dimension?: string;
    runCount: number;
    scenarioIds: string[];
    exampleError?: string;
    exampleRunId: string;
}
interface FailureClusterReport {
    clusters: FailureCluster[];
    totalFailures: number;
    totalRuns: number;
}
declare function failureClusterView(store: TraceStore, options?: {
    rules?: FailureRule[];
    minClusterSize?: number;
}): Promise<FailureClusterReport>;

/**
 * Trajectory — ordered, structured view over a run's spans.
 *
 * A pure function `buildTrajectory(store, runId) → Trajectory` returns
 * a topologically ordered list of `TrajectoryStep` with parent-child
 * grouping collapsed into a single line-of-agent-work. Separate
 * analyzers (stuck-loop detection, waste ratio) live in
 * `pipelines/` and consume the trajectory.
 */

interface TrajectoryStep {
    index: number;
    span: Span;
    /** Depth in the span tree from the root. 0 = top-level. */
    depth: number;
    /** Events attached to this span. */
    events: TraceEvent[];
}

/**
 * FirstDivergenceView — aligns two trajectories by step index, reports
 * the first step where they differ.
 *
 * "Differ" is configurable — default is (kind, toolName if tool, model
 * if llm). Use this view to attribute "why is variant B better?" to a
 * specific step rather than an aggregate mean delta.
 */

interface DivergenceReport {
    runA: string;
    runB: string;
    firstDivergenceIndex: number | null;
    aStep?: TrajectoryStep;
    bStep?: TrajectoryStep;
    reason?: string;
    /** Common prefix length (steps that matched). */
    commonPrefixLen: number;
}
interface DivergenceOptions {
    /** Returns true if two steps are considered equal. Default: kind + tool/model match. */
    stepEquals?: (a: TrajectoryStep, b: TrajectoryStep) => boolean;
}
declare function firstDivergenceView(store: TraceStore, runA: string, runB: string, options?: DivergenceOptions): Promise<DivergenceReport>;

/**
 * JudgeAgreementView — pairwise agreement between judges across the
 * corpus, grouped by dimension.
 *
 * Output drives two workflows:
 *   - Judge robustness audit: "does Claude agree with GPT at κ ≥ 0.6?"
 *   - Calibration tracking: κ vs golden human labels over time (by
 *     providing a `humanGoldenJudgeId`).
 */

interface JudgePair {
    judgeA: string;
    judgeB: string;
    dimension: string;
    /** Number of (targetSpanId, dimension) tuples both judges scored. */
    commonItems: number;
    pearson: number;
    krippendorff: number;
}
interface JudgeAgreementReport {
    pairs: JudgePair[];
    dimensions: string[];
    judgeIds: string[];
}
declare function judgeAgreementView(store: TraceStore): Promise<JudgeAgreementReport>;

interface MetricVerdict {
    metric: string;
    baselineMean: number;
    candidateMean: number;
    delta: number;
    cohensD: number;
    welchT: number;
    welchDf: number;
    welchP: number;
    stable: boolean;
    /** IQR of the combined samples — used as a rough stability indicator. */
    iqr: number;
    verdict: 'improved' | 'regressed' | 'stable' | 'unstable';
}
interface BaselineReport {
    metrics: MetricVerdict[];
    /** True if any critical metric regressed. */
    hasRegression: boolean;
    /** True if any metric is unstable (too noisy to judge). */
    hasUnstable: boolean;
}
interface BaselineOptions {
    /** Effect size threshold for meaningful delta (default 0.5 — medium effect). */
    effectThreshold?: number;
    /** p-value threshold for statistical significance (default 0.05). */
    alpha?: number;
    /** IQR/mean ratio above which samples are flagged unstable (default 0.30). */
    unstableCvThreshold?: number;
}

/**
 * RegressionView — compares a candidate slice to a baseline slice on a
 * named metric. Delegates the statistics (Welch's t-test, Cohen's d,
 * IQR stability) to `baseline.ts`.
 *
 * This is the entry point for CI regression gates: "given runs tagged
 * release=A and release=B, did any metric regress?"
 */

interface RegressionSpec {
    metric: string;
    higherIsBetter: boolean;
    /** Extract a scalar from a run. Default extractors handle common metrics. */
    extract?: (run: Run, store: TraceStore) => Promise<number | null>;
}
interface RegressionOptions extends BaselineOptions {
    baseline: RunFilter;
    candidate: RunFilter;
}
declare function regressionView(store: TraceStore, metrics: RegressionSpec[], options: RegressionOptions): Promise<BaselineReport>;

/**
 * StuckLoopView — detects when an agent calls the same tool with the
 * same (or structurally similar) arguments ≥ N times in a short window.
 *
 * Rationale: agents that loop are the number-one production failure
 * mode on long-horizon flows. The view returns (runId, toolName,
 * argHash, occurrences, windowMs) for each detected loop plus a
 * fraction of runs affected.
 */

interface StuckLoopFinding {
    runId: string;
    toolName: string;
    argHash: string;
    /** Calls in this episode's densest qualifying interval, not the whole-run total. */
    occurrences: number;
    spanIds: string[];
    /** Nearest agent ancestor, or the direct parent when ancestry is incomplete. */
    scopeSpanId?: string;
    /** Milliseconds between first and last call in the loop. */
    windowMs: number;
}
interface StuckLoopReport {
    findings: StuckLoopFinding[];
    affectedRunRatio: number;
    totalRuns: number;
}
interface StuckLoopOptions {
    /** Minimum call count to flag a loop (default 3). */
    minOccurrences?: number;
    /** Maximum time between the first and last repeated call (default 60 seconds). */
    maxWindowMs?: number;
    /**
     * Maximum other tool calls allowed between adjacent repeats (default 0).
     * Set to 1 to detect alternating patterns such as A,B,A,B,A.
     */
    maxInterveningToolCalls?: number;
    /** Filter to a specific runId; omit to scan the entire corpus. */
    runId?: string;
}
declare function stuckLoopView(store: TraceStore, options?: StuckLoopOptions): Promise<StuckLoopReport>;

/**
 * Tool-use metrics — derived purely from trace data.
 *
 * No scoring assumptions: consumers supply optional ground-truth tool
 * selections per turn + optional "information used downstream" signals.
 * Without those, we still compute descriptive metrics (error rate,
 * retry rate, duplicate-call rate) that are useful on their own.
 */

interface ToolUseMetrics {
    runId: string;
    totalCalls: number;
    /** Calls whose arguments were captured and can be compared for duplication. */
    callsWithCapturedArgs: number;
    byTool: Record<string, ToolStats>;
    errorRate: number;
    /** Ratio of captured-argument calls already seen with the same tool name and arguments. */
    duplicateRate: number;
    /** Ratio of error calls followed by ≥1 retry on same tool. */
    retryRate: number;
    /** Optional: of the calls agent made, fraction the evaluator marked as "correct selection". */
    selectionAccuracy?: number;
}
interface ToolStats {
    calls: number;
    callsWithCapturedArgs: number;
    errors: number;
    avgLatencyMs: number;
    duplicates: number;
}
interface ToolUseOptions {
    /** Map of spanId → whether the evaluator judged the tool selection correct. Optional. */
    selectionLabels?: Record<string, boolean>;
}
declare function computeToolUseMetrics(store: TraceStore, runId: string, options?: ToolUseOptions): Promise<ToolUseMetrics>;

/**
 * Typed query helpers over TraceStore.
 *
 * Not a full SQL engine — a minimal, composable set of operators that
 * cover the canned-pipeline use cases. For ad-hoc analytics, persist to
 * NDJSON and point DuckDB at it; the schema is stable so external SQL
 * tooling works out of the box.
 */

declare function llmSpans(store: TraceStore, runId?: string): Promise<LlmSpan[]>;

/**
 * ToolWasteView — fraction of tool calls whose results weren't used
 * downstream. Without a "used" signal we fall back to structural
 * proxies: error calls, duplicate calls, and tool calls followed by
 * zero subsequent LLM spans are all considered waste.
 *
 * Consumers can pass a `usageOracle` that inspects a tool span and
 * returns true iff the tool's result appears in a later LLM message,
 * artifact, or state mutation — that's the canonical definition; the
 * default heuristic is a reasonable fallback.
 */

interface ToolWasteFinding {
    runId: string;
    wastedCalls: number;
    totalCalls: number;
    wasteRate: number;
}
interface ToolWasteReport {
    byRun: ToolWasteFinding[];
    overallWasteRate: number;
}
interface ToolWasteOptions {
    runId?: string;
    usageOracle?: (tool: ToolSpan, later: {
        llm: Awaited<ReturnType<typeof llmSpans>>;
    }) => boolean;
}
declare function toolWasteView(store: TraceStore, options?: ToolWasteOptions): Promise<ToolWasteReport>;

export { type BudgetBreachFinding, type BudgetBreachReport, type DivergenceOptions, type DivergenceReport, type FailureCluster, type FailureClusterReport, type JudgeAgreementReport, type JudgePair, type RegressionOptions, type RegressionSpec, type StuckLoopFinding, type StuckLoopOptions, type StuckLoopReport, type ToolWasteFinding, type ToolWasteOptions, type ToolWasteReport, budgetBreachView, computeToolUseMetrics, failureClusterView, firstDivergenceView, judgeAgreementView, regressionView, stuckLoopView, toolWasteView };
