import * as _tangle_network_agent_eval from '@tangle-network/agent-eval';
import { TraceAnalystKindSpec, AnalystFinding } from '@tangle-network/agent-eval';
import { A as ArtifactKind, C as CandidateGenerator, P as PromotionGate } from './generator-YkAQrOoD.js';
import { a as RuntimeStreamEvent, S as SandboxClient, b as OutputAdapter, A as AgentRunSpec } from './types-ESeMOj94.js';
import { A as AgentSurfaces } from './improvement-adapter-CDR8QNVM.js';
export { C as CreateSurfaceImprovementAdapterOpts, D as DraftPatchInput, a as DraftPatchOutput, R as ResolvedSurface, S as SurfaceImprovementEdit, b as SurfaceValidationIssue, c as createSurfaceImprovementAdapter, r as renderSurfaceIssues, d as resolveSubjectPath, v as validateSurfaces } from './improvement-adapter-CDR8QNVM.js';
import { K as KnowledgeAdapter, a as RunAnalystLoopResult } from './types-BC3bZpH0.js';
import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from '@tangle-network/agent-interface';
import { SandboxEvent } from '@tangle-network/sandbox';

/**
 * The full agent manifest. Each agent ships ONE of these.
 *
 * Generics:
 *   `TPersona` — the agent's persona shape (loaded from
 *     `surfaces.personas`). Defaults to `unknown` so the substrate's
 *     persona discovery (`loadPersonas`) can accept anything; per-agent
 *     code re-narrows when it matters.
 *   `TRunOutput` — the shape `runtime.act` returns. Used by the rubric
 *     scorers and emitted into the trace.
 */
interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {
    /**
     * Stable identifier — used as `projectId` in traces, as the analyst
     * loop's `runId` prefix, and as the namespace under which findings
     * are persisted. MUST match the agent's repo name to keep
     * cross-repo telemetry joinable.
     */
    id: string;
    /**
     * Filesystem root the substrate resolves surface paths against.
     * Typically `process.cwd()` or a fixed absolute path. Use an
     * absolute path when the agent's tests may run from subdirectories
     * (vitest sometimes shifts cwd).
     */
    repoRoot: string;
    /**
     * Map of mutable surfaces the self-improvement loop can edit. See
     * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,
     * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,
     * `outputSchema`.
     *
     * Every required path is validated at `defineAgent` time. Missing
     * paths throw with the full list of offenders.
     */
    surfaces: AgentSurfaces;
    /**
     * Rubric the substrate uses to score each run. Dimensions × weights
     * × judges. The substrate computes the weighted composite and
     * stamps it into the RunRecord.
     */
    rubric: AgentRubric<TRunOutput>;
    /**
     * Runtime adapter — how the substrate INVOKES the agent against a
     * persona. The `act` function takes a persona + a context (with the
     * tracer the substrate threads through for span emission) and
     * returns the run output the rubric will score.
     *
     * The agent's existing production runtime goes in here; the
     * substrate is intentionally thin around it.
     */
    runtime: AgentRuntime<TPersona, TRunOutput>;
    /**
     * Persona discovery — the substrate loads personas via this function
     * at eval start. Can read from `surfaces.personas`, an API, or be
     * hardcoded. The substrate calls it once per `runAgentEval` call;
     * persona ordering is preserved.
     */
    personas: () => Promise<ReadonlyArray<TPersona>>;
    /**
     * Analyst kinds the substrate runs against each persona's trace.
     * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent
     * authors can prune (e.g. skip `knowledge-poisoning` when there's no
     * knowledge base) or extend (custom domain kinds).
     *
     * Empty array disables the loop — useful for `pnpm eval --no-analyst`.
     */
    analystKinds: ReadonlyArray<TraceAnalystKindSpec>;
    /**
     * Analyst LLM configuration. The substrate uses these for all four
     * kinds (override per-kind via `analystKinds` if needed).
     */
    analyst: AnalystConfig;
    /**
     * Auto-apply policy. Knowledge / improvement edits land only when
     * `enabled === true` AND the source finding's confidence meets the
     * threshold. `mode` controls how applies happen: `'write'` mutates
     * files in-place; `'open-pr'` writes to a branch and opens a PR.
     *
     * Default: knowledge auto-applies at confidence ≥0.85 in `'write'`
     * mode (wiki edits are git-reversible); improvement stays at
     * `enabled: false` until the agent author has measured precision.
     */
    autoApply?: AutoApplyPolicy;
    /**
     * Declarative per-surface artifact-lifecycle config the closed loop reads.
     *
     * Each entry names a profile surface (`skill` / `tool` / `prompt` / `mcp` /
     * `hook` / `subagent`) and supplies the `CandidateGenerator` that grows it +
     * the `PromotionGate` (the held-back exam) that decides promotion. `runLifecycle`
     * consumes these: it pools the generators, measures each candidate's marginal
     * lift on the held-back split, gates it, and stores the winners in an
     * `ArtifactRegistry` — then `composeProfile` folds the top-`k` active artifacts
     * back into this agent's profile.
     *
     * Optional — agents that don't self-improve their profile omit it. An empty or
     * absent map means "no lifecycle"; the manifest is otherwise unchanged.
     */
    lifecycles?: ReadonlyArray<SurfaceLifecycle>;
}
/**
 * One profile surface's artifact-lifecycle wiring — the declarative config a
 * `defineAgent` manifest carries and `runLifecycle` reads. It is config, not
 * execution: it names the generator + gate; the loop runs them.
 */
