UNPKG

@tobilu/qmd

Version:

Query Markup Documents - On-device hybrid search for markdown files with BM25, vector search, and LLM reranking

1,348 lines • 57.8 kB
/**
 * QMD Store - Core data access and retrieval functions
 *
 * This module provides all database operations, search functions, and document
 * retrieval for QMD. It returns raw data structures that can be formatted by
 * CLI or MCP consumers.
 *
 * Usage:
 *   const store = createStore("/path/to/db.sqlite");
 *   // or use default path:
 *   const store = createStore();
 */
import { type EmbedLockBusyReason } from "./cli/embed-lock.js";
import type { Database } from "./db.js";
import { LlamaCpp, formatQueryForEmbedding, formatDocForEmbedding, type ILLMSession } from "./llm.js";
import type { NamedCollection, Collection, CollectionConfig } from "./collections.js";
import { type DocumentMetadata } from "./metadata.js";
import { type DocumentProcessor } from "./processors.js";
import { type MetadataFilter } from "./metadata-filter.js";
import { type MetadataKeyOverview } from "./metadata-store.js";
export declare const DEFAULT_EMBED_MODEL = "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";
export declare const DEFAULT_RERANK_MODEL = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf";
export declare const DEFAULT_QUERY_MODEL = "hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf";
export declare const DEFAULT_GLOB = "**/*.md";
/**
 * Split a collection glob mask into fast-glob patterns.
 *
 * `--mask "a.md,*.txt"` is a comma-separated union (issue #557), but
 * fast-glob treats a comma outside `{...}` as a literal character, so
 * the joined string matches nothing. Brace form `{a.md,*.txt}` is
 * already valid glob syntax and is left intact.
 *
 * Commas inside `{...}` or `[...]` are not separators. Empty segments
 * after the split are dropped.
 */
export declare function splitGlobMask(mask: string): string[];
export declare const DEFAULT_MULTI_GET_MAX_BYTES: number;
export declare const DEFAULT_EMBED_MAX_DOCS_PER_BATCH = 64;
export declare const DEFAULT_EMBED_MAX_BATCH_BYTES: number;
export declare const DEFAULT_EMBED_MAX_DURATION_MS: number;
export declare const CHUNK_SIZE_TOKENS = 900;
export declare const CHUNK_OVERLAP_TOKENS: number;
export declare const CHUNK_SIZE_CHARS: number;
export declare const CHUNK_OVERLAP_CHARS: number;
export declare const CHUNK_WINDOW_TOKENS = 200;
export declare const CHUNK_WINDOW_CHARS: number;
export declare function getEmbeddingFingerprint(model?: string): string;
/**
 * A potential break point in the document with a base score indicating quality.
 */
export interface BreakPoint {
    pos: number;
    score: number;
    type: string;
}
/**
 * A region where a code fence exists (between ``` markers).
 * We should never split inside a code fence.
 */
export interface CodeFenceRegion {
    start: number;
    end: number;
}
/**
 * Patterns for detecting break points in markdown documents.
 * Higher scores indicate better places to split.
 * Scores are spread wide so headings decisively beat lower-quality breaks.
 * Order matters for scoring - more specific patterns first.
 */
export declare const BREAK_PATTERNS: [RegExp, number, string][];
/**
 * Scan text for all potential break points.
 * Returns sorted array of break points with higher-scoring patterns taking precedence
 * when multiple patterns match the same position.
 */
export declare function scanBreakPoints(text: string): BreakPoint[];
/**
 * Find all code fence regions in the text.
 * Code fences are delimited by ``` and we should never split inside them.
 */
export declare function findCodeFences(text: string): CodeFenceRegion[];
/**
 * Check if a position is inside a code fence region.
 */
export declare function isInsideCodeFence(pos: number, fences: CodeFenceRegion[]): boolean;
/**
 * Find the best cut position using scored break points with distance decay.
 *
 * Uses squared distance for gentler early decay - headings far back still win
 * over low-quality breaks near the target.
 *
 * @param breakPoints - Pre-scanned break points from scanBreakPoints()
 * @param targetCharPos - The ideal cut position (e.g., maxChars boundary)
 * @param windowChars - How far back to search for break points (default ~200 tokens)
 * @param decayFactor - How much to penalize distance (0.7 = 30% score at window edge)
 * @param codeFences - Code fence regions to avoid splitting inside
 * @returns The best position to cut at
 */
export declare function findBestCutoff(breakPoints: BreakPoint[], targetCharPos: number, windowChars?: number, decayFactor?: number, codeFences?: CodeFenceRegion[]): number;
export type ChunkStrategy = "auto" | "regex";
/**
 * Merge two sets of break points (e.g. regex + AST), keeping the highest
 * score at each position. Result is sorted by position.
 */
export declare function mergeBreakPoints(a: BreakPoint[], b: BreakPoint[]): BreakPoint[];
/**
 * Core chunk algorithm that operates on precomputed break points and code fences.
 * This is the shared implementation used by both regex-only and AST-aware chunking.
 */
export declare function chunkDocumentWithBreakPoints(content: string, breakPoints: BreakPoint[], codeFences: CodeFenceRegion[], maxChars?: number, overlapChars?: number, windowChars?: number): {
    text: string;
    pos: number;
}[];
export declare const STRONG_SIGNAL_MIN_SCORE = 0.85;
export declare const STRONG_SIGNAL_MIN_GAP = 0.15;
export declare const RERANK_CANDIDATE_LIMIT = 40;
/**
 * A typed query expansion result. Decoupled from llm.ts internal Queryable —
 * same shape, but store.ts owns its own public API type.
 *
 * - lex: keyword variant → routes to FTS only
 * - vec: semantic variant → routes to vector only
 * - hyde: hypothetical document → routes to vector only
 */
export type ExpandedQuery = {
    type: 'lex' | 'vec' | 'hyde';
    query: string;
    /** Optional line number for error reporting (CLI parser) */
    line?: number;
};
export declare function homedir(): string;
/**
 * Check if a path is absolute.
 * Supports:
 * - Unix paths: /path/to/file
 * - Windows native: C:\path or C:/path
 * - Git Bash: /c/path or /C/path (C-Z drives, excluding A/B floppy drives)
 *
 * Note: /c without trailing slash is treated as Unix path (directory named "c"),
 * while /c/ or /c/path are treated as Git Bash paths (C: drive).
 */
export declare function isAbsolutePath(path: string): boolean;
/**
 * Normalize path separators to forward slashes.
 * Converts Windows backslashes to forward slashes.
 */
export declare function normalizePathSeparators(path: string): string;
/**
 * Get the relative path from a prefix.
 * Returns null if path is not under prefix.
 * Returns empty string if path equals prefix.
 */
