import { FindingSubject, AnalystFinding } from '@tangle-network/agent-eval';
import { I as ImprovementAdapter } from './types-BC3bZpH0.js';

/**
 * `AgentSurfaces` — declarative map of the mutable file/directory paths
 * the self-improvement loop can edit on behalf of an agent.
 *
 * The substrate uses this map to resolve every parsed `FindingSubject`
 * (from agent-eval) to a real on-disk path. No per-vertical glue;
 * no fabricated paths; no silent `existsSync(...)` skips that hide
 * misconfiguration from the operator.
 *
 * Surfaces are validated at `defineAgent` time — missing paths fail
 * loud with a list of every offender. A surface that's not needed
 * (e.g. an agent with no RAG corpora) is simply omitted; the loop
 * refuses to route those subjects rather than fabricating a target.
 */

/**
 * Surface declarations. Every path is repo-relative (or absolute) at
 * `defineAgent` time. At resolution time, paths are joined against the
 * agent's `repoRoot`.
 *
 * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends
 * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.
 * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in
 * place.
 *
 * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);
 * `applyKnowledgeWriteBlocks` writes pages relative to it.
 *
 * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)
 * can be omitted — the loop will reject findings targeting them with a
 * clear log message instead of fabricating a path.
 */
interface AgentSurfaces {
    /** Directory containing one markdown file per system-prompt section. */
    systemPrompt: string;
    /** Directory containing one subdir per tool (`<tool>/README.md`). */
    tools: string;
    /** Single file (TypeScript module) defining the rubric weights + dimensions. */
    rubric: string;
    /** Knowledge-base root; typically `.agent-knowledge`. */
    knowledge: string;
    /** Directory containing one YAML/JSON file per persona. */
    personas: string;
    /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */
    scaffolding?: string;
    /** Optional: memory store path (JSONL / SQLite / DB). */
    memory?: string;
    /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */
    rag?: string;
    /** Optional: single file defining the output schema (Zod / JSON Schema). */
    outputSchema?: string;
}
interface ResolvedSurface {
    /** Absolute filesystem path the operator can `cat` / `vim`. */
    absolutePath: string;
    /** Repo-relative path for PR descriptions, diffs, audit logs. */
    repoRelativePath: string;
    /** Whether the path currently exists on disk. */
    exists: boolean;
    /** The substrate's intent: edit an existing file or create a new one. */
    intent: 'edit-existing' | 'create-new';
}
/**
 * Resolve a parsed `FindingSubject` to the file path the substrate
 * should edit (or create) on disk.
 *
 * Returns `null` when:
 *   - the subject targets a surface the agent didn't declare
 *     (e.g. `rag:*` when `surfaces.rag` is undefined), OR
 *   - the subject is a `cluster` (failure-mode emits these as evidence,
 *     not actionable mutations — they don't route to a file).
 *
 * Returns a `ResolvedSurface` with `intent: 'create-new'` when the
 * subject names a path that doesn't yet exist (e.g. a new wiki page).
 * The caller chooses whether to honour the create — for tightly-managed
 * surfaces like `systemPrompt` it's usually a contract violation
 * (the analyst named a section that doesn't exist); for `knowledge`
 * it's the whole point.
 */
declare function resolveSubjectPath(subject: FindingSubject, surfaces: AgentSurfaces, repoRoot: string): ResolvedSurface | null;
/**
 * Validate that every declared surface exists on disk under `repoRoot`.
 *
 * Returns an array of `SurfaceValidationIssue` — empty when all required
 * surfaces resolve. `defineAgent` throws with the issues rendered, so
 * a misconfigured manifest fails at startup (not at the first finding
 * the loop produces 20 minutes later).
 */
interface SurfaceValidationIssue {
    surface: keyof AgentSurfaces;
    path: string;
    reason: 'missing' | 'not-directory' | 'not-file';
}
/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */
declare function validateSurfaces(surfaces: AgentSurfaces, repoRoot: string): ReadonlyArray<SurfaceValidationIssue>;
/** Format a list of surface validation issues into a human-readable error string. */
declare function renderSurfaceIssues(issues: ReadonlyArray<SurfaceValidationIssue>, repoRoot: string): string;

