/**
 * StructuralPrepass — pluggable backend interface for analyse pre-pass.
 *
 * The pre-pass extracts deterministic structural facts from a source codebase
 * (entities / relationships / lifecycle state literals / etc.) BEFORE the LLM
 * sees it, so the LLM can focus on semantic interpretation rather than
 * structural discovery.
 *
 * Backends: grep-only (zero deps, fallback for tests/CI), codegraph
 * (recommended default), gitnexus (alternative for multi-component cases
 * where Leiden community detection adds value).
 *
 * Adapters: per-framework translators (typescript-prisma first, then
 * typescript-typeorm / python-sqlalchemy / go-gorm / etc.) that consume
 * this interface and produce SpecVerse-vocabulary facts.
 *
 * Design rationale: see specverse-self/docs/proposals/STRUCTURAL-PREPASS-FOR-ANALYSE.md
 */
/** A symbol detected by tree-sitter (or grep heuristics) — class / function / method / etc. */
export interface Symbol {
    kind: 'class' | 'function' | 'method' | 'interface' | 'type_alias' | 'constant' | 'enum';
    name: string;
    /** Fully-qualified name where applicable (e.g. "PollController.evolve"). */
    qualifiedName: string;
    filePath: string;
    startLine: number;
    endLine: number;
    /** Function/method signature, e.g. "(id: string, data: any): Promise<any>" */
    signature?: string;
    /** Leading docstring or JSDoc, if present */
    docstring?: string;
    /** Whether the symbol is exported from its module */
    isExported?: boolean;
    /** Decorators on the symbol (TypeScript / Python / Java) */
    decorators?: string[];
    /** Source-level language (typescript, javascript, python, go, ...) */
    language: string;
}
/** An import edge — file imports symbols from target module. */
export interface Import {
    fromFile: string;
    toModule: string;
    symbols: string[];
}
/** Capability flags — adapters check before using optional methods. */
export interface Capabilities {
    /** Backend can resolve callers/callees of a symbol via call graph. */
    callGraph: boolean;
    /** Backend resolves cross-file references (vs single-file regex). */
    crossFileResolution: boolean;
    /** Backend has community-detection clustering (e.g. Leiden in GitNexus). */
    componentClustering: boolean;
    /** Backend supports full-text search across source. */
    fullTextSearch: boolean;
    /** Backend automatically syncs as files change (e.g. CodeGraph file watchers). */
    fileWatching: boolean;
    /** Backend can extract HTTP routes from router-style frameworks
     *  (Express, Fastify, etc.). Engines 6.30.0+. */
    routeExtraction: boolean;
    /** Backend can extract Class→Interface IMPLEMENTS relationships.
     *  Engines 6.30.0+. */
    implementsExtraction: boolean;
    /** Backend can extract validation-schema declarations (Zod, Yup, Joi,
     *  TypeScript const objects matching schema-shaped patterns).
     *  Engines 6.30.0+. */
    validationSchemaExtraction: boolean;
    /** Backend can extract pre-computed cross-method execution flows
     *  (process traces from call-graph analysis). Currently GitNexus-only —
     *  walk-backend has no equivalent. Engines 6.30.0+. */
    processExtraction: boolean;
}
export interface FileFilter {
    dir?: string;
    lang?: string;
    glob?: string;
}
export interface ClassFilter {
    dir?: string;
    namePattern?: RegExp;
}
export interface MethodFilter {
    /** Class qualified-name (e.g. "OrderProcessorController") */
    class?: string;
    /** Names to filter to — e.g. ['evolve', 'create', 'validate'] */
    nameIn?: string[];
}
export interface InterfaceFilter {
    dir?: string;
    namePattern?: RegExp;
}
export interface IndexResult {
    files: number;
    symbols: number;
    durationMs: number;
}
/**
 * Per-method fact sheet for behavior extraction.
 *
 * The structural pre-pass surfaces these facts from a method's body via
 * tree-sitter call graph (where available) + regex heuristics for common
 * patterns (event emission, DB writes, throws, async boundaries). The
 * SpecVerse adapter layer (and downstream behavior-extraction prompt)
 * consumes these to translate procedural code into spec-vocabulary
 * `behaviors:` blocks with `steps:` decomposition.
 *
 * Design rationale: see specverse-self/docs/proposals/BEHAVIOR-EXTRACTION-FOR-ANALYSE.md
 * — per-method fact sheets shrink the LLM's job from "summarize 200 lines
 * of code" to "given this structured fact sheet, write a SpecVerse behavior
 * block". Smaller cognitive load → smaller variance surface.
 */