export declare function getRelativePathFromPrefix(path: string, prefix: string): string | null;
export declare function resolve(...paths: string[]): string;
export declare function enableProductionMode(): void;
/** Reset production mode flag — only for testing. */
export declare function _resetProductionModeForTesting(): void;
export declare function getDefaultDbPath(indexName?: string): string;
export declare function getPwd(): string;
export declare function getRealPath(path: string): string;
/**
 * True if `target` is `dir` or a descendant, after resolving symlinks.
 * Used to keep indexing and qmd:// filesystem resolution inside a collection.
 */
export declare function isPathInsideDir(dir: string, target: string): boolean;
export type VirtualPath = {
    collectionName: string;
    path: string;
    indexName?: string;
};
/**
 * Normalize explicit virtual path formats to standard qmd:// format.
 * Only handles paths that are already explicitly virtual:
 * - qmd://collection/path.md (already normalized)
 * - qmd:////collection/path.md (extra slashes - normalize)
 * - //collection/path.md (missing qmd: prefix - add it)
 *
 * Does NOT handle:
 * - collection/path.md (bare paths - could be filesystem relative)
 * - :linenum suffix (should be parsed separately before calling this)
 */
export declare function normalizeVirtualPath(input: string): string;
/**
 * Parse a virtual path like "qmd://collection-name/path/to/file.md"
 * into its components.
 * Also supports collection root: "qmd://collection-name/" or "qmd://collection-name"
 */
export declare function parseVirtualPath(virtualPath: string): VirtualPath | null;
/**
 * Build a virtual path from collection name and relative path.
 */
export declare function buildVirtualPath(collectionName: string, path: string, indexName?: string): string;
/**
 * Check if a path is explicitly a virtual path.
 * Only recognizes explicit virtual path formats:
 * - qmd://collection/path.md
 * - //collection/path.md
 *
 * Does NOT consider bare collection/path.md as virtual - that should be
 * handled separately by checking if the first component is a collection name.
 */
export declare function isVirtualPath(path: string): boolean;
/**
 * Resolve a virtual path to absolute filesystem path.
 */
export declare function resolveVirtualPath(db: Database, virtualPath: string): string | null;
/**
 * Convert an absolute filesystem path to a virtual path.
 * Returns null if the file is not in any indexed collection.
 */
export declare function toVirtualPath(db: Database, absolutePath: string): string | null;
export declare function verifySqliteVecLoaded(db: Database): void;
/**
 * FTS5's unicode61 tokenizer does not segment CJK text into searchable words.
 * Normalize CJK runs by spacing every character so exact CJK queries can be
 * translated into phrase queries while Latin text keeps the default tokenizer.
 */
export declare function normalizeCjkForFTS(text: string): string;
/** @internal Install the rebuild publish-race seam; pass null to clear it. */
export declare function _setFtsRebuildBeforePublishHookForTesting(hook: ((db: Database) => void) | null): void;
export declare function getStoreCollections(db: Database): NamedCollection[];
export declare function getStoreCollection(db: Database, name: string): NamedCollection | null;
export declare function getStoreGlobalContext(db: Database): string | undefined;
export declare function getStoreContexts(db: Database): Array<{
    collection: string;
    path: string;
    context: string;
}>;
export declare function upsertStoreCollection(db: Database, name: string, collection: Omit<Collection, 'pattern'> & {
    pattern?: string;
}): void;
export declare function deleteStoreCollection(db: Database, name: string): boolean;
export declare function renameStoreCollection(db: Database, oldName: string, newName: string): boolean;
export declare function updateStoreContext(db: Database, collectionName: string, path: string, text: string): boolean;
export declare function removeStoreContext(db: Database, collectionName: string, path: string): boolean;
export declare function setStoreGlobalContext(db: Database, value: string | undefined): void;
/**
 * Clear the stored config hash so the next sync re-derives `store_collections`
 * from the configuration instead of trusting a hash that was stamped before a
 * direct database write. Every mirror of a configuration mutation uses it: the
 * rows and the hash must not certify different documents.
 */
export declare function invalidateConfigHash(db: Database): void;
/**
 * Sync external config (YAML/inline) into SQLite store_collections.
 * External config always wins. Skips sync if config hash hasn't changed.
 *
 * The whole mirror is one immediate transaction, so a reader never observes a
 * half-applied config and the hash commits with the rows it certifies. Callers
 * that read the config from a file must read it under the file's lock and call
 * this while still holding it — see `CollectionConfigScope.withLockedConfig` —
 * otherwise a mutation another process published between the read and this
 * call is deleted from `store_collections` and the stale hash is stamped over
 * it. Cross-resource atomicity is not claimed: a crash between the file
 * publish and this commit leaves the database behind the file, and the
 * `config_hash` mismatch makes the next sync repair it.
 */