interface SurfaceLifecycle {
    /** The profile surface this lifecycle grows. */
    surface: ArtifactKind;
    /** Produces fresh candidate artifacts for `surface` from the agent's history. */
    generator: CandidateGenerator;
    /** The held-back exam that decides promotion of a measured candidate. */
    gate: PromotionGate;
    /** Top-`k` budget for `composeProfile` when folding this surface's promoted
     *  artifacts back in. Omit to fold in every active artifact. */
    composeK?: number;
}
interface AgentRubric<TRunOutput> {
    /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */
    dimensions: ReadonlyArray<RubricDimension<TRunOutput>>;
    /**
     * Optional judges layered on top of deterministic dimensions. Each
     * judge returns a score per dimension; the substrate averages judges
     * (mean by default) for the LLM contribution.
     */
    judges?: ReadonlyArray<JudgeConfig<TRunOutput>>;
}
interface RubricDimension<TRunOutput> {
    /** Unique identifier — appears in finding subjects (`rubric:<id>`). */
    id: string;
    /** 0..1 — weight in the composite. */
    weight: number;
    /**
     * Deterministic scorer: given the persona + run output, returns a
     * 0..1 score. The substrate sums weight × score across dimensions
     * for the deterministic composite; judges supplement subjective dims.
     */
    score: (input: {
        persona: unknown;
        output: TRunOutput;
    }) => number;
    /** Optional human-readable label for reports. */
    label?: string;
}
interface JudgeConfig<TRunOutput> {
    /** Judge identifier — appears in trace spans + manifest. */
    id: string;
    /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */
    model: string;
    /** Dimensions this judge scores. */
    dimensions: ReadonlyArray<string>;
    /**
     * Optional rubric anchors — text examples the judge sees as a
     * few-shot prompt to calibrate. STRONGLY recommended for subjective
     * dimensions; required by the calibration gate (Pearson ≥0.7).
     */
    anchors?: ReadonlyArray<{
        input: string;
        output: TRunOutput;
        expected: Record<string, number>;
    }>;
}
interface AgentRuntime<TPersona, TRunOutput> {
    /**
     * Invoke the agent against one persona. Returns BOTH:
     *   - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric
     *     product consumes verbatim (SSE / WebSocket / inline render).
     *     **Streaming is mandatory — never collapse this to a single Promise.**
     *     The agent's existing `runChatTurn` (or equivalent async generator)
     *     plugs in here directly.
     *   - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream
     *     drains. The eval substrate awaits this for rubric scoring; chat
     *     products usually ignore it (they already rendered incrementally).
     *
     * Implementation contract:
     *   1. `act` MUST return immediately (synchronous construction of the
     *      `events` iterator + the `output` promise).
     *   2. Iterating `events` drives the underlying LLM/tool calls — the
     *      caller chooses when to consume.
     *   3. `output` resolves only after the iterator yields its terminal
     *      event (typically `task_end`); see `collectAgentRun` helper.
     *
     * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes
     * SHOULD record LLM/tool spans through it for capture integrity.
     * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful
     * cancel. `ctx.signal` is the standard abort signal.
     */
    act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>;
}
interface AgentRunInvocation<TRunOutput> {
    /** Live stream of typed runtime events. Consumed by chat UX directly. */
    events: AsyncIterable<RuntimeStreamEvent>;
    /** Final structured output the rubric scores. Resolves after `events` drains. */
    output: Promise<TRunOutput>;
}
/**
 * Stub for agents whose `runtime.act` is not yet wired to the substrate's
 * eval path. Preserves the streaming contract (empty event stream + a
 * rejected `output` promise that tells the caller exactly what to fix).
 *
 * Per-vertical manifests usually start with this stub and replace it with
 * the agent's real streaming runtime (`runChatTurn` or equivalent) once
 * the eval path consumes the manifest end-to-end.
 */
