/**
 * Extraction Orchestrator
 *
 * Coordinates file scanning, parsing, and database storage.
 */
import * as fs from 'fs';
import { ExtractionResult, ExtractionError } from '../types';
import { QueryBuilder } from '../db/queries';
import { Ignore } from 'ignore';
/**
 * Progress callback for indexing operations
 */
export interface IndexProgress {
    phase: 'scanning' | 'parsing' | 'storing' | 'resolving' | 'linking';
    current: number;
    total: number;
    currentFile?: string;
}
/**
 * Result of an indexing operation
 */
export interface IndexResult {
    success: boolean;
    filesIndexed: number;
    filesSkipped: number;
    filesErrored: number;
    /**
     * How many indexable files the scan discovered — the ground truth the
     * indexed/skipped/errored tallies must add up to. A shortfall means files
     * were silently dropped mid-pipeline (e.g. a killed worker under load) and
     * the index is PARTIAL; callers surface that rather than trusting the
     * counts. Only set by full-index runs (indexAll), not indexFiles/sync.
     */
    filesDiscovered?: number;
    nodesCreated: number;
    edgesCreated: number;
    errors: ExtractionError[];
    durationMs: number;
}
/**
 * Result of a sync operation
 */
export interface SyncResult {
    filesChecked: number;
    filesAdded: number;
    filesModified: number;
    filesRemoved: number;
    nodesUpdated: number;
    durationMs: number;
    changedFilePaths?: string[];
    /**
     * Symbol names whose set of definitions this sync CHANGED — names the synced
     * files gained or lost, as the symmetric difference of their `file\0name`
     * definition pairs before and after the store phase (per file, so a name
     * moving between two changed files does not cancel itself out).
     * Resolution picks among all same-named definitions project-wide,
     * so these are exactly the names whose already-resolved edges — in files this
     * sync never touched — may now bind elsewhere and must be re-resolved for the
     * index to stay convergent with a full rebuild (CG-33).
     *
     * A body-only edit leaves this empty, which is the common case and costs
     * nothing downstream.
     */
    definitionDelta?: string[];
}
/**
 * Calculate SHA256 hash of file contents
 */
export declare function hashContent(content: string): string;
/**
 * An `ignore` matcher seeded with the built-in defaults, merged with the project's
 * root .gitignore so a negation there (e.g. `!vendor/`) overrides a default. Shared
 * by both enumeration paths so behavior is identical with or without git — and so
 * the defaults apply to tracked files too (committing a dependency dir doesn't make
 * it project code; the explicit `.gitignore` negation is the only opt-in).
 */
export declare function buildDefaultIgnore(rootDir: string): Ignore;
/**
 * Workspace-scope ignore matcher. Ordinary paths get the root's matcher
 * (built-in defaults + root `.gitignore`); paths inside an EMBEDDED repo get
 * that repo's own matcher (defaults + its root `.gitignore`) — the parent's
 * `.gitignore` hides a child repo from git, not from the index (#514). A
 * directory path (trailing slash) that is an ANCESTOR of an embedded root is
 * never ignored, so directory-pruning callers (the Linux per-directory
 * watcher) still descend to reach the embedded repos.
 *
 * Single source of truth for indexer and watcher scope — they must not diverge.
 */