export declare function syncConfigToDb(db: Database, config: CollectionConfig): void;
export declare function isSqliteVecAvailable(): boolean;
export type Store = {
    db: Database;
    dbPath: string;
    /** Optional LlamaCpp instance for this store (overrides the global singleton) */
    llm?: LlamaCpp;
    close: () => void;
    ensureVecTable: (dimensions: number) => void;
    getHashesNeedingEmbedding: (model?: string) => number;
    getIndexHealth: (model?: string) => IndexHealthInfo;
    getStatus: (model?: string) => IndexStatus;
    getStatusSummary: (model?: string) => IndexStatusSummary;
    getCacheKey: typeof getCacheKey;
    getCachedResult: (cacheKey: string) => string | null;
    setCachedResult: (cacheKey: string, result: string) => void;
    clearCache: () => void;
    deleteLLMCache: () => number;
    deleteInactiveDocuments: () => number;
    cleanupOrphanedContent: () => number;
    cleanupOrphanedVectors: () => number;
    vacuumDatabase: () => void;
    getContextForFile: (filepath: string) => string | null;
    getContextForPath: (collectionName: string, path: string) => string | null;
    getCollectionByName: (name: string) => {
        name: string;
        pwd: string;
        glob_pattern: string;
    } | null;
    getCollectionsWithoutContext: () => {
        name: string;
        pwd: string;
        doc_count: number;
    }[];
    getTopLevelPathsWithoutContext: (collectionName: string) => string[];
    parseVirtualPath: typeof parseVirtualPath;
    buildVirtualPath: typeof buildVirtualPath;
    isVirtualPath: typeof isVirtualPath;
    resolveVirtualPath: (virtualPath: string) => string | null;
    toVirtualPath: (absolutePath: string) => string | null;
    searchFTS: (query: string, limit?: number, collectionName?: string | readonly string[], filter?: MetadataFilter) => SearchResult[];
    searchVec: (query: string, model: string, limit?: number, collectionName?: string | readonly string[], session?: ILLMSession, precomputedEmbedding?: number[], filter?: MetadataFilter) => Promise<SearchResult[]>;
    expandQuery: (query: string, model?: string) => Promise<ExpandedQuery[]>;
    /** Drop the cached expansion for a query so the next call regenerates. */
    invalidateExpansionCache: (query: string) => void;
    rerank: (query: string, documents: {
        file: string;
        text: string;
    }[], model?: string, intent?: string, signal?: AbortSignal) => Promise<{
        file: string;
        score: number;
    }[]>;
    findDocument: (filename: string, options?: {
        includeBody?: boolean;
    }) => DocumentResult | DocumentLookupError;
    getDocumentBody: (doc: DocumentResult | {
        filepath: string;
    }, fromLine?: number, maxLines?: number) => string | null;
    findDocuments: (pattern: string, options?: {
        includeBody?: boolean;
        maxBytes?: number;
    }) => {
        docs: MultiGetResult[];
        errors: string[];
    };
    findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => string[];
    matchFilesByGlob: (pattern: string) => {
        filepath: string;
        displayPath: string;
        bodyLength: number;
    }[];
    findDocumentByDocid: (docid: string) => {
        filepath: string;
        hash: string;
    } | null;
    insertContent: (hash: string, content: string, createdAt: string) => void;
    insertDocument: (collectionName: string, path: string, title: string, hash: string, createdAt: string, modifiedAt: string) => number;
    findActiveDocument: (collectionName: string, path: string) => {
        id: number;
        hash: string;
        title: string;
    } | null;
    findOrMigrateLegacyDocument: (collectionName: string, path: string) => {
        id: number;
        hash: string;
        title: string;
    } | null;
    updateDocumentTitle: (documentId: number, title: string, modifiedAt: string) => void;
    updateDocument: (documentId: number, title: string, hash: string, modifiedAt: string) => void;
    deactivateDocument: (collectionName: string, path: string) => void;
    getActiveDocumentPaths: (collectionName: string) => string[];
    getHashesForEmbedding: () => {
        hash: string;
        body: string;
        path: string;
    }[];
    clearAllEmbeddings: () => void;
    insertEmbedding: (hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string, totalChunks?: number, fingerprint?: string) => void;
};
export type ReindexProgress = {
    file: string;
    current: number;
    total: number;
};
export type ReindexSkippedFile = {
    file: string;
    code: string;
};
export type ReindexResult = {
    indexed: number;
    updated: number;
    unchanged: number;
    removed: number;
    orphanedCleaned: number;
    skipped: number;
    skippedFiles: ReindexSkippedFile[];
    /** Documents whose qmd.metadata frontmatter failed extraction this pass. */
    metadataErrors: number;
};
/**
 * Maximum file size to index — prevents OOM on accidental binary inclusion.
 */
export declare const REINDEX_MAX_FILE_SIZE: number;
/**
 * Groups the per-file writes of a collection scan into short transactions.
 * Committed one by one, a first index of a large collection writes a content
 * row, a document, its metadata and a sync row per file, each its own WAL
 * commit: 20,000 files took about 176 s that way. A batch closes after
 * `maxFiles` files or `maxMs`, so other writers never wait longer than that.
 *
 * An open transaction must never outlive the synchronous stretch that opened
 * it: while the batch is suspended on an `await`, any other writer's statements
 * would execute inside this transaction. `commit()` before awaiting.
 */
export declare function scanWriteBatch(db: Database, maxFiles?: number, maxMs?: number): {
    /** Call before a file's writes; closes the batch when it is full or old. */
    next(): void;
    commit(): void;
    rollback(): void;
};
/**
 * Re-index a single collection by scanning the filesystem and updating the database.
 * Uses mtime+size fast-path (file_sync_state) to avoid re-reading unchanged files.
 * Pure function — no console output, no db lifecycle management.
 *
 * Fast-path: stat mtime_ms+size against cached row to skip file read.
 * If mtime changed but content hash identical, only mtime cache is updated.
 * Skips >10MB and empty files, cleans sync table entry on orphan removal.
 */
export declare function reindexCollection(store: Store, collectionPath: string, globPattern: string, collectionName: string, options?: {
    ignorePatterns?: string[];
    processor?: DocumentProcessor;
    signal?: AbortSignal;
    /**
     * Called synchronously from inside the scan's write-batch transaction.
     * Statements it runs join that transaction by design (they commit or roll
     * back with the scan), so it must not commit or roll it back, and it must
     * not start another scan of this store. It must return synchronously: work
     * it defers can land in a later batch's transaction.
     */
    onProgress?: (info: ReindexProgress) => void;
}): Promise<ReindexResult>;
export type EmbedFailure = {
    path: string;
    hash: string;
    seq: number;
    attempts: number;
    reason: string;
};
export type EmbedProgress = {
    chunksEmbedded: number;
    totalChunks: number;
    bytesProcessed: number;
    totalBytes: number;
    /** Active failed chunks still awaiting a successful retry. */
    errors: number;
    failures?: EmbedFailure[];
};
export type EmbedResult = {
    docsProcessed: number;
    chunksEmbedded: number;
    /** Chunks copied into the partition of a collection that gained an already-embedded hash. */
    chunksCopied: number;
    /** Active failed chunks that did not recover after retries. */
    errors: number;
    failures?: EmbedFailure[];
    durationMs: number;
    /**
     * True when this run found no documents waiting for embeddings, so a caller
     * can report "everything is already embedded" instead of a zero-chunk run.
     *
     * This is answered inside the embed lock on purpose: probing for pending work
     * before taking the lock can see another run's in-flight state, and taking
     * the lock to probe and then taking it again would reintroduce the very
     * double acquisition the lock exists to prevent. Callers that want their
     * "no work" message to be authoritative must use this flag — a zero
     * docsProcessed alone also covers runs whose documents were all empty.
     */
    nothingToDo: boolean;
};
/**
 * Thrown when an embed run cannot start because another run already owns this
 * index's embed lock — another process (CLI, SDK, or a direct
 * generateEmbeddings call), or a run this process already has in flight.
 *
 * Embedding is exclusive per index. Two runs embedding the same hashes
 * interleave their partial-chunk cleanup and their vector publication, so each
 * can delete what the other just completed and the index can be left with
 * chunks no run believes it wrote (#825). Ownership is a sidecar SQLite write
 * transaction next to the index (`cli/embed-lock.ts`), so a crashed holder can
 * never leave the lock stuck.
 *
 * The CLI reports this as "Another embed process is already running.
 * Skipping."; library callers can catch it to back off or ask the user to wait
 * for the running embed to finish.
 */