declare function unimplementedAgentRun<TRunOutput = unknown>(reason?: string): AgentRunInvocation<TRunOutput>;
/**
 * Drain `act`'s `events` into an array AND await its `output`. Useful for
 * eval / outcome-measurement code paths that don't care about live
 * rendering. The events array is preserved so the substrate can inspect
 * tool calls / readiness / questions retrospectively.
 *
 * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming
 * (no incremental render). Use `for await (const ev of invocation.events)`
 * directly in the chat surface.
 */
declare function collectAgentRun<TRunOutput>(invocation: AgentRunInvocation<TRunOutput>): Promise<{
    events: ReadonlyArray<RuntimeStreamEvent>;
    output: TRunOutput;
}>;
interface AgentRunContext {
    /** Substrate-managed trace emitter. */
    emitter: _tangle_network_agent_eval.TraceEmitter;
    /** Stable run id for this persona × variant cell. */
    runId: string;
    /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */
    variantId?: string;
    /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */
    deadlineMs?: number;
    /** Optional abort signal. */
    signal?: AbortSignal;
}
interface AnalystConfig {
    /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */
    model: string;
    /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */
    budgetUsd?: number;
    /** Backend hint for the AxAIService factory — same shape every kind uses. */
    backend?: {
        name?: 'openai' | 'router';
        apiKey?: string;
        baseUrl?: string;
    };
}
interface AutoApplyPolicy {
    knowledge?: {
        enabled: boolean;
        confidenceThreshold?: number;
        mode?: 'write' | 'open-pr';
    };
    improvement?: {
        enabled: boolean;
        confidenceThreshold?: number;
        mode?: 'write' | 'open-pr';
    };
}
/** Thrown when `defineAgent` finds a required surface missing on disk. */
declare class AgentManifestError extends Error {
    readonly agentId: string;
    readonly issues: ReadonlyArray<unknown>;
    constructor(message: string, agentId: string, issues?: ReadonlyArray<unknown>);
}
/**
 * Construct a validated agent manifest. Throws `AgentManifestError`
 * if any required surface is missing on disk.
 *
 * Generics: pass your persona / output types if you want narrowed
 * `runtime.act` signatures:
 *   `defineAgent<TaxPersona, TaxRunOutput>({ ... })`
 *
 * Most callers don't need the generics — the substrate operates on
 * `unknown` payloads internally and the manifest's `score` /
 * `runtime.act` see the typed shapes via TypeScript inference at
 * the call site.
 */
declare function defineAgent<TPersona = unknown, TRunOutput = unknown>(manifest: AgentManifest<TPersona, TRunOutput>): AgentManifest<TPersona, TRunOutput>;

/**
 * Substrate-default `KnowledgeAdapter` — wraps agent-knowledge's
 * `proposeFromFindings` + `applyKnowledgeWriteBlocks` with substrate
 * defaults (auto-lint after apply, source linkage via finding id).
 *
 * Every agent that ships a `.agent-knowledge/` tree uses this adapter
 * unmodified. Per-agent customization happens at the manifest level
 * (`autoApply.knowledge.confidenceThreshold`, etc.), not by writing a
 * new adapter.
 *
 * Lint discipline: after each apply we run agent-knowledge's
 * `lintKnowledgeIndex` to catch broken links / circular claims /
 * duplicate pages introduced by the new writes. Findings that fail the
 * post-apply lint are recorded in `warnings`; the apply itself is not
 * rolled back (lint failures are soft — humans review the wiki state).
 */