export interface MethodFactSheet {
    qualifiedName: string;
    signature: string;
    /** Raw source body (the function body — between { and }). */
    body: string;
    filePath: string;
    startLine: number;
    endLine: number;
    language: string;
    /**
     * Methods/functions this one invokes (call graph).
     * From CodeGraph: SQL on edges table (kind='call').
     * From grep-only: regex for `(\w+)\(` calls within the body.
     */
    calls: Symbol[];
    /**
     * Event names emitted from this method's body.
     * Patterns matched: emit() / dispatchEvent() / .next() (RxJS) /
     * eventBus.publish() / pubsub.publish() / send() with first-arg literal.
     */
    emits: string[];
    /**
     * Persisted-state writes detected in the body (per ORM heuristic).
     * Prisma: prisma.X.create() / .update() / .delete() / .upsert().
     * TypeORM: repository.save() / .update() / .remove().
     * SQLAlchemy: session.add() / .delete() / commit-tracked mutations.
     * For arbitrary code, populated only when the adapter knows the ORM.
     */
    dbWrites: Array<{
        entity: string;
        field?: string;
        op: 'create' | 'update' | 'delete' | 'upsert' | 'unknown';
    }>;
    /**
     * External system calls detected in the body.
     * Patterns: fetch() / axios.X() / http.request() (HTTP),
     * kafka.send() / rabbit.publish() (queue), redis.set() / cache.set() (cache).
     */
    externalCalls: Array<{
        kind: 'http' | 'queue' | 'cache' | 'unknown';
        target?: string;
    }>;
    /**
     * Explicit throw statements with their error type. `throw new BadRequestError(...)`
     * → `BadRequestError`. Useful for inferring preconditions / error states.
     */
    throws: string[];
    /**
     * Async boundaries — locations where the method awaits, runs in parallel,
     * or races. Useful for distinguishing sequential from parallel steps.
     */
    asyncBoundaries: Array<{
        type: 'await' | 'promise.all' | 'promise.race' | 'promise.allSettled';
        line: number;
    }>;
    /**
     * Cyclomatic complexity proxy: count of branch points (if/else/switch/catch/ternary).
     * High values suggest the LLM should look for branching steps in spec.
     */
    branchPoints: number;
    /**
     * For SpecVerse-realized backends: the body has comment-delineated regions
     * (PRECONDITIONS / EXECUTE / POSTCONDITIONS / EVENTS). When detected, the
     * regions are sliced out for the verify-behavior pass to cross-check spec
     * preconditions/postconditions/events against source-side markers.
     *
     * For arbitrary backends, all fields here are undefined.
     */
    bodyTextSliced?: {
        preconditions?: string;
        execute?: string;
        postconditions?: string;
        events?: string;
    };
}
/**
 * Pluggable backend for structural extraction. Implementations:
 *   - backends/grep-only.ts   — no external tools, regex per language
 *   - backends/codegraph.ts   — tree-sitter via CodeGraph CLI + SQLite
 *   - backends/gitnexus.ts    — tree-sitter via GitNexus MCP + LadybugDB
 */