export declare class EmbedLockBusyError extends Error {
    /** Sidecar lock path that another run owns. */
    readonly lockPath: string;
    /** Which artifact made this attempt lose (current sidecar or legacy pidfile). */
    readonly reason: EmbedLockBusyReason;
    constructor(lockPath: string, reason: EmbedLockBusyReason);
}
export type EmbedOptions = {
    signal?: AbortSignal;
    force?: boolean;
    model?: string;
    /**
     * Restrict embedding to documents in a single collection.
     * When omitted, all pending documents across every collection are embedded.
     */
    collection?: string;
    maxDocsPerBatch?: number;
    maxBatchBytes?: number;
    chunkStrategy?: ChunkStrategy;
    /**
     * Max wall-clock duration for the whole embed session, in milliseconds. When the
     * cap is reached, remaining document batches are skipped (re-run `qmd embed` to
     * continue). A value <= 0 disables the cap. Defaults to
     * {@link DEFAULT_EMBED_MAX_DURATION_MS} (30 minutes).
     */
    maxDurationMs?: number;
    onProgress?: (info: EmbedProgress) => void;
};
/**
 * Generate vector embeddings for documents that need them.
 * Pure function — no console output, no db lifecycle management.
 * Uses the store's LlamaCpp instance if set, otherwise the global singleton.
 *
 * Exclusive per index: the run holds the sidecar embed lock from before it
 * clears, copies or reads pending vectors until after its last publication, so
 * a concurrent CLI/SDK/direct run cannot interleave partial-chunk cleanup and
 * vector writes with this one. Rejects with {@link EmbedLockBusyError} when
 * another run already owns the lock; the lock is released on success, error
 * and cancellation. A `force` clear goes through the lock-held body: this run
 * already owns the lock and must not try to acquire it again.
 */
export declare function generateEmbeddings(store: Store, options?: EmbedOptions): Promise<EmbedResult>;
/**
 * Create a new store instance with the given database path.
 * If no path is provided, uses the default path (~/.cache/qmd/index.sqlite).
 *
 * @param dbPath - Path to the SQLite database file
 * @returns Store instance with all methods bound to the database
 */
export declare function createStore(dbPath?: string): Store;
/**
 * Unified document result type with all metadata.
 * Body is optional - use getDocumentBody() to load it separately if needed.
 */
export type DocumentResult = {
    filepath: string;
    displayPath: string;
    title: string;
    context: string | null;
    hash: string;
    docid: string;
    collectionName: string;
    modifiedAt: string;
    bodyLength: number;
    body?: string;
};
/**
 * Extract short docid from a full hash (first 6 characters).
 */
export declare function getDocid(hash: string): string;
export declare function handelize(path: string): string;
/**
 * Search result extends DocumentResult with score and source info
 */
export type SearchResult = DocumentResult & {
    metadata: DocumentMetadata;
    score: number;
    source: "fts" | "vec";
    chunkPos?: number;
};
/**
 * Ranked result for RRF fusion (simplified, used internally)
 */
export type RankedResult = {
    file: string;
    displayPath: string;
    title: string;
    body: string;
    score: number;
};
export type RRFContributionTrace = {
    listIndex: number;
    source: "fts" | "vec";
    queryType: "original" | "lex" | "vec" | "hyde";
    query: string;
    rank: number;
    weight: number;
    backendScore: number;
    rrfContribution: number;
};
export type RRFScoreTrace = {
    contributions: RRFContributionTrace[];
    baseScore: number;
    topRank: number;
    topRankBonus: number;
    totalScore: number;
};
export type HybridQueryExplain = {
    ftsScores: number[];
    vectorScores: number[];
    rrf: {
        rank: number;
        positionScore: number;
        weight: number;
        baseScore: number;
        topRankBonus: number;
        totalScore: number;
        contributions: RRFContributionTrace[];
    };
    rerankScore: number;
    blendedScore: number;
};
/**
 * Error result when document is not found
 */
export type DocumentNotFound = {
    error: "not_found";
    query: string;
    similarFiles: string[];
};
export type DocumentExcludedByIgnore = {
    error: "excluded_by_ignore";
    query: string;
    collection: string;
    path: string;
    rule: string;
};
export type DocumentLookupError = DocumentNotFound | DocumentExcludedByIgnore;
/**
 * Result from multi-get operations
 */
export type MultiGetResult = {
    doc: DocumentResult;
    skipped: false;
} | {
    doc: Pick<DocumentResult, "filepath" | "displayPath">;
    skipped: true;
    skipReason: string;
};
export type CollectionInfo = {
    name: string;
    path: string | null;
    pattern: string | null;
    documents: number;
    lastUpdated: string;
    /** Distinct metadata keys declared in this collection. */
    metadataKeyCount: number;
    /**
     * The most covered metadata keys in this collection, with coverage and
     * types, by coverage. Windowed to STATUS_METADATA_KEY_LIMIT; `listMetadata`
     * pages through the rest.
     */
    metadataKeys: MetadataKeyOverview[];
};
/** Keys a status view names per collection before pointing at discovery. */
export declare const STATUS_METADATA_KEY_LIMIT = 10;
export type IndexStatus = {
    totalDocuments: number;
    needsEmbedding: number;
    hasVectorIndex: boolean;
    /** Active documents without current, error-free metadata extraction. */
    pendingMetadata: number;
    collections: CollectionInfo[];
};
/** Index facts for initialization, without computing unused metadata overviews. */
export type IndexStatusSummary = Omit<IndexStatus, "collections"> & {
    collections: Omit<CollectionInfo, "metadataKeyCount" | "metadataKeys">[];
};
export type EmbeddingVectorSample = {
    hash: string;
    seq: number;
    pos: number;
    body: string;
    path: string;
};
export declare function getEmbeddingVectorSamples(db: Database, model: string, fingerprint: string, sampleSize?: number): EmbeddingVectorSample[];
export declare function getHashesNeedingEmbedding(db: Database, collection?: string, model?: string): number;
export type IndexHealthInfo = {
    needsEmbedding: number;
    totalDocs: number;
    daysStale: number | null;
};
export type LegacyFingerprintAdoptionResult = {
    checked: boolean;
    adopted: number;
    reason: string;
};
export declare function maybeAdoptLegacyEmbeddingFingerprint(store: Store, model?: string): Promise<LegacyFingerprintAdoptionResult>;
export declare function getIndexHealth(db: Database, model?: string): IndexHealthInfo;
export type CacheKeyBody = {
    query?: string;
    model?: string;
    chunk?: string;
    file?: string;
};
export declare function getCacheKey(url: string, body: CacheKeyBody): string;
export declare function getCachedResult(db: Database, cacheKey: string): string | null;
export declare function setCachedResult(db: Database, cacheKey: string, result: string): void;
export declare function clearCache(db: Database): void;
/**
 * Delete cached LLM API responses.
 * Returns the number of cached responses deleted.
 */