interface CreateSurfaceKnowledgeAdapterOpts {
    /** `.agent-knowledge/` root (absolute path the substrate writes blocks against). */
    knowledgeRoot: string;
}
/**
 * Build the adapter. We accept the agent-knowledge functions as DI so
 * the substrate stays decoupled from a specific agent-knowledge
 * version — the agent author imports them in their manifest module
 * and hands them to the factory.
 *
 * `proposeFromFindings(findings)` returns
 *   `{ proposals: KnowledgeProposal[]; skipped: number; errors: ... }`.
 *
 * `applyKnowledgeWriteBlocks(root, content)` returns
 *   `{ written: string[]; warnings: string[] }`.
 *
 * `lintKnowledgeIndex(index)` (optional) returns `KnowledgeLintFinding[]`.
 */
interface KnowledgeAdapterDeps<TProposal> {
    proposeFromFindings: (findings: ReadonlyArray<AnalystFinding>) => {
        proposals: TProposal[];
        skipped: number;
        errors: Array<{
            findingId: string;
            subject: string;
            message: string;
        }>;
    };
    applyKnowledgeWriteBlocks: (root: string, proposalText: string) => Promise<{
        written: string[];
        warnings: string[];
    }>;
    /**
     * Optional post-apply lint hook. The substrate runs it after each
     * batch of writes; failures land in `warnings` (the apply is not
     * rolled back — lint signals drift to review, not block).
     */
    lintAfterApply?: (root: string) => Promise<ReadonlyArray<string>>;
}
/** Wire a surface-based `KnowledgeAdapter` that writes analyst proposals to agent surface files. */
declare function createSurfaceKnowledgeAdapter<TProposal>(opts: CreateSurfaceKnowledgeAdapterOpts, deps: KnowledgeAdapterDeps<TProposal>): KnowledgeAdapter<TProposal>;

/**
 * `OutcomeMeasurement` — the missing metric that turns the analyst
 * loop from "observability" into "self-improvement".
 *
 * Without this hook, the loop reports process counts (`findings: 42`,
 * `applied: 7`) and never proves the applied edits actually improved
 * anything. With this hook, the substrate re-runs the cohort against
 * the same personas after each apply pass and reports a composite
 * score delta. A negative delta is the substrate's strongest signal
 * to either roll back or surface for review.
 *
 * Wiring is intentionally simple: pass the manifest + the `runAgentEval`
 * function and a list of `personaIds` to re-run. The wrapper:
 *   1. Captures the baseline composite from the just-finished run.
 *   2. After `runAnalystLoop` returns, re-invokes `runAgentEval` against
 *      the same persona slice.
 *   3. Computes the delta and appends to `loop-report.json`.
 *   4. If `rollbackOnRegression` and delta < 0, reverts applied edits.
 */

interface OutcomeMeasurement {
    /** Baseline composite before applies — captured from the most-recent eval run. */
    baselineComposite: number;
    /** Composite after re-running the cohort with applied edits. */
    afterComposite: number;
    /** `afterComposite - baselineComposite`. Positive = the loop improved the agent. */
    delta: number;
    /** Per-persona deltas for finer-grained review. */
    perPersona: ReadonlyArray<{
        personaId: string;
        before: number;
        after: number;
        delta: number;
    }>;
    /** When the substrate rolled back applies due to regression, the paths reverted. */
    rolledBackPaths: ReadonlyArray<string>;
}
interface OutcomeMeasurementOpts {
    /** Composite scores from the run that produced the findings. */
    baseline: ReadonlyArray<{
        personaId: string;
        composite: number;
    }>;
    /**
     * Re-run callback — the substrate invokes this after applies. The
     * agent author provides their `runAgentEval`-equivalent so the
     * substrate can ask "score this persona slice now."
     *
     * The callback SHOULD reuse the same cohort + judges + variant as
     * the baseline run; only the agent's mutable surfaces have changed.
     */
    reRunCohort: (personaIds: ReadonlyArray<string>) => Promise<ReadonlyArray<{
        personaId: string;
        composite: number;
    }>>;
    /** When `true`, applied edits are reverted on negative delta. Default `false`. */
    rollbackOnRegression?: boolean;
    /** Callback to revert a list of paths (typically `git checkout HEAD --`). */
    revert?: (paths: ReadonlyArray<string>) => Promise<void>;
}
/**
 * Run `runAnalystLoop` and stamp an `OutcomeMeasurement` onto the
 * result. The substrate calls this after each canonical eval; the
 * delta lands in `loop-report.json` for cross-run trend analysis.
 *
 * The function returns the original `RunAnalystLoopResult` enriched
 * with `outcome` so callers stay backwards-compatible (the field is
 * optional on the type; missing means no measurement was wired).
 */
