/**
 * CodeGraph
 *
 * A local-first code intelligence system that builds a semantic
 * knowledge graph from any codebase.
 */
import { Node, NodeKind, Edge, FileRecord, ExtractionResult, Subgraph, TraversalOptions, SearchOptions, SearchResult, SegmentMatch, Context, GraphStats, TaskInput, TaskContext, BuildContextOptions, FindRelevantContextOptions, UnresolvedReference } from './types';
import { QueryBuilder } from './db/queries';
import { IndexProgress, IndexResult, SyncResult } from './extraction';
import { ResolutionResult } from './resolution';
import { WatchOptions, PendingFile } from './sync';
export * from './types';
export { getDatabasePath, DatabaseConnection } from './db';
export { QueryBuilder } from './db/queries';
export { getCodeGraphDir, isInitialized, findNearestCodeGraphRoot, CODEGRAPH_DIR, } from './directory';
export { IndexProgress, IndexResult, SyncResult } from './extraction';
export { detectLanguage, isLanguageSupported, isGrammarLoaded, getSupportedLanguages, initGrammars, loadGrammarsForLanguages, loadAllGrammars } from './extraction';
export { ResolutionResult } from './resolution';
export { CodeGraphError, FileError, ParseError, DatabaseError, SearchError, VectorError, ConfigError, Logger, setLogger, getLogger, silentLogger, defaultLogger, } from './errors';
export { Mutex, FileLock, processInBatches, debounce, throttle, MemoryMonitor } from './utils';
export { FileWatcher, WatchOptions, PendingFile, LockUnavailableError } from './sync';
export { MCPServer } from './mcp';
/**
 * Options for initializing a new CodeGraph project
 */
export interface InitOptions {
    /** Whether to run initial indexing after init */
    index?: boolean;
    /** Progress callback for indexing */
    onProgress?: (progress: IndexProgress) => void;
}
/**
 * Options for opening an existing CodeGraph project
 */
export interface OpenOptions {
    /** Whether to run sync if files have changed */
    sync?: boolean;
    /** Whether to run in read-only mode */
    readOnly?: boolean;
}
/**
 * Options for indexing
 */
export interface IndexOptions {
    /** Progress callback */
    onProgress?: (progress: IndexProgress) => void;
    /** Abort signal for cancellation */
    signal?: AbortSignal;
    /** Enable verbose logging (worker lifecycle, memory, timeouts) */
    verbose?: boolean;
    /** Watcher fast path: reconcile ONLY these project-relative paths (see ExtractionOrchestrator.sync). */
    paths?: string[];
}
/**
 * Main CodeGraph class
 *
 * Provides the primary interface for interacting with the code knowledge graph.
 */