export declare class ScopeIgnore {
    private rootMatcher;
    /**
     * Project `codegraph.json` `exclude` patterns (#999), matched against the
     * full root-relative path. Wins over everything else — an explicit user
     * exclude applies even to tracked files and even inside embedded repos.
     */
    private exclude;
    /**
     * Project `codegraph.json` `include` patterns — first-party source forced
     * INTO the index despite `.gitignore`. When a path matches, it is NOT
     * ignored (so the watcher watches it), overriding `.gitignore`/`rootMatcher`
     * — but never `exclude` (checked first) and never a built-in default-ignored
     * dir. `includeRoots` are the static prefixes so a gitignored ANCESTOR
     * directory of an included subtree still isn't pruned by the directory
     * walker/watcher.
     */
    private include;
    private includeRoots;
    private embedded;
    private defaults;
    constructor(rootMatcher: Ignore, embedded: Array<{
        root: string;
        matcher: Ignore;
    }>, 
    /**
     * Project `codegraph.json` `exclude` patterns (#999), matched against the
     * full root-relative path. Wins over everything else — an explicit user
     * exclude applies even to tracked files and even inside embedded repos.
     */
    exclude?: Ignore | null, 
    /**
     * Project `codegraph.json` `include` patterns — first-party source forced
     * INTO the index despite `.gitignore`. When a path matches, it is NOT
     * ignored (so the watcher watches it), overriding `.gitignore`/`rootMatcher`
     * — but never `exclude` (checked first) and never a built-in default-ignored
     * dir. `includeRoots` are the static prefixes so a gitignored ANCESTOR
     * directory of an included subtree still isn't pruned by the directory
     * walker/watcher.
     */
    include?: Ignore | null, includeRoots?: string[]);
    ignores(rel: string): boolean;
}
/**
 * Build the workspace-scope matcher. When the caller already knows the
 * embedded roots (the scanner discovers them during collection), pass them to
 * skip rediscovery; otherwise they're discovered here (the watcher path).
 */
export declare function buildScopeIgnore(rootDir: string, embeddedRoots?: Iterable<string>): ScopeIgnore;
/**
 * Standalone discovery of every embedded repo root under `rootDir` (relative,
 * trailing-slashed) — the untracked kind (#193) always, and the gitignored kind
 * (#514) only for directories the project opted in via `codegraph.json`
 * `includeIgnored` (#622, #699); otherwise `.gitignore` is respected and they
 * are not discovered (#970, #976). Recursive (an embedded repo can embed further
 * repos). Returns [] for non-git roots: the filesystem walk handles nested repos
 * there already.
 */
export declare function discoverEmbeddedRepoRoots(rootDir: string): string[];
/**
 * The INVERSE of the gitignored side of {@link discoverEmbeddedRepoRoots}:
 * nested git repositories under a gitignored directory that the project has NOT
 * opted into via `codegraph.json` `includeIgnored`. These are real repos the
 * default `init`/`index` deliberately skips because `.gitignore` excludes them
 * (#970, #976) — most visibly the "super-repo `.gitignore`s its child repos"
 * layout (#1156), where `init` at the parent correctly indexes ~nothing while
 * `init` inside each child works. The CLI uses this to turn that silent empty
 * index into an actionable hint: it names the skipped repos and offers to opt
 * them in. Paths are `rootDir`-relative and trailing-slashed (valid
 * `includeIgnored` patterns as-is). Returns `[]` for a non-git root (a
 * filesystem walk already descends into nested repos there), skips built-in
 * default-ignored dirs (`node_modules`, …), and is bounded so it never stalls
 * on a giant ignored tree.
 */
export declare function findUnindexedIgnoredRepos(rootDir: string): string[];
/**
 * Result of git-based change detection.
 * Returns null when git is unavailable (non-git project or command failure),
 * signaling the caller to fall back to full filesystem scan.
 */
interface GitChanges {
    modified: string[];
    added: string[];
    deleted: string[];
}
/**
 * Use `git status` to detect changed files instead of scanning every file.
 * Returns null on failure so callers fall back to full scan.
 *
 * Recurses into embedded repos — the untracked kind (#193: the parent's status
 * collapses them to an opaque `?? subdir/` entry) always, and the gitignored
 * kind (#514: they never appear in the parent's status at all) only for
 * directories opted in via `codegraph.json` `includeIgnored` (#622, #699) —
 * running `git status` inside each, so changes in a multi-repo workspace sync
 * without a full rescan. By default a gitignored dir is left alone, matching the
 * full-index scan (#970, #976). Deleting an ENTIRE embedded repo dir is the one
 * case this cannot see (the child status that would report the deletions is gone
 * with it); a full `codegraph index` reconciles that.
 */
export declare function getGitChangedFiles(rootDir: string): GitChanges | null;
/**
 * Recursively scan a directory for source files.
 *
 * In git repos, uses `git ls-files` (inherently respects .gitignore at all
 * levels), then keeps files with a supported source extension. For non-git
 * projects, falls back to a filesystem walk that parses .gitignore itself.
 */