declare function measureOutcome<TProposal, TEdit>(result: RunAnalystLoopResult<TProposal, TEdit>, opts: OutcomeMeasurementOpts): Promise<RunAnalystLoopResult<TProposal, TEdit> & {
    outcome: OutcomeMeasurement;
}>;

/**
 * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.
 *
 * The point of this adapter is parity: the eval substrate must run the agent
 * through the SAME profile the production chat turn uses, or scorecard numbers
 * grade a profile that never ships. `createSandboxAct` boots a sandbox with the
 * agent's profile (the caller's `baseProfile`, with optional per-persona
 * overrides) through the loop kernel's own {@link createSandboxForSpec},
 * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`
 * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring
 * — satisfying the `act` streaming contract with one code path shared by chat
 * and eval.
 *
 * Agents with a bespoke streaming chat turn should wire THAT into `act`
 * directly (the contract is designed for it); this adapter is the default for
 * agents whose turn is a plain prod-profile sandbox dispatch — notably the
 * agents agent-builder generates.
 */

/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the
 *  per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */
interface SandboxActComposeOverrides {
    /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */
    systemPrompt?: string;
    /** Extra file mounts layered after the base profile's `resources.files`. */
    extraFiles?: AgentProfileFileMount[];
    /** Override the profile `name`. Defaults to the base profile's name. */
    name?: string;
    /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */
    tools?: Record<string, boolean>;
    /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */
    mcpConnections?: Record<string, AgentProfileMcpServer>;
}
interface CreateSandboxActOptions<TPersona, TRunOutput> {
    /** Canonical agent profile — the same one the prod chat turn uses. */
    baseProfile: AgentProfile;
    /** Sandbox client used to boot the per-run sandbox. */
    sandboxClient: SandboxClient;
    /** Persona → prompt. Pure; the eval cell's input. */
    buildPrompt: (persona: TPersona) => string;
    /** Sandbox event stream → typed output the rubric scores. */
    output: OutputAdapter<TRunOutput>;
    /**
     * Per-persona profile overrides (workspace-augmented system prompt, extra
     * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.
     */
    compose?: (persona: TPersona) => SandboxActComposeOverrides;
    /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */
    sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides'];
    /** Stable run name surfaced in mapped `llm_call` events. */
    name?: string;
    /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */
    mapEvent?: (event: SandboxEvent, opts: {
        agentRunName?: string;
    }) => RuntimeStreamEvent | undefined;
}
/**
 * Build an `AgentRuntime.act` implementation backed by a single prod-profile
 * sandbox run. The returned function honours the `act` contract: it returns
 * synchronously with a live `events` iterator and an `output` promise that
 * resolves only after the iterator drains.
 */
declare function createSandboxAct<TPersona, TRunOutput>(options: CreateSandboxActOptions<TPersona, TRunOutput>): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>;

export { type AgentManifest, AgentManifestError, type AgentRubric, type AgentRunContext, type AgentRunInvocation, type AgentRuntime, AgentSurfaces, type AnalystConfig, type AutoApplyPolicy, type CreateSandboxActOptions, type CreateSurfaceKnowledgeAdapterOpts, type JudgeConfig, type KnowledgeAdapterDeps, type OutcomeMeasurement, type OutcomeMeasurementOpts, type RubricDimension, type SurfaceLifecycle, collectAgentRun, createSandboxAct, createSurfaceKnowledgeAdapter, defineAgent, measureOutcome, unimplementedAgentRun };
