/**
 * Per-file allocation diagnostic for `codegraph_explore` (CG-4).
 *
 * The explore response is a fixed byte envelope (`budget.maxOutputChars`, hard-
 * capped at 25K so the host never externalizes the result). WHICH files fill it,
 * and in what proportion, is decided by a long chain of gates, tiers and caps
 * spread across `handleExplore`. That chain is currently unobservable: you can
 * read the output and guess, but you cannot say "this file took 16% of the
 * envelope and that one took 21%" without hand-counting.
 *
 * This module is the instrument. Enabled by `CODEGRAPH_EXPLORE_DEBUG`, it
 * records, for one explore call:
 *   - per candidate file: relevance score, graph (RWR) mass, distinct query-term
 *     hits, ranking flags, render mode, bytes of source actually emitted, that
 *     file's share of the final envelope, whether it was clipped, whether it
 *     carries a flow-spine symbol — and for the ones that didn't render, why;
 *   - totals: envelope vs `maxOutputChars` vs the hard ceiling, source bytes vs
 *     meta-text overhead, files considered at each filter stage, and the score
 *     floor / relevance-gate thresholds that were applied.
 *
 * HARD CONSTRAINT — this ships in the product binary: when the env var is unset
 * the diagnostic must not exist. `start()` returns `null`, every call site is a
 * `diag?.` no-op, and the agent-facing response is byte-identical. The
 * diagnostic never mutates render state, and every method is wrapped so a bug in
 * here can never fail an explore call.
 *
 * Sinks (value of `CODEGRAPH_EXPLORE_DEBUG`):
 *   `1` / `true` / `on` / `yes` / `stderr` → human-readable table on stderr
 *   `json`                                 → one JSON object on stderr
 *   anything else                          → treated as a path; one JSON object
 *                                            per line appended (JSONL sidecar)
 */
import type { ExploreProjectState } from './explore-session-state';
/** How a file's source was rendered into the response. */
export type ExploreRenderMode = 'whole' | 'clusters' | 'focused' | 'skeleton' | 'stale-omitted' | 'backref' | 'dropped';
/** Why a ranked candidate never reached the output. */
export type ExploreSkipReason = 'max-files' | 'cliff' | 'budget-whole-file' | 'budget-clusters' | 'unreadable' | 'no-ranges';
/** Ranking inputs for one candidate file, captured before the render loop. */
export interface ExploreCandidateMeta {
    rank: number;
    score: number;
    graphScore: number;
    termHits: number;
    nodes: number;
    /** The query named this file by PATH — pinned rank/allocation treatment. */
    pinned?: boolean;
    named: boolean;
    central: boolean;
    entry: boolean;
    spine: boolean;
    lowValue: boolean;
    generated: boolean;
    /**
     * Nothing but type declarations in this file, and nothing in the index
     * depends on it (CG-28) — it cannot answer a flow question, so it ranks on
     * discounted signals unless the query named one of the types it declares.
     */
    ambientDeclaration: boolean;
    /**
     * Multiplier `rankPenalty` applied to BOTH `score` and `graphScore` (1 = no
     * penalty). Generated and test/i18n files rank on discounted signals, so the
     * raw values are `score / penalty` — worth reporting, since "why did this
     * generated file lose?" is otherwise invisible in the numbers (CG-10).
     */
    penalty: number;
    /**
     * Which NodeKinds the file's matched symbols were, most-numerous first
     * (`function:4 constant:1`). The scoring is kind-weighted, so this is the
     * breakdown that explains a score — a file carried by one isolated `constant`
     * is the #1500 failure, and it is legible here at a glance.
     */
    kinds: string;
}
/** Budget fields the diagnostic reports. Structural, to avoid a cyclic import. */
interface BudgetShape {
    maxOutputChars: number;
    maxCharsPerFile: number;
    defaultMaxFiles: number;
}
/** One file's line in the report. Also the JSONL sidecar's per-file shape. */
export interface ExploreDiagnosticFile extends ExploreCandidateMeta {
    path: string;
    allowance: number | null;
    /** Reservation + inherited slack — the bound the render paths actually use. */
    spendable: number | null;
    /** Render ceiling after holding back what is still owed to unreached files. */
    funded: number | null;
    render: ExploreRenderMode | null;
    skipped: ExploreSkipReason | null;
    clipped: boolean;
    dedupSavedChars: number;
    dedupCovered: Array<[number, number]>;
    emittedChars: number;
    finalChars: number;
    share: number;
    allocatedShare: number;
}
/**
 * This session's explore history for this project, as of BEFORE the call being
 * reported (CG-17). Present only when the caller tracks session state — the CLI
 * and bare-handler callers don't, so it is absent there rather than zeroed.
 */