export declare function deleteLLMCache(db: Database): number;
/**
 * Remove inactive document records (active = 0).
 * Returns the number of inactive documents deleted.
 */
export declare function deleteInactiveDocuments(db: Database): number;
/**
 * Remove orphaned content hashes that are not referenced by any document.
 * Inactive documents are soft-deleted tombstones, so their content rows must
 * remain referenced until deleteInactiveDocuments() hard-deletes them.
 * Returns the number of orphaned content hashes deleted.
 */
export declare function cleanupOrphanedContent(db: Database): number;
/**
 * Count content hashes that would be unreferenced after inactive documents
 * are hard-deleted. Shared hashes still used by an active document are kept.
 */
export declare function countOrphanedContent(db: Database): number;
/**
 * Count embedding chunks whose hash is not referenced by any active document.
 * Reads `content_vectors` only, so this works even when sqlite-vec is unavailable (#768).
 */
export declare function countOrphanedVectors(db: Database): number;
/**
 * Remove vector rows whose (hash, collection) no active document references,
 * and the content_vectors rows of hashes no active document references at
 * all. Returns the number of orphaned chunks deleted.
 */
export declare function cleanupOrphanedVectors(db: Database): number;
export type VectorTableLayout = {
    rows: number;
    chunks: number;
    /** Chunks a freshly packed table needs for the same rows. */
    neededChunks: number;
    /** neededChunks over chunks: the share of a scan's chunk reads that hold live rows. */
    occupancy: number;
};
/** Chunk layout of the vector table from vec0's shadow tables, or null without a readable table. */
export declare function vectorTableLayout(db: Database): VectorTableLayout | null;
/**
 * Compact the vector table in place: the live rows of every chunk that is
 * mostly holes are deleted and re-inserted under their rowid and partition,
 * one chunk per IMMEDIATE transaction. vec0 puts each insert in the first
 * free slot of its partition's newest chunk and drops a chunk once it is
 * empty, so the moved rows fill that partition's tail and the emptied chunks
 * vanish; each partition's newest chunk is left alone because that is where
 * its rows land. A transaction holds the write lock for at most one chunk of
 * rows, so concurrent embed and update runs interleave with it, and an
 * interrupted run leaves a consistent table that the next cleanup finishes.
 */
export declare function repackVectors(db: Database, onChunk?: (moved: number, total: number) => void): VectorTableLayout | null;
/**
 * Run VACUUM to reclaim unused space in the database.
 * This operation rebuilds the database file to eliminate fragmentation.
 */
export declare function vacuumDatabase(db: Database): void;
/**
 * Merge FTS5 b-trees so deleted rows (deactivated / hard-deleted documents)
 * leave `documents_fts_data`. VACUUM alone does not compact FTS5 (#550).
 */
export declare function optimizeDocumentsFts(db: Database): void;
export type CleanupStats = {
    cacheCount: number;
    orphanedVectors: number;
    inactiveDocs: number;
    orphanedContent: number;
    /** Chunk layout of the vector table before any repack, null without a vector table. */
    vectorLayout: VectorTableLayout | null;
    /** True when the vector table was repacked (or, in a preview, would be). */
    vectorsRepacked: boolean;
};
/** Counts what `runCleanup` would remove, including content only held by inactive docs. */
export declare function previewCleanup(db: Database): CleanupStats;
export type CleanupHooks = {
    /** Called with the layout right before a vector repack starts. */
    onVectorRepack?: (layout: VectorTableLayout) => void;
};
/**
 * Full `qmd cleanup` sequence: drop cache, orphaned vectors, repack the vector
 * table when its chunks are mostly holes, inactive document rows, then the
 * content those rows were pinning, compact FTS5, vacuum.
 */
export declare function runCleanup(db: Database, hooks?: CleanupHooks): CleanupStats;
/**
 * Synchronous core of {@link hashContent}. Callers that hash while their write
 * batch holds the connection's transaction (collection scans, the CLI index
 * loop) must use this: awaiting a hash hands that transaction to whatever else
 * runs during the suspension.
 */
export declare function hashContentSync(content: string): string;
export declare function hashContent(content: string): Promise<string>;
export declare function extractTitle(content: string, filename: string): string;
/**
 * Insert content into the content table (content-addressable storage).
 * Uses INSERT OR IGNORE so duplicate hashes are skipped.
 */
export declare function insertContent(db: Database, hash: string, content: string, createdAt: string): void;
/**
 * Insert a new document into the documents table.
 * Returns the document's id so callers can attach document-scoped state.
 */
export declare function insertDocument(db: Database, collectionName: string, path: string, title: string, hash: string, createdAt: string, modifiedAt: string): number;
/**
 * Find an active document by collection name and path.
 */
export declare function findActiveDocument(db: Database, collectionName: string, path: string): {
    id: number;
    hash: string;
    title: string;
} | null;
/**
 * Find an active document, falling back to a legacy handalized-path match.
 * If found under the pre-2.6 slug, renames it in-place and rebuilds the
 * FTS entry. Embeddings are keyed by content hash, so the rename is
 * safe — no re-embedding required.
 *
 * `livePaths`, when given, is the set of literal paths of every file in the
 * current scan of this collection. A legacy row whose path is in that set
 * belongs to a *different* file that still exists on disk, so it must never be
 * adopted — renaming it would evict that file from the index (#717).
 *
 * @internal Used by reindexCollection and indexFiles during qmd update.
 * Returns null if the document does not exist under either path.
 */
export declare function findOrMigrateLegacyDocument(db: Database, collectionName: string, path: string, livePaths?: ReadonlySet<string>): {
    id: number;
    hash: string;
    title: string;
} | null;
/**
 * Update the title and modified_at timestamp for a document.
 */
export declare function updateDocumentTitle(db: Database, documentId: number, title: string, modifiedAt: string): void;
/**
 * Update an existing document's hash, title, and modified_at timestamp.
 * Used when content changes but the file path stays the same.
 */
export declare function updateDocument(db: Database, documentId: number, title: string, hash: string, modifiedAt: string): void;
/**
 * Deactivate a document (mark as inactive but don't delete).
 */
export declare function deactivateDocument(db: Database, collectionName: string, path: string): void;
/**
 * Get all active document paths for a collection.
 */
export declare function getActiveDocumentPaths(db: Database, collectionName: string): string[];
export { formatQueryForEmbedding, formatDocForEmbedding };
/**
 * Chunk a document using regex-only break point detection.
 * This is the sync, backward-compatible API used by tests and legacy callers.
 */
export declare function chunkDocument(content: string, maxChars?: number, overlapChars?: number, windowChars?: number): {
    text: string;
    pos: number;
}[];
/**
 * Async AST-aware chunking. Detects language from filepath, computes AST
 * break points for supported code files, merges with regex break points,
 * and delegates to the shared chunk algorithm.
 *
 * Falls back to regex-only when strategy is "regex", filepath is absent,
 * or language is unsupported.
 */