export declare class CodeGraph {
    private db;
    private queries;
    private projectRoot;
    private orchestrator;
    private resolver;
    private graphManager;
    private traverser;
    private contextBuilder;
    private indexMutex;
    private fileLock;
    private watcher;
    private constructor();
    /**
     * (Re)build the query/extraction/graph layers over the current `this.queries`
     * (which wraps `this.db`). Factored out of the constructor so `reopenIfReplaced`
     * can rebuild them against a fresh connection without duplicating the wiring.
     * The path-based `fileLock` is independent of the DB handle, so it stays put.
     */
    private wireLayers;
    /**
     * Set when this instance followed a database replaced on disk (#1902): the
     * next sync that can run reconciles the whole tree, because whatever the old
     * handle absorbed since the rebuild never reached the new file.
     */
    private pendingFullReconcile;
    /** How long a recreated, not-yet-indexed database is treated as a rebuild in progress. */
    private static readonly RECREATE_GRACE_MS;
    /** The database file at the path was written within the recreate grace window. */
    private isFreshlyRecreated;
    /**
     * Heal a stale database handle in place. If `.codegraph/` was removed and
     * recreated at the SAME path while this instance held the DB open — a git
     * worktree removed and re-added, or `rm -rf .codegraph` + `codegraph init` —
     * our open fd points at the now-unlinked inode and can never see the new
     * index, so every query returns the pre-removal snapshot until the process
     * restarts (#925). When that's detected, open the live file at the same path,
     * rebuild the query layers, and swap them IN PLACE, so every holder of this
     * instance (the MCP daemon's default project, cached projectPath connections)
     * heals without a restart. Returns true iff it reopened.
     *
     * POSIX-only in practice: `isReplacedOnDisk` never fires on Windows (an open
     * file can't be unlinked there, and st_ino is unreliable).
     *
     * Refuses (returns false) while an index/sync holds the index mutex: closing
     * the handle that run is writing through would break it mid-flight. `sync()`
     * performs the same check itself once it holds the mutex (#1902), so the
     * replaced file is still picked up — by that sync, or by the caller's retry.
     */
    reopenIfReplaced(): boolean;
    /** The body of {@link reopenIfReplaced}, without the in-flight-sync guard. */
    private reopenReplacedDatabase;
    /**
     * Initialize a new CodeGraph project
     *
     * Creates the .CodeGraph directory, database, and configuration.
     *
     * @param projectRoot - Path to the project root directory
     * @param options - Initialization options
     * @returns A new CodeGraph instance
     */
    static init(projectRoot: string, options?: InitOptions): Promise<CodeGraph>;
    /**
     * Initialize synchronously (without indexing)
     */
    static initSync(projectRoot: string): CodeGraph;
    /**
     * Open an existing CodeGraph project
     *
     * @param projectRoot - Path to the project root directory
     * @param options - Open options
     * @returns A CodeGraph instance
     */
    static open(projectRoot: string, options?: OpenOptions): Promise<CodeGraph>;
    /**
     * Rebuild the project's database from scratch and return a fresh, empty
     * instance — the "same result as a fresh init" semantics that `codegraph
     * index` documents.
     *
     * Unlike `open()` followed by `clear()`, this DISCARDS the existing
     * `.codegraph/codegraph.db` (and its `-wal`/`-shm` sidecars) before
     * re-initializing, instead of opening the old database and DELETE-ing every
     * row. On a large or pre-fix poisoned index — e.g. an old graph that scanned
     * an ignored gitlink corpus (#1065) into ~1.6M nodes with a multi-GB WAL —
     * the per-row `nodes_fts` delete-trigger churn blocks the main thread long
     * enough to trip the #850 liveness watchdog before indexing even starts, so a
     * full re-index could never recover the bad state (#1067). Discarding the
     * files is O(1) regardless of size, reclaims the disk, and sidesteps opening
     * (and running migrations against) the poisoned database entirely.
     */
    static recreate(projectRoot: string): Promise<CodeGraph>;
    /**
     * Open synchronously (without sync)
     */
    static openSync(projectRoot: string, options?: Pick<OpenOptions, 'readOnly'>): CodeGraph;
    /**
     * Check if a directory has been initialized as a CodeGraph project
     */
    static isInitialized(projectRoot: string): boolean;
    /**
     * Close the CodeGraph instance and release resources
     */
    close(): void;
    /**
     * Get the project root directory
     */
    getProjectRoot(): string;
    /**
     * Index all files in the project
     *
     * Uses a mutex to prevent concurrent indexing operations.
     */
    indexAll(options?: IndexOptions): Promise<IndexResult>;
    /**
     * Index specific files
     *
     * Uses a mutex to prevent concurrent indexing operations.
     */
    indexFiles(filePaths: string[]): Promise<IndexResult>;
    /**
     * Sync with current file state (incremental update).
     * Throws LockUnavailableError if the cross-process write lock is unavailable.
     *
     * Uses a mutex to prevent concurrent indexing operations.
     */
    sync(options?: IndexOptions): Promise<SyncResult>;
    /**
     * Check if an indexing operation is currently in progress
     */
    isIndexing(): boolean;
    /**
     * Whether an OS watcher event points at a file whose index metadata is still
     * current. Used on Windows to discard NTFS last-access notifications, which
     * libuv reports through fs.watch as ordinary change events (#1451).
     */
    private isIndexedFileStateCurrent;
    /**
     * Start watching for file changes and auto-syncing.
     *
     * Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
     * ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
     *
     * @param options - Watch options (debounce delay, callbacks)
     * @returns true if watching started successfully
     */
    watch(options?: WatchOptions): boolean;
    /**
     * Stop watching for file changes.
     */
    unwatch(): void;
    /**
     * Check if the file watcher is active.
     */
    isWatching(): boolean;
    /**
     * True once live watching has degraded, or while a re-armed watcher has not
     * completed its full catch-up. Distinct from `!isWatching()`: a stopped or
     * never-started watcher is inactive but NOT degraded. MCP tools use this for
     * a whole-index stale notice, since pending files are lost when watching
     * stops (#876, #1959).
     */
    isWatcherDegraded(): boolean;
    /** The reason live watching degraded, or null if it is healthy (#876). */
    getWatcherDegradedReason(): string | null;
    /** Re-arm a lock-degraded watcher; its stale state persists until a full sync. */
    rearmWatcherAfterLockContention(): boolean;
    /** True while a re-armed watcher owes a full reconcile of missed changes. */
    isWatcherRecovering(): boolean;
    /**
     * Files seen by the file watcher since the last successful sync —
     * the per-file "stale" signal MCP tools attach to responses so an agent
     * can fall back to {@link Read} for just the affected file without
     * waiting for a debounced sync to complete (issue #403).
     *
     * Returns an empty list when the watcher isn't active, or no events have
     * arrived. Each entry includes `firstSeenMs` and `lastSeenMs` (wall-clock
     * `Date.now()` values) so callers can render "edited Nms ago", plus an
     * `indexing` flag indicating whether the in-flight sync (if any) will
     * absorb that file.
     */
    getPendingFiles(): PendingFile[];
    /**
     * Resolves once the file watcher has installed its watch set. Useful for
     * tests that need a deterministic boundary before asserting on
     * `getPendingFiles()`. Resolves immediately when no watcher is active.
     */
    waitUntilWatcherReady(timeoutMs?: number): Promise<void>;
    /**
     * Get files that have changed since last index
     */
    getChangedFiles(): {
        added: string[];
        modified: string[];
        removed: string[];
    };
    /**
     * Most recent index timestamp (ms since epoch) across all tracked files, or
     * null when nothing is indexed yet. Lets library consumers check index
     * freshness without shelling out to `codegraph status --json`. (#329)
     */
    getLastIndexedAt(): number | null;
    /**
     * How far the last sync got and how many files it left behind — the cheapest
     * marker of "has this index moved". One query; safe to call on every
     * filesystem event a live viewer sees.
     */
    getIndexRevision(): {
        lastIndexedAt: number | null;
        fileCount: number;
    };
    /**
     * Files re-indexed strictly after `since`, newest first — what a sync just
     * picked up. `total` is the real count, `paths` is capped at `limit`.
     */
    getFilesIndexedSince(since: number, limit: number): {
        paths: string[];
        total: number;
    };
    /**
     * Forget everything held in memory about rows another process may have
     * changed.
     *
     * The query layer keeps an LRU of nodes by id, invalidated by writes made
     * through THIS instance — which is exactly right for a process that owns the
     * index, and wrong for one that is only reading a database somebody else is
     * writing. A long-lived reader (the `codegraph ui` server, a daemon holding a
     * graph open across an agent's edits) will otherwise answer `getNode(id)`
     * with a row a sync deleted minutes ago, while every SQL-backed query beside
     * it reports the truth — a disagreement that reads as a bug in whichever
     * screen shows both.
     *
     * Cheap (clearing a bounded Map) and safe to call whenever the database file
     * looks like it moved.
     */
    dropReadCaches(): void;
    /**
     * Completeness of the last full index run. `'complete'` is the only good
     * state. `'indexing'` after the fact means a run was killed mid-index (OOM,
     * SIGKILL, liveness watchdog) and the on-disk index is truncated;
     * `'partial'` means the run finished but silently dropped files
     * (discovered > indexed+skipped+errored); `'failed'` means it reported
     * failure. `null` = index predates this marker. Surfaced by
     * `codegraph status`.
     */
    getIndexState(): 'indexing' | 'complete' | 'partial' | 'failed' | null;
    /**
     * Which engine built the current index: the package version + extraction
     * version stamped at the last full `indexAll`. Either field is null for an
     * index built before stamping existed (treated as stale). See
     * `extraction-version.ts` and `isIndexStale()`.
     */
    getIndexBuildInfo(): {
        version: string | null;
        extractionVersion: number | null;
    };
    /**
     * True when the on-disk index was built by an engine whose extraction is
     * older than the one now running — i.e. a re-index would add data a migration
     * can't backfill. False when there's no index yet (nothing to refresh) or the
     * stamp is current. This is the signal behind `codegraph status`'s re-index
     * hint and `codegraph upgrade`'s reminder.
     */
    isIndexStale(): boolean;
    /**
     * Extract nodes and edges from source code (without storing)
     */
    extractFromSource(filePath: string, source: string): ExtractionResult;
    /**
     * Resolve unresolved references and create edges
     *
     * This method takes unresolved references from extraction and attempts
     * to resolve them using multiple strategies:
     * - Framework-specific patterns (React, Express, Laravel)
     * - Import-based resolution
     * - Name-based symbol matching
     */
    resolveReferences(onProgress?: (current: number, total: number) => void): ResolutionResult;
    /**
     * Resolve references in batches to keep memory bounded on large codebases.
     * Processes chunks of unresolved refs, persisting results after each batch.
     */
    resolveReferencesBatched(onProgress?: (current: number, total: number) => void, onSynthesisProgress?: (done: number, total: number) => void, backpressure?: () => Promise<void> | null, synthesize?: boolean): Promise<ResolutionResult>;
    /**
     * References extracted but never attempted by a resolution pass. Zero on a
     * healthy index — a completed pass consumes every pending row (resolving it
     * or parking it as failed, #1240). Non-zero at rest means a pass was
     * interrupted mid-run (killed indexer, crash — #1187), so some files' call
     * edges are missing; the next `sync` sweeps them.
     */
    getPendingReferenceCount(): number;
    /**
     * Get detected frameworks in the project
     */
    getDetectedFrameworks(): string[];
    /**
     * Re-initialize the resolver (useful after adding new files)
     */
    reinitializeResolver(): void;
    /**
     * Get statistics about the knowledge graph
     */
    getStats(): GraphStats;
    /**
     * Active SQLite backend for this project's connection (`node-sqlite` — Node's
     * built-in real-SQLite module). Surfaced via `codegraph status` and the
     * `codegraph_status` MCP tool alongside the effective journal mode.
     */
    getBackend(): import('./db').SqliteBackend;
    /**
     * The journal mode actually in effect ('wal', 'delete', …). 'wal' means
     * readers never block on a concurrent writer; anything else means they can,
     * which is the precondition for the "database is locked" failures in issue
     * #238. Surfaced via `codegraph status` and the `codegraph_status` MCP tool.
     */
    getJournalMode(): string;
    /**
     * Get a node by ID
     */
    getNode(id: string): Node | null;
    /**
     * Get many nodes by id in ONE round-trip (LRU-cache aware).
     *
     * The batch form of {@link getNode}. Anything resolving a list of edges to
     * their endpoints — a caller list, a callee rail, an impact set — must use
     * this rather than a `getNode` per edge: a symbol with 500 callers is 500
     * queries otherwise. Ids that name nothing are simply absent from the map.
     */
    getNodesByIds(ids: readonly string[]): Map<string, Node>;
    /**
     * Every symbol carrying an exact qualified name.
     *
     * The identity that survives a re-index. A node's id contains its start line,
     * so any edit ABOVE a symbol gives it a different id — anything that has to
     * name the same symbol across two indexes (a saved trail, a bookmark, a
     * review comment) has to key on this instead, and then disambiguate the
     * result by kind and file. Index-backed; unlike
     * {@link GraphQueryManager.findByQualifiedName} it takes no pattern and scans
     * nothing.
     */
    getNodesByQualifiedName(qualifiedName: string): Node[];
    /**
     * Outgoing edges for many source nodes at once — the batch form of
     * {@link getOutgoingEdges}. See {@link QueryBuilder.getOutgoingEdgesFrom}.
     */
    getOutgoingEdgesFrom(nodeIds: readonly string[], kinds?: Edge['kind'][]): Edge[];
    /**
     * Fan-in (incoming edge count) for many nodes at once — the "hub" signal,
     * without a query per node. See {@link QueryBuilder.countIncomingEdges}.
     */
    getFanIn(ids: readonly string[]): Map<string, number>;
    /**
     * Incoming edges for many target nodes at once — the mirror of
     * {@link getOutgoingEdgesFrom}. See {@link QueryBuilder.getIncomingEdgesTo}.
     */
    getIncomingEdgesTo(nodeIds: readonly string[], kinds?: Edge['kind'][]): Edge[];
    /**
     * Fan-out (outgoing edge count) for many nodes at once — the mirror of
     * {@link getFanIn}. See {@link QueryBuilder.countOutgoingEdges}.
     */
    getFanOut(ids: readonly string[]): Map<string, number>;
    /**
     * Symbols nothing in the index points at, by kind — the candidate set the
     * dead code report (`src/graph/dead-code.ts`) applies its exclusions to.
     *
     * Every edge kind except `contains` counts as a reference, so a method is
     * not "reached" by the class that holds it. An unreferenced symbol is not
     * yet a dead one: see {@link buildDeadCodeReport}.
     */
    getUnreferencedNodes(kinds: readonly Node['kind'][], limit: number): Array<{
        node: Node;
        generated: boolean;
    }>;
    /**
     * Which of the given names are carried by more than one symbol, at least one
     * of which something references — the names a "nothing reaches this" claim
     * must not be made about, because the resolver may have picked the twin.
     */
    getAmbiguousReferencedNames(names: Iterable<string>): Set<string>;
    /**
     * Which of the given languages this index records an export marker for. A
     * language with none has no "reachable from outside" signal at all.
     */
    getLanguagesWithExports(languages: Iterable<string>): Set<string>;
    /**
     * Which of the given names the index holds an unresolved reference to — the
     * resolver saw the name and could not decide what it meant. A symbol with
     * such a name can never be called unreferenced.
     */
    getUnresolvedNamesAmong(names: Iterable<string>): Set<string>;
    /**
     * Which of the given symbols extend or implement a type outside the index —
     * an ancestor the resolver could not follow, so it has no edge (#1973).
     */
    getUnresolvedSupertypeSourcesAmong(nodeIds: Iterable<string>): Set<string>;
    /**
     * The symbols with the most distinct dependents, most first — the index's
     * hubs. Distinct dependents, not edges: a helper called forty times from one
     * function has one dependent, and it is dependents a blast radius grows from.
     */
    getTopDependedOn(limit: number): Array<{
        nodeId: string;
        dependents: number;
    }>;
    /**
     * The graph's executable roots — files that run something at module level (a
     * CLI, a worker entry, a script), ranked by calls x the number of other files
     * they reach. A statement at the top level of a file is recorded as an edge
     * out of the *file* node, which is what makes these visible at all.
     */
    getTopCallingFiles(limit: number): Array<{
        nodeId: string;
        filePath: string;
        calls: number;
        reaches: number;
        score: number;
    }>;
    /**
     * How many other files depend on each of the given files, counted through
     * their symbols (an `imports` edge points at the symbol, not the file).
     * A zero means nothing else in the index reaches into that file.
     */
    getFileDependentCounts(filePaths: string[]): Map<string, number>;
    /**
     * How far each of the given files reaches out: distinct other files their
     * symbols touch, and how many references that is. The mirror of
     * {@link getFileDependentCounts}; a test file's reach is what it exercises.
     */
    getFileReachCounts(filePaths: string[]): Map<string, {
        reaches: number;
        refs: number;
    }>;
    /** The `file` nodes for the given paths, in one query. */
    getFileNodes(filePaths: string[]): Node[];
    /**
     * Roll the edge table up to module granularity, for a file → module
     * assignment the caller decides.
     *
     * The architecture map's single query: cross-module edge counts by kind,
     * the `declared` subset of each (see {@link QueryBuilder.aggregateModuleGraph}),
     * and the busiest symbol pairs behind each link. Read-only, and bounded by
     * the number of modules rather than the number of edges.
     */
    getModuleAggregation(assignments: ReadonlyArray<{
        filePath: string;
        module: string;
    }>, options: {
        kinds: readonly Edge['kind'][];
        minConfidence: number;
        topPairsPerLink: number;
        pairKinds: readonly Edge['kind'][];
    }): ReturnType<QueryBuilder['aggregateModuleGraph']>;
    /**
     * Every ordered pair of files where one reaches into the other — the edge
     * list a cycle finder runs on. See {@link QueryBuilder.getCrossFileDependencyPairs}.
     */
    getFileDependencyPairs(minConfidence?: number): Array<{
        source: string;
        target: string;
    }>;
    /**
     * References from a symbol that never resolved to an indexed node — the
     * calls and type mentions that leave the index. Lets a reader account for
     * the call sites that have no callee row instead of implying there are none.
     */
    getUnresolvedReferencesFrom(nodeId: string): UnresolvedReference[];
    /**
     * The same, for every symbol in a FILE at once, in line order.
     *
     * One indexed lookup instead of one per symbol — the whole-file reader needs
     * it for every line it draws. See
     * {@link QueryBuilder.getUnresolvedReferencesInFile}.
     */
    getUnresolvedReferencesInFile(filePath: string, limit?: number): UnresolvedReference[];
    /**
     * Get all nodes in a file
     */
    getNodesInFile(filePath: string): Node[];
    /**
     * Get all nodes in several files, in one batched query.
     */
    getNodesInFiles(filePaths: readonly string[]): Node[];
    /**
     * Get all nodes of a specific kind
     */
    getNodesByKind(kind: Node['kind']): Node[];
    /**
     * Get ALL nodes with an exact name (direct index lookup, not FTS-ranked/capped).
     * Used to enumerate every overload of a heavily-overloaded name so the specific
     * definition the caller wants is never dropped below a search cut.
     */
    getNodesByName(name: string): Node[];
    /** Nodes whose name starts with `prefix` (index range scan, capped). */
    getNodesByNamePrefix(prefix: string, limit?: number): Node[];
    /**
     * Nodes whose name CONTAINS `substring` (LIKE scan, ASCII-case-insensitive,
     * shortest-first). The camel-infix lookup FTS can't do — `profileInfo`
     * inside `getProfileInfoV2` is one FTS token (#1196).
     */
    getNodesByNameSubstring(substring: string, options?: {
        kinds?: NodeKind[];
        limit?: number;
        excludePrefix?: boolean;
    }): Node[];
    /**
     * Search nodes by text
     */
    searchNodes(query: string, options?: SearchOptions): SearchResult[];
    /** Lexical evidence for an empty explore result; does not alter retrieval. */
    getExploreMissDiagnostics(query: string): {
        matched: string[];
        unmatched: string[];
        candidates: string[];
        limited: boolean;
    };
    /**
     * Graph-derived prompt matching for the front-load hook's MEDIUM tier:
     * which indexed symbols do these prose words name? "state machine des
     * commandes" → `OrderStateMachine`, in any human language whose technical
     * nouns are Latin script — no keyword list involved.
     *
     * Precision comes from the repo's own naming statistics, not vocabulary:
     * - CO-OCCURRENCE: ≥2 words that are segments of the SAME name ("state" +
     *   "machine" → OrderStateMachine) is strong evidence and always qualifies.
     * - RARITY: a single matched word qualifies only when its segment is
     *   discriminative here (≤ {@link SEGMENT_RARITY_CEILING} distinct names) —
     *   "checkout" in a shop backend yes, "state" in a react app no.
     * Every candidate is re-verified against `nodes` before being returned
     * (vocab rows are proposals; deletions leave orphans by design), so a
     * returned symbol is guaranteed to exist right now.
     */
    getSegmentMatches(words: string[], limit?: number): SegmentMatch[];
    /** A single word ("state") can match hundreds of names in a big repo — that
     *  is noise, not signal. Ceiling for the single-word tier; co-occurrence is
     *  exempt because two words on one name is already discriminative. */
    private static readonly SEGMENT_RARITY_CEILING;
    /** Which of the prompt's original words match `name`'s segments (via
     *  variants). Segments are recomputed in JS — a name-keyed vocab lookup
     *  would scan the (segment, name) primary key. */
    private wordsMatchingName;
    /**
     * One-shot upgrade heal for callers that open the graph WITHOUT syncing —
     * concretely the prompt hook, whose MEDIUM tier reads the segment
     * vocabulary: a database migrated from before the vocab table existed
     * starts with it empty, and the only other backfill lives inside `sync()`,
     * which such callers never run (#1142). Returns true when the vocab is
     * usable (already populated — the overwhelmingly common one-SELECT case —
     * or healed here); false when it isn't (empty graph, or another process
     * holds the index lock — that process's own sync heals it).
     */
    healSegmentVocabIfEmpty(): Promise<boolean>;
    /**
     * Rebuild the segment vocabulary from the current graph, batched and
     * yielding — the upgrade-heal path for indexes built before the vocab table
     * existed. Runs inside the index mutex/lock (sync and
     * healSegmentVocabIfEmpty hold them).
     */
    private rebuildNameSegmentVocab;
    /**
     * Normalized project-name tokens (go.mod / package.json / repo dir) used to
     * down-weight the non-discriminative project name in search ranking (#720).
     * Exposed so explore can exclude it from the PascalCase type-disambiguation
     * bias, which would otherwise pull overloaded tokens toward whichever stack
     * embeds the project name.
     */
    getProjectNameTokens(): Set<string>;
    /**
     * Find the project's "primary route file" — the file with the densest
     * concentration of framework-emitted `route` nodes (≥3 routes, ≥30%
     * of all non-test routes). Used to inline the routing config in
     * `codegraph_explore` responses on small realworld template repos
     * (rails-realworld, laravel-realworld, drupal-admintoolbar, …) where
     * Glob+Read of `routes.rb`/`urls.py`/etc. otherwise beats codegraph.
     */
    getTopRouteFile(): {
        filePath: string;
        routeCount: number;
        totalRoutes: number;
    } | null;
    /**
     * Build a URL → handler routing manifest from the index. Each entry
     * pairs a route node (URL + method) with its handler function/method
     * via the `references` edge that framework resolvers emit. Returns
     * null when fewer than 3 valid (non-test) routes exist.
     */
    getRoutingManifest(limit?: number): {
        entries: Array<{
            url: string;
            handler: string;
            handlerFile: string;
            handlerLine: number;
            handlerKind: string;
            routeId: string;
            routeFile: string;
            routeLine: number;
        }>;
        topHandlerFile: string | null;
        topHandlerFileCount: number;
        totalRoutes: number;
    } | null;
    /**
     * Get outgoing edges from a node
     */
    getOutgoingEdges(nodeId: string): Edge[];
    /**
     * Get incoming edges to a node
     */
    getIncomingEdges(nodeId: string): Edge[];
    /**
     * Get a file record by path
     */
    getFile(filePath: string): FileRecord | null;
    /**
     * Whether the index holds any file under `dir`, a project-relative POSIX
     * directory (e.g. `packages/api`).
     */
    hasFilesUnder(dir: string): boolean;
    /**
     * Get all tracked files
     */
    getFiles(): FileRecord[];
    /**
     * A `(path) => boolean` generated-file test over a BOUNDED candidate list,
     * unioning the index-time content-banner flag with the filename convention
     * (#1500). One query up front, O(1) per call after — built for use inside a
     * ranking comparator, where re-querying per comparison would be quadratic.
     *
     * Pass every path you might ask about; a path outside the list falls back to
     * the filename check alone.
     */
    generatedFilePredicate(filePaths: Iterable<string>): (filePath: string) => boolean;
    /**
     * A `(path) => boolean` ambient-declaration test over a BOUNDED candidate
     * list: true for a file that declares nothing but types, originates no call
     * edge, and that nothing in the index depends on — an ambient `.d.ts` of
     * global shims, vendored typings, module augmentation (CG-28). Structural
     * rather than extension-based, and deliberately narrow: see
     * `QueryBuilder.getAmbientDeclarationPathsAmong` for why each condition is
     * there, in particular why a `types.ts` the codebase imports is NOT flagged.
     */
    ambientDeclarationFilePredicate(filePaths: Iterable<string>): (filePath: string) => boolean;
    /** How many indexed files are flagged tool-generated. Reported by `status`. */
    getGeneratedFileCount(): number;
    /**
     * Get the context for a node (ancestors, children, references)
     *
     * Returns comprehensive context about a node including its containment
     * hierarchy, children, incoming/outgoing references, type information,
     * and relevant imports.
     *
     * @param nodeId - ID of the focal node
     * @returns Context object with all related information
     */
    getContext(nodeId: string): Context;
    /**
     * Traverse the graph from a starting node
     *
     * Uses breadth-first search by default. Supports filtering by edge types,
     * node types, and traversal direction.
     *
     * @param startId - Starting node ID
     * @param options - Traversal options
     * @returns Subgraph containing traversed nodes and edges
     */
    traverse(startId: string, options?: TraversalOptions): Subgraph;
    /**
     * Get the call graph for a function
     *
     * Returns both callers (functions that call this function) and
     * callees (functions called by this function) up to the specified depth.
     *
     * @param nodeId - ID of the function/method node
     * @param depth - Maximum depth in each direction (default: 2)
     * @returns Subgraph containing the call graph
     */
    getCallGraph(nodeId: string, depth?: number): Subgraph;
    /**
     * Get the type hierarchy for a class/interface
     *
     * Returns both ancestors (types this extends/implements) and
     * descendants (types that extend/implement this).
     *
     * @param nodeId - ID of the class/interface node
     * @returns Subgraph containing the type hierarchy
     */
    getTypeHierarchy(nodeId: string): Subgraph;
    /**
     * Find all usages of a symbol
     *
     * Returns all nodes that reference the specified symbol through
     * any edge type (calls, references, type_of, etc.).
     *
     * @param nodeId - ID of the symbol node
     * @returns Array of nodes and edges that reference this symbol
     */
    findUsages(nodeId: string): Array<{
        node: Node;
        edge: Edge;
    }>;
    /**
     * Get callers of a function/method
     *
     * @param nodeId - ID of the function/method node
     * @param maxDepth - Maximum depth to traverse (default: 1)
     * @returns Array of nodes that call this function
     */
    getCallers(nodeId: string, maxDepth?: number): Array<{
        node: Node;
        edge: Edge;
    }>;
    /**
     * Get callees of a function/method
     *
     * @param nodeId - ID of the function/method node
     * @param maxDepth - Maximum depth to traverse (default: 1)
     * @returns Array of nodes called by this function
     */
    getCallees(nodeId: string, maxDepth?: number): Array<{
        node: Node;
        edge: Edge;
    }>;
    /**
     * Calculate the impact radius of a node
     *
     * Returns all nodes that could be affected by changes to this node.
     *
     * @param nodeId - ID of the node
     * @param maxDepth - Maximum depth to traverse (default: 3)
     * @returns Subgraph containing potentially impacted nodes
     */
    getImpactRadius(nodeId: string, maxDepth?: number): Subgraph;
    /**
     * Find the shortest path between two nodes
     *
     * @param fromId - Starting node ID
     * @param toId - Target node ID
     * @param edgeKinds - Edge types to consider (all if empty)
     * @returns Array of nodes and edges forming the path, or null if no path exists
     */
    findPath(fromId: string, toId: string, edgeKinds?: Edge['kind'][]): Array<{
        node: Node;
        edge: Edge | null;
    }> | null;
    /**
     * Get ancestors of a node in the containment hierarchy
     *
     * @param nodeId - ID of the node
     * @returns Array of ancestor nodes from immediate parent to root
     */
    getAncestors(nodeId: string): Node[];
    /**
     * Get immediate children of a node
     *
     * @param nodeId - ID of the node
     * @returns Array of child nodes
     */
    getChildren(nodeId: string): Node[];
    /**
     * Get dependencies of a file
     *
     * @param filePath - Path to the file
     * @returns Array of file paths this file depends on
     */
    getFileDependencies(filePath: string): string[];
    /**
     * Get dependents of a file
     *
     * @param filePath - Path to the file
     * @returns Array of file paths that depend on this file
     */
    getFileDependents(filePath: string): string[];
    /**
     * Find circular dependencies in the codebase
     *
     * @returns Array of cycles, each cycle is an array of file paths
     */
    findCircularDependencies(): string[][];
    /**
     * Find unreferenced symbols — the RAW candidate set.
     *
     * Non-exported symbols of the given kinds with no incoming edge but
     * `contains`. That is a fact, not a claim: on this engine's own index it
     * returns ~2 500 symbols, of which about 20 are actually unreachable. The
     * rest are overrides, framework registrations, mis-resolved twins and
     * references the extractor never recorded.
     *
     * For a list anybody should act on, use `buildDeadCodeReport` from
     * `src/graph/dead-code.ts`, which applies the exclusions and counts every one
     * of them. This method is kept as-is because it is a published API.
     *
     * @param kinds - Node kinds to check (default: functions, methods, classes)
     * @returns Array of unreferenced nodes
     */
    findDeadCode(kinds?: Node['kind'][]): Node[];
    /**
     * Get complexity metrics for a node
     *
     * @param nodeId - ID of the node
     * @returns Object containing various complexity metrics
     */
    getNodeMetrics(nodeId: string): {
        incomingEdgeCount: number;
        outgoingEdgeCount: number;
        callCount: number;
        callerCount: number;
        childCount: number;
        depth: number;
    };
    /**
     * Get the source code for a node
     *
     * Reads the file and extracts the code between startLine and endLine.
     *
     * @param nodeId - ID of the node
     * @returns Code string or null if not found
     */
    getCode(nodeId: string): Promise<string | null>;
    /**
     * Find relevant subgraph for a query
     *
     * Combines semantic search with graph traversal to find the most
     * relevant nodes and their relationships for a given query.
     *
     * @param query - Natural language query describing the task
     * @param options - Search and traversal options
     * @returns Subgraph of relevant nodes and edges
     */
    findRelevantContext(query: string, options?: FindRelevantContextOptions): Promise<Subgraph>;
    /**
     * Build context for a task
     *
     * Creates comprehensive context by:
     * 1. Running FTS search to find entry points
     * 2. Expanding the graph around entry points
     * 3. Extracting code blocks for key nodes
     * 4. Formatting output for Claude
     *
     * @param input - Task description (string or {title, description})
     * @param options - Build options (maxNodes, includeCode, format, etc.)
     * @returns TaskContext object or formatted string (markdown/JSON)
     */
    buildContext(input: TaskInput, options?: BuildContextOptions): Promise<TaskContext | string>;
    /**
     * Optimize the database (vacuum and analyze)
     */
    optimize(): void;
    /**
     * Clear all data from the graph
     */
    clear(): void;
    /**
     * Alias for close() for backwards compatibility.
     * @deprecated Use close() instead
     */
    destroy(): void;
    /**
     * Completely remove CodeGraph from the project.
     * This closes the database and deletes the .CodeGraph directory.
     *
     * WARNING: This permanently deletes all CodeGraph data for the project.
     */
    uninitialize(): void;
}
export default CodeGraph;
//# sourceMappingURL=index.d.ts.map