/**
 * Substrate-default `ImprovementAdapter` — surfaces-driven, LLM-drafted
 * patches, optional auto-apply or PR-open.
 *
 * This is the one ImprovementAdapter every vertical agent uses. The
 * substrate parses each finding's `subject` via
 * `parseFindingSubject` (agent-eval), resolves it to a real file path
 * via the agent's `AgentSurfaces`, reads the current content, and asks
 * an LLM to draft a unified-diff patch given the finding + current
 * content + per-kind editing-discipline rules.
 *
 * Auto-apply gates on the source-finding's confidence and the
 * autoApply.improvement policy. Two modes:
 *   `write` — apply the patch in-place via `git apply -p0`. Operator
 *     reviews via `git diff`.
 *   `open-pr` — write to a branch, commit, push, open a PR via `gh`.
 *     Operator reviews via the PR UI.
 *
 * Fail-loud rules:
 *   - Findings whose subject doesn't parse → counted in `errors`.
 *   - Findings whose subject targets an undeclared surface → counted in
 *     `errors` with the offending kind in the message.
 *   - Findings whose target path doesn't exist AND the kind isn't a
 *     create-new variant (`new-tool`, `knowledge.wiki`) → counted in
 *     `errors` with the resolved path in the message.
 *   - LLM drafts that fail JSON-schema validation → counted in
 *     `errors` with the schema issue.
 *
 * No silent skips. Every dropped finding has a recorded reason the
 * loop's report surfaces.
 */

interface SurfaceImprovementEdit {
    /** Stable id derived from the source finding so re-proposals are idempotent. */
    id: string;
    /** The finding that produced this edit — for revert + audit trail. */
    sourceFindingId: string;
    /** Parsed subject; included so the apply step doesn't re-parse. */
    subject: FindingSubject;
    /** Resolved on-disk target. */
    target: ResolvedSurface;
    /** SHA-256 of the current file content the patch was drafted against. */
    baseSha256: string;
    /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */
    patch: string;
    /** One-line summary the operator sees in the report / PR title. */
    summary: string;
    /** Multi-line rationale for the PR body — finding context + LLM reasoning. */
    rationale: string;
    /** Carry-forward from the finding so the apply gate can check the threshold. */
    confidence: number;
    /** Carry-forward severity for prioritization. */
    severity: AnalystFinding['severity'];
}
interface CreateSurfaceImprovementAdapterOpts {
    surfaces: AgentSurfaces;
    repoRoot: string;
    /**
     * LLM-draft callback. Given a finding + current file content + the
     * resolved target, returns a unified-diff patch + summary + rationale.
     *
     * Required — the substrate doesn't ship a hardcoded prompt; the agent
     * author picks the model (Haiku for cheap routine drafts, Sonnet for
     * substantive prompt rewrites, etc.) via this callback.
     */
    draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>;
    /**
     * Apply mode:
     *   `write` — `git apply` in-place; operator reviews via `git diff`
     *   `open-pr` — branch + commit + push + `gh pr create`
     *   `none` — never apply; collect proposals for the report only
     *
     * The `apply` method honours this even when the loop calls it; the
     * effective behaviour is also gated on the per-finding confidence
     * threshold via `runAnalystLoop`'s `autoApply` policy.
     */
    mode?: 'write' | 'open-pr' | 'none';
    /** When `mode === 'open-pr'`, the base branch new PRs target. Default: `main`. */
    baseBranch?: string;
    /** Required for `mode === 'open-pr'` — the GH owner/repo (`tangle-network/tax-agent`). */
    ghRepo?: string;
    /**
     * When the resolved target doesn't exist, allow the substrate to
     * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default
     * true for those kinds, false for `system-prompt` / `rubric` / etc.
     * (named sections that don't exist are a contract violation, not a
     * scaffolding opportunity).
     */
    allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>;
}
interface DraftPatchInput {
    finding: AnalystFinding;
    subject: FindingSubject;
    target: ResolvedSurface;
    /** Current file content (empty string when `intent === 'create-new'`). */
    currentContent: string;
}
interface DraftPatchOutput {
    /** Unified diff against the current file content. Empty string skips this finding. */
    patch: string;
    /** One-line summary for the operator. */
    summary: string;
    /** Multi-line rationale for the PR body. */
    rationale: string;
}
/** The substrate-default `ImprovementAdapter`: resolve each finding's subject to a real surface path, LLM-draft a unified-diff patch, then auto-apply or open a PR. */
declare function createSurfaceImprovementAdapter(opts: CreateSurfaceImprovementAdapterOpts): ImprovementAdapter<SurfaceImprovementEdit>;

export { type AgentSurfaces as A, type CreateSurfaceImprovementAdapterOpts as C, type DraftPatchInput as D, type ResolvedSurface as R, type SurfaceImprovementEdit as S, type DraftPatchOutput as a, type SurfaceValidationIssue as b, createSurfaceImprovementAdapter as c, resolveSubjectPath as d, renderSurfaceIssues as r, validateSurfaces as v };