export declare function chunkDocumentAsync(content: string, maxChars?: number, overlapChars?: number, windowChars?: number, filepath?: string, chunkStrategy?: ChunkStrategy): Promise<{
    text: string;
    pos: number;
}[]>;
export declare function chunkDocumentByTokens(content: string, maxTokens?: number, overlapTokens?: number, windowTokens?: number, filepath?: string, chunkStrategy?: ChunkStrategy, signal?: AbortSignal): Promise<{
    text: string;
    pos: number;
    tokens: number;
}[]>;
/**
 * Normalize a docid input by stripping surrounding quotes and leading #.
 * Handles: "#abc123", 'abc123', "abc123", #abc123, abc123
 * Returns the bare hex string.
 */
export declare function normalizeDocid(docid: string): string;
/**
 * Check if a string looks like a docid reference.
 * Accepts: #abc123, abc123, "#abc123", "abc123", '#abc123', 'abc123'
 * Returns true if the normalized form is a valid hex string of 6+ chars.
 */
export declare function isDocid(input: string): boolean;
/**
 * Find a document by its short docid (first 6 characters of hash).
 * Returns the document's virtual path if found, null otherwise.
 * If multiple documents match the same short hash (collision), returns the first one.
 *
 * Accepts lenient input: #abc123, abc123, "#abc123", "abc123"
 */
export declare function findDocumentByDocid(db: Database, docid: string): {
    filepath: string;
    hash: string;
} | null;
export declare function findSimilarFiles(db: Database, query: string, maxDistance?: number, limit?: number): string[];
export declare function matchFilesByGlob(db: Database, pattern: string): {
    filepath: string;
    displayPath: string;
    bodyLength: number;
}[];
/**
 * Get context for a file path using hierarchical inheritance.
 * Contexts are collection-scoped and inherit from parent directories.
 * For example, context at "/talks" applies to "/talks/2024/keynote.md".
 *
 * @param db Database instance (unused - kept for compatibility)
 * @param collectionName Collection name
 * @param path Relative path within the collection
 * @returns Context string or null if no context is defined
 */
export declare function getContextForPath(db: Database, collectionName: string, path: string): string | null;
/**
 * Get context for a file path (virtual or filesystem).
 * Resolves the collection and relative path from the DB store_collections table.
 */
export declare function getContextForFile(db: Database, filepath: string): string | null;
/**
 * Get collection by name from DB store_collections table.
 */
export declare function getCollectionByName(db: Database, name: string): {
    name: string;
    pwd: string;
    glob_pattern: string;
} | null;
/**
 * List all collections with document counts from database.
 * Merges store_collections config with database statistics.
 */
export declare function listCollections(db: Database): {
    name: string;
    pwd: string;
    glob_pattern: string;
    doc_count: number;
    active_count: number;
    last_modified: string | null;
    includeByDefault: boolean;
}[];
/**
 * Whether the index still holds anything keyed by this collection name:
 * documents, sync rows, processor state or a vector partition.
 *
 * The store_collections row is deliberately excluded. A config sync writes that
 * row straight from the configuration, so a removal or rename whose index half
 * failed — or that crashed between publishing the file and moving the index —
 * leaves the state below under the old name while the row already reflects the
 * published file. Re-running the command finishes that state; see
 * {@link reconcilePublishedRename}.
 */
export declare function hasCollectionIndexState(db: Database, name: string): boolean;
/**
 * Refuse a rename whose target the index cannot take: a populated collection of
 * that name, or a removed collection of that name whose vector partition only a
 * sqlite-vec loaded build can drop.
 *
 * A caller that publishes the configuration before renaming the index calls
 * this first, so an ordinary refusal happens before the file changes. A target
 * row with no documents is not a refusal: a config sync writes rows from the
 * already published file, and {@link reconcilePublishedRename} finishes that
 * rename instead.
 */
export declare function assertRenameTargetAvailable(db: Database, newName: string): void;
/**
 * Remove a collection: its vector partition, its documents, the content no
 * active document references any more, and its store_collections row. Safe to
 * repeat: every step is keyed by the name, so finishing a removal that a
 * later config sync already dropped the row for still deletes what is left.
 */
export declare function removeCollection(db: Database, collectionName: string): {
    deletedDocs: number;
    cleanedHashes: number;
};
/**
 * Rename a collection: its documents, its vector partition id, and its
 * store_collections row. Throws when the target row already exists.
 */
export declare function renameCollection(db: Database, oldName: string, newName: string): void;
/**
 * Finish a rename whose configuration was already published: move whatever the
 * index still holds under `oldName` to `newName`.
 *
 * This is the recovery path for a rename interrupted after its file publish —
 * by a failed index commit or by a crash — and it is idempotent. The caller
 * must only invoke it with evidence of that specific rename (the configuration
 * scope's pending-rename marker, or the publication it just made): "the file no
 * longer lists the old name and lists another name" is not evidence, because
 * that other name may be an unrelated collection and moving documents into it
 * would corrupt its ownership.
 *
 * A config sync may already have written the target row from the published file
 * while the documents were still under the old name, so an existing target row
 * is not a conflict here; a target that owns documents is, and is refused
 * rather than merged. Returns whether the index held anything under either name.
 *
 * The configuration stays authoritative: if this throws, the file already
 * reflects the rename and re-running the same rename finishes it.
 */
export declare function reconcilePublishedRename(db: Database, oldName: string, newName: string): boolean;
/**
 * Insert or update a context for a specific collection and path prefix.
 *
 * `store_collections` is keyed by name (`TEXT PRIMARY KEY`), not an integer id.
 * #754 retargeted this query from the dropped `collections` table but left
 * `WHERE id = ?`, which throws `no such column: id`.
 */
export declare function insertContext(db: Database, collectionName: string, pathPrefix: string, context: string): void;
/**
 * Delete a context for a specific collection and path prefix.
 * Returns the number of contexts deleted.
 */
export declare function deleteContext(db: Database, collectionName: string, pathPrefix: string): number;
/**
 * Delete all global contexts (contexts with empty path_prefix).
 * Returns the number of contexts deleted.
 */
export declare function deleteGlobalContexts(db: Database): number;
/**
 * List all contexts, grouped by collection.
 * Returns contexts ordered by collection name, then by path prefix length (longest first).
 */
export declare function listPathContexts(db: Database): {
    collection_name: string;
    path_prefix: string;
    context: string;
}[];
/**
 * Get all collections (name only - from YAML config).
 */
export declare function getAllCollections(db: Database): {
    name: string;
}[];
/**
 * Check which collections don't have any context defined.
 * Returns collections that have no context entries at all (not even root context).
 */