export interface StructuralPrepass {
    /** Initialize the backend on a source directory. */
    init(sourceDir: string): Promise<void>;
    /** Build / refresh the index. Returns stats. May be a no-op on grep-only. */
    index(): Promise<IndexResult>;
    /** List files in scope, optionally filtered. */
    listFiles(filter?: FileFilter): Promise<string[]>;
    /** List classes (or class-like declarations across languages). */
    listClasses(filter?: ClassFilter): Promise<Symbol[]>;
    /** List methods on classes. Class membership encoded in qualifiedName. */
    listMethods(filter?: MethodFilter): Promise<Symbol[]>;
    /** List interfaces / type-defs. */
    listInterfaces(filter?: InterfaceFilter): Promise<Symbol[]>;
    /** List imports for a single file. */
    listImports(file: string): Promise<Import[]>;
    /** Read raw source text. Adapters use this for regex extraction of literals. */
    fileSourceText(file: string): Promise<string>;
    /**
     * Optional: callers/callees graph traversal.
     * Throws if `capabilities.callGraph === false`.
     */
    callers?(symbol: string): Promise<Symbol[]>;
    callees?(symbol: string): Promise<Symbol[]>;
    /**
     * Get the per-method fact sheet for a single method (by qualified name,
     * e.g. "OrderProcessorController.processOrder"). Returns null if the
     * method isn't found or isn't analyseable.
     *
     * All backends implement this — grep-only via regex over the method body,
     * CodeGraph via SQL on the edges table for call data + regex for everything
     * else (events, dbWrites, etc. aren't tree-sitter symbols, they're patterns).
     */
    getMethodDetails(qualifiedName: string): Promise<MethodFactSheet | null>;
    /**
     * Optional: cluster files into communities (Leiden / similar).
     * Throws if `capabilities.componentClustering === false`.
     */
    clusterFiles?(): Promise<Array<{
        id: string;
        files: string[];
    }>>;
    /**
     * Optional: list HTTP routes detected in router-style frameworks
     * (Express, Fastify). Engines 6.30.0+ (TODO #51 phase 1).
     *
     * GitNexus emits `Route` nodes + `HANDLES_ROUTE` edges natively.
     * Walk-backend implements via regex over `**\/routes/**` files
     * (lifted from the engines 6.27.x express-routes adapter).
     *
     * `responseKeys` / `errorKeys` / `middleware` are best-effort —
     * GitNexus may populate them when its handler-shape analysis fires;
     * walk-backend leaves them empty.
     *
     * Throws if `capabilities.routeExtraction === false`.
     */
    listRoutes?(): Promise<Array<{
        filePath: string;
        httpVerb: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'all' | 'head' | 'options';
        routePath: string;
        /** Handler reference — function name when available, else synthesized. */
        handlerName: string;
        /** Source line range of the full route declaration. Best-effort. */
        sourceLineRange?: [number, number];
        /** Response keys extracted from handler body (e.g. `res.json({foo, bar})` → `["foo","bar"]`). Optional. */
        responseKeys?: string[];
        /** Error keys / status codes thrown / returned. Optional. */
        errorKeys?: string[];
        /** Middleware names invoked before the handler. Optional. */
        middleware?: string[];
        /** When the handler is an inline arrow/function, the body for downstream
         *  classification. When it's a named ref (`router.post('/x', registerHandler)`),
         *  empty — adapters can resolve the named ref via listMethods/listClasses. */
        handlerBody?: string;
    }>>;
    /**
     * Optional: list Class → Interface IMPLEMENTS relationships. Engines
     * 6.30.0+ (TODO #51 phase 2). Maps to SpecVerse's `provides:` /
     * `requires:` capability slots.
     *
     * GitNexus emits `IMPLEMENTS` edges natively. Walk-backend implements
     * via regex over `class X implements Y` declarations.
     *
     * Throws if `capabilities.implementsExtraction === false`.
     */
    listImplementsRelationships?(): Promise<Array<{
        /** The implementing class name (subject). */
        className: string;
        /** The implemented interface name (object). */
        interfaceName: string;
        classFilePath: string;
        /** Optional — interface declaration file path when resolved. */
        interfaceFilePath?: string;
    }>>;
    /**
     * Optional: list validation-schema declarations. Engines 6.30.0+
     * (TODO #51 phase 3). Targets Zod (`z.object`, `z.string`, etc.),
     * Yup, Joi, and any other schema-shaped const declarations.
     *
     * GitNexus emits `Const` nodes with `name` + `content` properties
     * natively. Walk-backend implements via regex over `*.ts`/`*.tsx`
     * files for `export const X(Schema|Shape) = z.object(...)` patterns
     * and similar.
     *
     * Adapters consume the raw content and parse for shape (Zod field
     * declarations, etc.) — the interface returns the raw declaration
     * because schema libraries vary too much for a generic structured
     * representation.
     *
     * Throws if `capabilities.validationSchemaExtraction === false`.
     */
    listConstSchemas?(): Promise<Array<{
        name: string;
        filePath: string;
        /** Raw const declaration content (RHS of `=`). Adapter parses for shape. */
        content: string;
        /** Source line range. Best-effort. */
        sourceLineRange?: [number, number];
        /** Detected library (zod, yup, joi, etc.) when the content gives a
         *  clear signal. Optional — adapter may also infer. */
        library?: string;
    }>>;
    /**
     * Optional: list pre-computed cross-method execution flows. Engines
     * 6.30.0+ (TODO #51 phase 4). Currently GitNexus-only — walk-backend
     * has no equivalent (would require call-graph analysis we don't do).
     *
     * Each process is a heuristic-labelled trace from an entry point
     * (route handler, exported function) through a sequence of method
     * calls to a terminal (response, throw, leaf method). Adapters use
     * high-stepCount processes (≥ N) to seed `behaviors:` action shells
     * with pre-grouped step sequences.
     *
     * Throws if `capabilities.processExtraction === false`.
     */
    listProcesses?(): Promise<Array<{
        id: string;
        /** Heuristic label like "AuthProvider → IsAuthenticated". */
        label: string;
        /** Symbol id (qualifiedName-like) of the entry point. */
        entryPointId: string;
        /** Symbol id of the terminal step. */
        terminalId: string;
        /** Total steps in the process. */
        stepCount: number;
        /** intra_community = within one entity's class graph; cross_community
         *  = spans multiple entities (often more interesting for behaviours). */
        processType: 'cross_community' | 'intra_community' | string;
        /** Ordered steps; each step references a symbol id. */
        steps: Array<{
            symbolId: string;
            step: number;
        }>;
    }>>;
    /** Capability flags — adapters check before calling optional methods. */
    capabilities: Capabilities;
}
//# sourceMappingURL=interface.d.ts.map