/**
 * Extraction Orchestrator
 *
 * Coordinates file scanning, parsing, and database storage.
 */
import * as fs from 'fs';
import { Language, ExtractionResult, ExtractionError } from '../types';
import { QueryBuilder } from '../db/queries';
import { Ignore } from 'ignore';
import { oversizeStamp } from '../file-limits';
export { oversizeStamp };
/**
 * 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;
    /**
     * Files the scan saw but has no grammar for, tallied by extension. Only the
     * degenerate case needs it: a project of unsupported files otherwise looks
     * exactly like an empty one (0 files, state `complete`), so nothing tells the
     * user — or an agent — that there was code here CodeGraph could not read
     * (#1502). Counted during the scan's existing walk.
     */
    filesSkippedUnsupported?: number;
    /** The most common unsupported extensions, biggest first. */
    topUnsupportedExtensions?: {
        ext: string;
        count: number;
    }[];
    nodesCreated: number;
    edgesCreated: number;
    errors: ExtractionError[];
    durationMs: number;
}
/**
 * Result of a sync operation
 */
export interface SyncResult {
    /** References attempted by the pending-reference recovery sweep, if run. */
    pendingRefsProcessed?: number;
    /** Pending references successfully resolved by the recovery sweep. */
    pendingRefsResolved?: number;
    /** Pending references the recovery sweep could not resolve. */
    pendingRefsUnresolved?: number;
    filesChecked: number;
    filesAdded: number;
    filesModified: number;
    filesRemoved: number;
    nodesUpdated: number;
    durationMs: number;
    changedFilePaths?: string[];
    /** Paths not absorbed because reading or extraction failed; retain for status/retry. */
    failedFilePaths?: 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, plus
 * git's other root-relative exclude files (`.git/info/exclude`, `core.excludesFile`)
 * so watcher / FS-walk scope matches `git ls-files --exclude-standard` (#1728).
 * 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` + `.git/info/exclude` +
 * `core.excludesFile`, plus directories `git ls-files --exclude-standard`
 * reports as ignored); paths inside an EMBEDDED repo get that repo's own
 * matcher — 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.
 *
 * Shared by the indexer (scoped sync / skip checks) and the watcher so their
 * scope cannot diverge from each other or from `git ls-files --exclude-standard`
 * (#1728).
 */
/**
 * The grammars to preload for a file set.
 *
 * Path-only detection calls every `.h` file C, but parse-time detection reads
 * the source and can reclassify it as C++ or Objective-C (`detectLanguage`
 * with a `source` argument). Workers only ever get the grammars named here, so
 * a header that turns out to be Objective-C in a project with no `.m` file
 * found no parser and failed with `Failed to get parser for language: objc`
 * (#1628). C++ was already covered; Objective-C was not.
 */
export declare function preloadLanguagesForFiles(files: string[], overrides?: Record<string, Language>): Language[];
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, sinceCommit?: string | null): GitChanges | null;
/**
 * Metadata key: the commit the index was last brought up to date at. Written by
 * a full index AND by every successful sync — unlike the extraction stamp, which
 * a sync must not advance because it only touches a subset of files. This one is
 * about the tree; failed file paths remain explicit retry candidates. (#1829)
 */
export declare const INDEXED_AT_COMMIT_KEY = "indexed_at_commit";
/** HEAD's commit sha, or null in a non-git repo or one with no commits yet. */
export declare function getGitHeadSha(rootDir: string): string | null;
/**
 * Can an INDEX trust the git fast path, given the commit it was built at?
 *
 * False means "fall back to the full scan" — the expensive path that compares
 * every file on disk against the DB, and the only correct read when git cannot
 * say what happened between the stamp and now:
 *
 *  - stamp present but unknown to this repo (rebase, gc, shallow clone, a stamp
 *    from a different checkout) — history moved under the index.
 *  - stamp absent while the repo HAS commits — an index built before stamping
 *    existed. One full scan; the next sync stamps it and the fast path returns.
 *
 * A repo with NO commits keeps the fast path with or without a stamp: every
 * file is untracked, so `git status` already sees all of them. Callers with no
 * index behind them (the exported `getGitChangedFiles`) never ask this — a
 * working-tree diff is the whole of what they wanted. (#1829)
 */
export declare function canTrustGitFastPath(rootDir: string, sinceCommit?: string | null): boolean;
/**
 * 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.
 */
/**
 * What a scan saw but could not index, tallied by extension.
 *
 * Filled during the walk the scan already performs — a project of unsupported
 * files is otherwise indistinguishable from an empty one, because unsupported
 * extensions are filtered out at discovery and never counted anywhere (#1502).
 */
export interface ScanSkipStats {
    /** Lowercased extension (with dot) → how many files carried it. */
    unsupportedByExtension: Map<string, number>;
}
export declare function scanDirectoryAsync(rootDir: string, onProgress?: (current: number, file: string) => void, stats?: ScanSkipStats): 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;
    /** Detected frameworks whose extractors run only inside their own apps, with the packages that mark one. */
    private gatedFrameworks;
    /** `<dir>|<framework>` → does the package.json at or above `dir` declare the framework. */
    private appFrameworkMemo;
    /** Directory → the dependency names its package.json declares, null without one. */
    private manifestDependencies;
    /**
     * The detected frameworks whose extractors apply to `filePath`: all of them,
     * except one with `appDependencies` when neither the file's package.json nor
     * an enclosing one declares any of them.
     */
    private frameworksForFile;
    private frameworkAppliesIn;
    private dependenciesDeclaredIn;
    /**
     * 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): move each edge's target to the re-indexed node that replaces it
     * ({@link pairReindexedNodes}). Targets that vanished, or that can't be
     * told apart from a same-named sibling (#2276), are resurrected as their
     * original unresolved ref (#1240's removal-side counterpart) when the edge
     * carries its refName stamp, so resolution picks the target afresh.
     */
    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[], 
    /**
     * Writer-side WAL pressure valve (#1539). Called after every changed file
     * is stored, when no extraction transaction is open, so a checkpoint can
     * safely catch up before the next file grows the WAL further.
     */
    backpressure?: () => Promise<void> | null, 
    /** Inspect changed inputs before deletion/re-extraction cascades their edges. */
    onFileChange?: (filePath: string, content?: string) => void): Promise<SyncResult>;
    private indexedDirtyPaths;
    /** Capture before file reads. In-flight/failed full writes must not claim freshness. */
    beginGitIndexState(full: boolean): {
        head: string;
        stamp: string;
        dirty: string[] | null;
    };
    finishGitIndexState(snapshot: {
        head: string;
        stamp: string;
        dirty: string[] | null;
    }, full: boolean, retries?: string[]): void;
    /**
     * 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