export declare function getCollectionsWithoutContext(db: Database): {
    name: string;
    pwd: string;
    doc_count: number;
}[];
/**
 * Get top-level directories in a collection that don't have context.
 * Useful for suggesting where context might be needed.
 */
export declare function getTopLevelPathsWithoutContext(db: Database, collectionName: string): string[];
export declare function sanitizeFTS5Term(term: string): string;
/**
 * Validate that a vec/hyde query doesn't use lex-only syntax.
 * Returns error message if invalid, null if valid.
 */
export declare function validateSemanticQuery(query: string): string | null;
export declare function validateLexQuery(query: string): string | null;
/** One collection, several (OR), or all (undefined). */
export type CollectionScope = string | readonly string[] | undefined;
export declare function searchFTS(db: Database, query: string, limit?: number, collectionName?: string | readonly string[], filter?: MetadataFilter): SearchResult[];
export declare function searchVec(db: Database, query: string, model: string, limit?: number, collectionName?: string | readonly string[], session?: ILLMSession, precomputedEmbedding?: number[], llm?: LlamaCpp, filter?: MetadataFilter): Promise<SearchResult[]>;
/**
 * Get all unique content hashes that need embeddings (from active documents).
 * Returns hash, document body, and a sample path for display purposes.
 */
export declare function getHashesForEmbedding(db: Database, model?: string): {
    hash: string;
    body: string;
    path: string;
}[];
/**
 * Clear embeddings for the whole index, or just for one collection.
 *
 * Takes the index's exclusive embed lock, like an embedding run, because a
 * clear and a run both delete vector rows: a whole-index clear drops the vec0
 * table under a run that is publishing chunks into it, and a scoped clear that
 * commits between a run's pending-vector read and its writes can resurrect
 * vectors the user asked to delete. Throws {@link EmbedLockBusyError} instead
 * of interleaving. An embedding run clearing its own vectors for `force` calls
 * the lock-held body, since it already owns the lock.
 *
 * When `collection` is omitted the content_vectors and vector_rows tables are
 * emptied and the vec0 table is dropped (it is recreated with the right
 * dimensions on the next embed run).
 *
 * When `collection` is provided, only chunks whose hash is referenced
 * exclusively by active documents in that collection are removed, from that
 * collection's partition and from content_vectors. Hashes shared with active
 * documents in other collections are left in place so vector search keeps
 * working there (content_vectors is keyed globally by content hash; identical
 * document bodies across collections share a row). The vec0 table is dropped
 * only when the scoped clear empties content_vectors entirely, so the next
 * embed can recreate it with the current dimensions.
 */
export declare function clearAllEmbeddings(db: Database, collection?: string): void;
/** Partition rows written per commit by copyVectorsToNewCollections. */
export declare const VECTOR_COPY_BATCH_ROWS = 1000;
/**
 * Give every active (hash, collection) pair whose chunks are embedded a row
 * in that collection's partition, copied from any partition that holds the
 * chunk, so a hash that gains a collection is searchable there without
 * another model call. A chunk no partition holds is queued for embedding by
 * deleting its hash's rows, which the pending detector then picks up.
 *
 * Rows commit in batches of VECTOR_COPY_BATCH_ROWS so a collection that gains
 * thousands of embedded hashes does not hold the write lock for the whole
 * copy; an interrupted run resumes from whatever missingPartitionRows still
 * reports.
 */
export declare function copyVectorsToNewCollections(db: Database, collection?: string): {
    copied: number;
    queued: number;
};
/**
 * Insert a single embedding: the content_vectors row plus one row in the
 * partition of every active collection that holds the hash, in one
 * transaction so a crash cannot leave the tables out of step. A hash with no
 * active document gets its content_vectors row only.
 */
export declare function insertEmbedding(db: Database, hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string, totalChunks?: number, fingerprint?: string): void;
export declare function expandQuery(query: string, model: string | undefined, db: Database, llmOverride?: LlamaCpp): Promise<ExpandedQuery[]>;
/**
 * Delete the cached expansion for a query. hybridQuery() calls this when an
 * expansion's sub-queries all came back empty — left in place, the dud entry
 * would replay the same misses on every warm repeat of the query.
 */
export declare function deleteExpansionCacheEntry(db: Database, query: string, model?: string): void;
export declare function rerank(query: string, documents: {
    file: string;
    text: string;
}[], model: string | undefined, db: Database, intent?: string, llmOverride?: LlamaCpp, signal?: AbortSignal): Promise<{
    file: string;
    score: number;
}[]>;
export declare function reciprocalRankFusion(resultLists: RankedResult[][], weights?: number[], k?: number): RankedResult[];
/**
 * Build per-document RRF contribution traces for explain/debug output.
 */
export declare function buildRrfTrace(resultLists: RankedResult[][], weights?: number[], listMeta?: RankedListMeta[], k?: number): Map<string, RRFScoreTrace>;
/**
 * Find a document by filename/path, docid (#hash), or with fuzzy matching.
 * Returns document metadata without body by default.
 *
 * Supports:
 * - Virtual paths: qmd://collection/path/to/file.md
 * - Absolute paths: /path/to/file.md
 * - Relative paths: path/to/file.md
 * - Short docid: #abc123 (first 6 chars of hash)
 */
export declare function findDocument(db: Database, filename: string, options?: {
    includeBody?: boolean;
}): DocumentResult | DocumentLookupError;
/**
 * Get the body content for a document
 * Optionally slice by line range
 */
export declare function getDocumentBody(db: Database, doc: DocumentResult | {
    filepath: string;
}, fromLine?: number, maxLines?: number): string | null;
/**
 * Escape a user-supplied string so it is matched literally by SQLite LIKE.
 * Uses '#' as the ESCAPE character (avoids quote-escaping pitfalls with '\\').
 */
export declare function escapeLikePattern(value: string): string;
export type CommaListMatch = {
    collection: string;
    path: string;
    virtualPath: string;
    bodyLength: number;
};
export type CommaListResolve = {
    ok: true;
    match: CommaListMatch;
} | {
    ok: false;
    error: string;
};
/**
 * Resolve one comma-list name for multi-get (shared by CLI and SDK/MCP).
 *
 * Match order: docid / qmd:// URI (exact only), then exact collection-prefixed
 * path, then exact document path, then a path-boundary suffix (`.../name`).
 * Unanchored LIKE is never used, so a fragment like `NTAX.md` cannot silently
 * fetch `SYNTAX.md`. Multiple hits at the same tier error with the candidate
 * list instead of `LIMIT 1` (#759).
 */
export declare function resolveCommaListName(db: Database, name: string): CommaListResolve;
/**
 * Find multiple documents by glob pattern or comma-separated list
 * Returns documents without body by default (use getDocumentBody to load)
 */