export interface ExploreDiagnosticSession {
    /** 1-based index of THIS call within the session, for this project. */
    callIndex: number;
    /** Calls already served this session for this project. */
    priorCalls: number;
    /** Response chars already served this session for this project. */
    priorResponseChars: number;
    /** Files already served source this session, most-recent call first. */
    priorFiles: Array<{
        path: string;
        ranges: Array<[number, number]>;
        bytes: number;
    }>;
}
/** The full report — one per explore call, JSON-serialized to the sink. */
export interface ExploreDiagnosticReport {
    tool: 'codegraph_explore';
    query: string;
    projectRoot: string;
    indexedFileCount: number;
    note?: string;
    /** Session-scoped call state (CG-17); absent when the caller tracks none. */
    session?: ExploreDiagnosticSession;
    budget: {
        maxOutputChars: number;
        maxCharsPerFile: number;
        maxFiles: number;
        hardCeiling: number;
    };
    envelope: {
        /** Chars actually returned to the agent (post-truncation). */
        chars: number;
        /** Chars the render loop produced, BEFORE the hard-ceiling cut. */
        allocatedChars: number;
        overBudget: boolean;
        truncated: boolean;
        sourceChars: number;
        sourceShare: number;
        metaChars: number;
        metaShare: number;
    };
    selection: {
        scoreFloor: number;
        maxGraph: number;
        graphGateThreshold: number;
        graphGateApplied: boolean;
        filesGrouped: number;
        filesPastLowValueFilter: number;
        filesPastScoreFloor: number;
        filesRanked: number;
        filesRenderedByLoop: number;
        filesInFinalOutput: number;
    };
    /**
     * Cross-call source dedup (CG-18): what this call did NOT re-send because an
     * earlier call in this session already sent it, and where those bytes went.
     * `savedChars` 0 with a non-empty session block means nothing overlapped.
     */
    dedup: {
        savedChars: number;
        backReferenced: string[];
        /** Files fully replaced by a pointer — each one also freed a `maxFiles` slot. */
        fullyBackReferenced: string[];
    };
    /** The proportional split (CG-12): what each file was promised, and why. */
    allocation: {
        /** Chars divided among admitted files (envelope minus per-file overhead). */
        pool: number;
        /** Weight threshold the cliff fired at; 0 when nothing was cliffed. */
        cliffAt: number;
        /** Files given zero source — pointers in the not-shown list instead. */
        cliffed: string[];
        /** Sum of reservations. Must not exceed `pool`. */
        reserved: number;
    };
    files: ExploreDiagnosticFile[];
}
export declare class ExploreDiagnostics {
    private readonly sink;
    private readonly query;
    private readonly projectRoot;
    private readonly budget;
    private readonly maxFiles;
    private readonly indexedFileCount;
    private readonly files;
    private readonly stages;
    private scoreFloor;
    private maxGraph;
    private graphGateThreshold;
    private graphGateApplied;
    private note;
    private session;
    private allocPool;
    private allocCliffAt;
    private allocCliffed;
    private constructor();
    /**
     * Returns `null` when `CODEGRAPH_EXPLORE_DEBUG` is unset/off — the whole
     * instrument then costs one env read per explore call and nothing else.
     */
    static start(query: string, projectRoot: string, budget: BudgetShape, maxFiles: number, indexedFileCount: number): ExploreDiagnostics | null;
    /**
     * Candidate count after the test/spec/icon/i18n hard-exclude — the FIRST
     * selection stage, ahead of the score floor.
     */
    setLowValueFiltered(grouped: number, kept: number): void;
    /**
     * Record what this session had already been served for this project (CG-17),
     * so the report says which call in the session it is and what the earlier ones
     * cost. Read-only for now: nothing in the render loop consults it, which is
     * what keeps the response byte-identical at this stage.
     *
     * Files are listed most-recent call first and de-duplicated by path — the same
     * file re-served across calls is the pattern this instrument exists to make
     * visible, and its ranges are unioned so a glance shows what of it the agent
     * already holds.
     */
    noteSession(prior: ExploreProjectState | null): void;
    /** Candidate count after the `group.score >= floor` filter. */
    setScoreFloor(floor: number, kept: number): void;
    /** Graph-relevance gate: threshold, whether it actually pruned, what survived. */
    setRelevanceGate(maxGraph: number, threshold: number, applied: boolean, kept: number): void;
    /** Record one ranked candidate's scoring inputs, in final sort order. */
    noteCandidate(path: string, meta: ExploreCandidateMeta): void;
    /**
     * Record the proportional split (CG-12), taken right after ranking and before
     * a single byte renders. Called once per explore.
     */
    setAllocation(allowances: ReadonlyMap<string, number>, cliffed: readonly string[], cliffAt: number, pool: number): void;
    /**
     * What the render loop will let this file spend — reservation plus inherited
     * slack. Called once per file, before any of its render paths run.
     */
    recordSpendable(path: string, chars: number): void;
    /**
     * What the render loop will let this file spend once the reservations still
     * owed BELOW it are held back (CG-31). Called alongside `recordSpendable`.
     */
    recordFunded(path: string, chars: number): void;
    /** A candidate rendered source into the response. */
    recordRender(path: string, render: ExploreRenderMode, sourceChars: number, clipped: boolean): void;
    /**
     * Source this call withheld because the session already holds it (CG-18).
     * Called with `(path, 0, [])` to clear a record — the anti-abandonment restore
     * puts a suppressed file's source back, and a diagnostic still claiming the
     * saving would misreport where the envelope went.
     */
    recordDedup(path: string, savedChars: number, covered: ReadonlyArray<{
        start: number;
        end: number;
    }>): void;
    /**
     * A candidate was passed over before rendering. First reason wins — the
     * blanket `max-files` sweep must not overwrite a file's specific reason.
     */
    recordSkip(path: string, reason: ExploreSkipReason): void;
    /** Explore returned early (no subgraph). Emits a minimal record. */
    finishEmpty(reason: string): void;
    /**
     * Final pass: attribute the FINAL text's bytes back to files (so the hard
     * ceiling's truncation is reflected in what each file actually delivered),
     * then emit.
     *
     * `allocatedChars` is the pre-truncation length — the size the render loop
     * *chose*. Reporting both is the point: the allocator's decision and the
     * agent's delivered payload diverge exactly when the ceiling cuts, and
     * conflating them is how a dropped trailing file goes unnoticed.
     */
    finish(finalText: string, allocatedChars: number, hardCeiling: number, filesIncluded: number): void;
    private buildReport;
    private emit;
}
/**
 * Attribute the final response's source bytes back to files by walking the
 * rendered markdown: a ``**`path`**`` section header followed by a fenced code
 * block. Reading the FINAL text (rather than trusting the render loop's running
 * total) is what makes the numbers truthful — it accounts for the hard-ceiling
 * truncation that can drop whole trailing sections after they were "emitted".
 *
 * Line numbering is on by default, so a source line that is itself a ``` fence
 * arrives as `42\t```` and cannot close the block early.
 */
export declare function attributeSourceBytes(finalText: string): Map<string, number>;
/** Human-readable stderr rendering of the JSON report. */
export declare function renderTable(report: ExploreDiagnosticReport): string;
export {};
//# sourceMappingURL=explore-diagnostics.d.ts.map