export declare function scanDirectory(rootDir: string, onProgress?: (current: number, file: string) => void): string[];
/**
 * Async variant of scanDirectory that yields to the event loop periodically,
 * allowing worker threads to receive and render progress messages.
 */
export declare function scanDirectoryAsync(rootDir: string, onProgress?: (current: number, file: string) => void): Promise<string[]>;
/**
 * Extraction orchestrator
 */
export declare class ExtractionOrchestrator {
    private rootDir;
    private queries;
    /**
     * Names of frameworks detected for this project, populated by indexAll().
     * Passed to extractFromSource so framework-specific extractors (route nodes,
     * middleware, etc.) run after the tree-sitter pass. Cleared if detection
     * hasn't run yet so single-file re-index paths can detect on the spot.
     */
    private detectedFrameworkNames;
    /**
     * Scope matcher for SCOPED syncs, memoized on the mtimes of the two root
     * files it is derived from (`codegraph.json`, `.gitignore`). See
     * {@link scopedSyncMatcher}.
     */
    private scopedMatcher;
    constructor(rootDir: string, queries: QueryBuilder);
    /**
     * The scope matcher a scoped sync applies to the paths it was handed — the
     * same `buildScopeIgnore` the full scan uses, so an explicitly-passed path
     * that is OUT of scope (a user `exclude` in `codegraph.json`, a `.gitignore`
     * rule, a built-in default) is treated exactly as the full walk would treat
     * it: absent, hence removed if tracked, never parsed (#1590).
     *
     * Memoized on the root config + root `.gitignore` mtimes: building the
     * matcher runs embedded-repo discovery (`git ls-files`), which would defeat
     * the scoped path's whole point (skipping O(repo) work) if paid per sync.
     * Two `stat`s per sync while nothing changed. An embedded repo created
     * between config edits joins the scoped matcher on the next full sync, the
     * same lifecycle the watcher's own matcher already has.
     */
    private scopedSyncMatcher;
    /**
     * Build a filesystem-backed ResolutionContext sufficient for framework
     * detection. Graph-query methods (getNodesByName etc.) return empty because
     * the DB hasn't been populated yet, but detect() only uses readFile,
     * fileExists, and getAllFiles, so that's fine.
     */
    private buildDetectionContext;
    /**
     * Detect frameworks on demand using the current scanned files (or a fresh
     * scan if none are provided). Cached on the orchestrator so repeat calls
     * inside a single run don't re-scan.
     */
    private ensureDetectedFrameworks;
    /**
     * Index all files in the project
     */
    indexAll(onProgress?: (progress: IndexProgress) => void, signal?: AbortSignal, verbose?: boolean, walBackpressure?: () => Promise<void> | null, storeWriterOpts?: {
        dbPath: string;
        fastInit: boolean;
    } | null): Promise<IndexResult>;
    /**
     * Index specific files
     */
    indexFiles(filePaths: string[]): Promise<IndexResult>;
    /**
     * Index a single file
     */
    indexFile(relativePath: string): Promise<ExtractionResult>;
    /**
     * Index a single file with pre-read content and stats.
     * Used by the parallel batch reader to avoid redundant file I/O.
     */
    indexFileWithContent(relativePath: string, content: string, stats: fs.Stats): Promise<ExtractionResult>;
    /**
     * Store extraction result in database
     */
    /**
     * Delete file rows recorded with ZERO nodes so their files re-index.
     *
     * No extraction path stores an empty, error-free result for a
     * symbol-bearing language — even an empty file keeps its file node — so a
     * zero-node row is a wiped one (#1541: an interrupted parse's retry stored
     * an undecoded kernel transport). The wiped row's content hash matches the
     * on-disk bytes, so every hash-based reconcile skips the file forever;
     * deleting the row lets the normal add path repair it. File-level-only
     * languages (yaml, twig, properties) are left alone. Deleting a zero-node
     * row cascades nothing: it has no nodes, so no edges or refs either.
     */
    private healZeroNodeRows;
    private storeExtractionResult;
    /**
     * Build one file's store bundle for the FRESH-DB path: no existing-file
     * check, no cross-file edge snapshot (both are re-index concerns — a fresh
     * database has neither). Filters mirror storeExtractionResult exactly.
     */
    /** The FileRecord for a fresh-index store (nodeCount is the PRE-filter count). */
    private buildFileRecord;
    private buildFreshStoreBundle;
    /**
     * Re-attach cross-file incoming edges snapshotted before a re-index delete
     * (#899): re-resolve each edge's target to the re-indexed node's new id by
     * (kind, name); targets that vanished are resurrected as their original
     * unresolved ref (#1240's removal-side counterpart) when the edge carries
     * its refName stamp.
     */
    private reattachCrossFileEdges;
    /**
     * Re-open, for re-resolution, every resolution edge whose answer this sync
     * may have changed — the fix for index drift (CG-33).
     *
     * Incremental sync re-resolves only the references IN the changed files, but
     * resolution's answer is a function of the WHOLE graph: a reference binds to
     * one of the same-named definitions project-wide, so adding or removing a
     * definition of `pct` can change which `pct` every other file's `pct(...)`
     * should bind to. Those other files are never revisited, and their references
     * resolved successfully once and were deleted from `unresolved_refs`, so
     * nothing existed to revisit them with — the index kept an answer that was
     * correct against an older graph. Measured on codegraph's own long-lived
     * index: 4.3% of distinct edges differed from a clean rebuild, in BOTH
     * directions, overwhelmingly `calls`. See docs/benchmarks/index-drift-cg33.md.
     *
     * This deletes each affected edge and re-inserts it as the reference that
     * created it (the refName/refKind stamp), status='pending', for the sync's
     * resolution sweep to bind against the post-sync graph — the same input a
     * full rebuild resolves from, which is what makes the two converge.
     *
     * Deliberately conservative in three ways, because a wrong deletion is a
     * permanent edge loss while a missed rebind is only residual drift:
     * - an edge with no refName stamp (synthesized, or built by an engine older
     *   than the stamp) is left ALONE rather than reconstructed from the target's
     *   plain name, same rule as `resurrectRefFromDroppedEdge`;
     * - edges whose source is in a file this sync already re-extracted are
     *   skipped — their references were re-resolved from scratch moments ago;
     * - very common names are skipped by the per-name ceiling in
     *   `getResolutionEdgesByTargetName`.
     *
     * Returns the number of references resurrected.
     */
    resurrectStaleResolutionEdges(definitionDelta: string[], changedFilePaths: string[]): number;
    /**
     * Sync the index with the current file state.
     *
     * Change detection is filesystem-based, never git: a (size, mtime) stat
     * pre-filter skips unchanged files, then a content-hash compare confirms real
     * changes. This works in non-git projects and catches committed changes from
     * `git pull`/`checkout`/`merge`/`rebase` that `git status` cannot see.
     */
    sync(onProgress?: (progress: IndexProgress) => void, 
    /**
     * Watcher fast path: the exact project-relative paths the OS reported as
     * changed. When provided, reconciliation runs over ONLY these paths —
     * per-path logic identical to the full walk (stat pre-filter, hash
     * confirm, the #1240 removal/resurrection flow) — skipping the O(repo)
     * scan and tracked-load. Callers must pass undefined whenever the change
     * set is not exactly known (directory removals, event overflow): the full
     * scan-diff remains the ground truth those cases need (#1285).
     */
    scopedPaths?: string[]): Promise<SyncResult>;
    /**
     * Get files that have changed since last index.
     * Uses git status as a fast path when available, falling back to full scan.
     */
    getChangedFiles(): {
        added: string[];
        modified: string[];
        removed: string[];
    };
}
export { extractFromSource } from './tree-sitter';
export { detectLanguage, isSourceFile, isLanguageSupported, isGrammarLoaded, getSupportedLanguages, initGrammars, loadGrammarsForLanguages, loadAllGrammars } from './grammars';
//# sourceMappingURL=index.d.ts.map