export declare function findDocuments(db: Database, pattern: string, options?: {
    includeBody?: boolean;
    maxBytes?: number;
}): {
    docs: MultiGetResult[];
    errors: string[];
};
export declare function getStatus(db: Database, model?: string): IndexStatus;
export declare function getStatusSummary(db: Database, model?: string): IndexStatusSummary;
export type SnippetResult = {
    line: number;
    snippet: string;
    linesBefore: number;
    linesAfter: number;
    snippetLines: number;
};
/** Weight for intent terms relative to query terms (1.0) in snippet scoring */
export declare const INTENT_WEIGHT_SNIPPET = 0.3;
/** Weight for intent terms relative to query terms (1.0) in chunk selection */
export declare const INTENT_WEIGHT_CHUNK = 0.5;
/**
 * Extract meaningful terms from an intent string, filtering stop words and punctuation.
 * Uses Unicode-aware punctuation stripping so domain terms like "API" survive.
 * Returns lowercase terms suitable for text matching.
 */
export declare function extractIntentTerms(intent: string): string[];
export declare function extractSnippet(body: string, query: string, maxLen?: number, chunkPos?: number, chunkLen?: number, intent?: string): SnippetResult;
/**
 * Add line numbers to text content.
 * Each line becomes: "{lineNum}: {content}"
 */
export declare function addLineNumbers(text: string, startLine?: number): string;
/**
 * Optional progress hooks for search orchestration.
 * CLI wires these to stderr for user feedback; MCP leaves them unset.
 */
export interface SearchHooks {
    /** BM25 probe found strong signal — expansion will be skipped */
    onStrongSignal?: (topScore: number) => void;
    /** Query expansion starting */
    onExpandStart?: () => void;
    /** Query expansion complete. Empty array = strong signal skip. elapsedMs = time taken. */
    onExpand?: (original: string, expanded: ExpandedQuery[], elapsedMs: number) => void;
    /** Embedding starting (vec/hyde queries) */
    onEmbedStart?: (count: number) => void;
    /** Embedding complete */
    onEmbedDone?: (elapsedMs: number) => void;
    /** Reranking is about to start */
    onRerankStart?: (chunkCount: number) => void;
    /** Reranking finished */
    onRerankDone?: (elapsedMs: number) => void;
}
export interface HybridQueryOptions {
    signal?: AbortSignal;
    collection?: string | readonly string[];
    filter?: MetadataFilter;
    limit?: number;
    minScore?: number;
    candidateLimit?: number;
    explain?: boolean;
    intent?: string;
    skipRerank?: boolean;
    chunkStrategy?: ChunkStrategy;
    hooks?: SearchHooks;
}
export interface HybridQueryResult {
    file: string;
    displayPath: string;
    title: string;
    body: string;
    bestChunk: string;
    bestChunkPos: number;
    score: number;
    context: string | null;
    docid: string;
    metadata: DocumentMetadata;
    explain?: HybridQueryExplain;
}
export type RankedListMeta = {
    source: "fts" | "vec";
    queryType: "original" | "lex" | "vec" | "hyde";
    query: string;
};
/**
 * RRF list weights for hybridQuery.
 *
 * Original-query retrieval paths are the primary evidence and get 2x weight:
 * - original FTS
 * - original vector search
 *
 * Expansion-derived lists (lex/vec/hyde) stay at 1x regardless of list order,
 * so a lex expansion inserted before original vector search cannot steal the
 * original vector boost.
 */
export declare function getHybridRrfWeights(rankedListMeta: RankedListMeta[]): number[];
/**
 * Hybrid search: BM25 + vector + query expansion + RRF + chunked reranking.
 *
 * Pipeline:
 * 1. BM25 probe → skip expansion if strong signal
 * 2. expandQuery() → typed query variants (lex/vec/hyde)
 * 3. Type-routed search: original→vector, lex→FTS, vec/hyde→vector
 * 4. RRF fusion → slice to candidateLimit
 * 5. chunkDocument() + keyword-best-chunk selection
 * 6. rerank on chunks (NOT full bodies — O(tokens) trap)
 * 7. Position-aware score blending (RRF rank × reranker score)
 * 8. Dedup by file, filter by minScore, slice to limit
 */
export declare function hybridQuery(store: Store, query: string, options?: HybridQueryOptions): Promise<HybridQueryResult[]>;
export interface VectorSearchOptions {
    collection?: string | readonly string[];
    filter?: MetadataFilter;
    limit?: number;
    minScore?: number;
    intent?: string;
    hooks?: Pick<SearchHooks, 'onExpand'>;
}
export interface VectorSearchResult {
    file: string;
    displayPath: string;
    title: string;
    body: string;
    score: number;
    context: string | null;
    docid: string;
    metadata: DocumentMetadata;
}
/**
 * Vector-only semantic search with query expansion.
 *
 * Pipeline:
 * 1. expandQuery() → typed variants, filter to vec/hyde only (lex irrelevant here)
 * 2. searchVec() for original + vec/hyde variants (sequential — node-llama-cpp embed limitation)
 * 3. Dedup by filepath (keep max score)
 * 4. Sort by score descending, filter by minScore, slice to limit
 */
export declare function vectorSearchQuery(store: Store, query: string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
/**
 * A single sub-search in a structured search request.
 * Matches the format used in QMD training data.
 */
export interface StructuredSearchOptions {
    signal?: AbortSignal;
    collections?: string[];
    filter?: MetadataFilter;
    limit?: number;
    minScore?: number;
    candidateLimit?: number;
    explain?: boolean;
    /** Domain intent hint for disambiguation — steers reranking and chunk selection */
    intent?: string;
    /** Skip LLM reranking, use only RRF scores */
    skipRerank?: boolean;
    chunkStrategy?: ChunkStrategy;
    hooks?: SearchHooks;
}
/**
 * Structured search: execute pre-expanded queries without LLM query expansion.
 *
 * Designed for LLM callers (MCP/HTTP) that generate their own query expansions.
 * Skips the internal expandQuery() step — goes directly to:
 *
 * Pipeline:
 * 1. Route searches: lex→FTS, vec/hyde→vector (batch embed)
 * 2. RRF fusion across all result lists
 * 3. Chunk documents + keyword-best-chunk selection
 * 4. Rerank on chunks
 * 5. Position-aware score blending
 * 6. Dedup, filter, slice
 *
 * This is the recommended endpoint for capable LLMs — they can generate
 * better query variations than our small local model, especially for
 * domain-specific or nuanced queries.
 */
export declare function structuredSearch(store: Store, searches: ExpandedQuery[], options?: StructuredSearchOptions): Promise<HybridQueryResult[]>;