export declare function extractAliases(frontmatter: Record | undefined | null): string[]; /** * The searchable title for a note = its basename with the `.md` extension * stripped (the note's canonical Obsidian identity). Populates the weighted * FTS5 `title` column. (v3.11.6-rc.6.) */ export declare function deriveFtsTitle(relPath: string): string; /** * FTS5 tokenizer mode. `unicode61` (default) tokenizes on Unicode word * boundaries with diacritic folding — good fit for natural-language * markdown. `trigram` indexes every 3-char substring — slower to build * but better recall on CJK / agglutinative scripts. */ export type TokenizeMode = "unicode61" | "trigram"; /** Content-source kind. v2.7.0 added `pdf`; v2.8.0 indexes them. */ export type ChunkKind = "md" | "pdf"; /** A single hit from {@link FtsIndex.search}. `snippet` carries the * FTS5 `snippet(...)` output (matched terms wrapped in `«»`). */ export interface FtsSearchHit { /** Vault-relative path of the source note / PDF. */ rel_path: string; /** 0-based chunk position within the source. */ chunk_index: number; /** 1-based starting line in the source. */ line_start: number; /** 1-based ending line in the source (inclusive). */ line_end: number; /** Excerpt with matched tokens wrapped in `«»` and `…` truncation markers. */ snippet: string; /** Flipped BM25 score — higher = better (the underlying FTS5 score is * negative; we negate so callers can sort descending). */ score: number; /** v2.8.0 — content-source kind. Defaults to "md" for backward compat. */ kind: ChunkKind; } /** Counter summary returned by the FTS5 sync routine in `server.ts`. */ export interface FtsSyncReport { /** Files newly indexed (no prior source_state row). */ added: number; /** Files re-indexed due to mtime change. */ updated: number; /** Files dropped because the source vanished from the vault. */ deleted: number; /** Files whose mtime matched the stored row — no work needed. */ unchanged: number; /** Total chunks in the index after the sync. */ total_chunks: number; } /** * SQLite FTS5 inverted index over chunked note content. Opt-in via * `--persistent-index`. Provides sub-100ms BM25-ranked search on * multi-thousand-note vaults; falls back transparently to the in-memory * parallel-scan path when `better-sqlite3` isn't installed. * * Construct, then call `open()`, then drive incremental sync via * {@link diff} + {@link reindexFile} / {@link reindexPdfFile} / {@link dropFile}. * Query with {@link search}; deep-link to individual chunks with * {@link getChunk}. * * @example * ```ts * const idx = new FtsIndex({ file, vaultRoot, tokenize: "unicode61" }); * await idx.open(); * idx.reindexFile(relPath, mtimeMs, content, wikilinkTargets, tags); * const hits = idx.search("vector retrieval", { limit: 25 }); * idx.close(); * ``` */ export declare class FtsIndex { private db; private readonly file; private readonly tokenize; private readonly vaultRoot; constructor(opts: { file: string; vaultRoot: string; tokenize?: TokenizeMode; }); /** * Open the SQLite database, bootstrap the FTS5 virtual table + helpers, * and tighten file perms to 0o600 on the db + WAL/SHM sidecars. Idempotent — * a second `open()` call is a no-op. * * @throws {Error} If `better-sqlite3` (optional dep) fails to load or * the native binding can't be loaded. */ open(): Promise; /** Remove the index file + WAL/SHM sidecar files. Idempotent. */ clearOnDisk(): Promise; /** Close the underlying SQLite handle. Idempotent. Call before process * exit to flush WAL. */ close(): void; private bootstrapSchema; private readMeta; private writeMeta; private requireDb; /** * Diff the on-disk source_state against the live vault snapshot. Returns * categorized lists; caller is expected to feed `added` + `updated` paths * back into reindexFile() and pass `deleted` to dropFile(). * * v2.8.0: optional `kind` filter — when set, the diff only considers * source_state rows of that kind. Lets the markdown-sync and PDF-sync * paths run independently against the same DB without one's "missing * files" being mistakenly deleted by the other. Default `undefined` * means "all kinds" (used by older callers + diff queries that want * a global view). */ diff(liveEntries: Array<{ relPath: string; mtimeMs: number; }>, kind?: ChunkKind): { added: string[]; updated: string[]; deleted: string[]; unchanged: string[]; }; /** Drop a file's chunks + state row. Idempotent. * * v3.7.18 R-8 — wrapped in `db.transaction()` for atomicity. Pre-3.7.18 * the two DELETE statements ran independently; a crash / SIGKILL / DB * lock contention between them could leave `source_state` saying "this * file is indexed at mtime X" while `chunks` had no rows — causing the * next watcher event to skip re-indexing (state matches) but search to * miss the file (no chunks). Sibling of v3.7.10 audit #10 fix that * wrapped `reindexFile` / `reindexPdfFile` / source_state in a txn for * the same reason. Caught by round-20 external audit. */ dropFile(relPath: string): void; /** Re-chunk a single markdown file, replacing its existing chunks atomically. * * v3.7.10 (external audit #10) — wrapped DELETE + N×INSERT + source_state * UPDATE in a single SQLite transaction. Pre-fix a crash/error between * statements could leave partially-updated chunks (some new, some stale) * with a stale source_state row pointing at the wrong chunk count. The * transaction guarantees all-or-nothing atomicity. better-sqlite3 * `db.transaction()` wraps + auto-rolls back on throw. */ reindexFile(relPath: string, mtimeMs: number, content: string, wikilinkTargets?: string[], tags?: string[], title?: string, aliases?: string[]): number; /** * v2.8.0 — re-chunk a single PDF, replacing its existing chunks atomically. * Caller pre-extracts page text via `extractPdfText` (src/pdf.ts) so this * method stays decoupled from pdfjs-dist (which is an optionalDependency). * * Page boundaries are preserved as `[page: N]` markers in the joined text * before chunking — the chunker may split a page across chunks or merge * short pages, but the markers travel with the text so search snippets * carry page citations. Same `chunkContent` pipeline as markdown so chunk * IDs match across the BM25 / TF-IDF / embeddings rankers (RRF requires * stable IDs). */ reindexPdfFile(relPath: string, mtimeMs: number, pages: ReadonlyArray<{ pageNumber: number; text: string; }>): number; /** * BM25-ranked search over chunk content. Folder + tag + recency filters * are pushed down to the SQL layer. Hyphenated identifiers (e.g. * `"claude-telegram"`) are quote-escaped via {@link safeFts5Query} so * FTS5 doesn't interpret `-` as the `NOT` operator. * * @param rawQuery - User query string. Whitespace-only returns `[]`. * @param opts.limit - Max results. Default 25. * @param opts.folder - Vault-relative prefix filter. * @param opts.tag - Exact-tag membership filter (only matches the full * tag, not `core-team` for `core`). * @param opts.sinceMtimeMs - Recency filter — only return chunks from * files modified at or after this mtime. * @returns Sorted hits (score desc). Empty array if no usable query * tokens or no matches. */ search(rawQuery: string, opts?: { limit?: number; folder?: string; tag?: string; sinceMtimeMs?: number; }): FtsSearchHit[]; /** * Fetch a single chunk by (rel_path, chunk_index). Backs the * `obsidian://chunk/{chunkIndex}/{+notePath}` resource so MCP clients can * deep-link into specific chunks returned by a prior search. Returns the * RAW chunk text (the unenriched original); the FTS5 `content` column * additionally carries a synthetic wikilink-targets meta-line for recall, * which would otherwise pollute resource responses (audit v0.10.4 P1). */ getChunk(relPath: string, chunkIndex: number): { content: string; line_start: number; line_end: number; } | null; /** Total chunks across the index. Used by stats / banner / UI. */ totalChunks(): number; /** Total source files (notes + PDFs) tracked in `source_state`. Used by * the ready banner so users can verify the index actually built. */ totalFiles(): number; } /** * Sanitize a user query for FTS5. Quote-wraps any token containing * non-alphanumerics so hyphens / colons / dots are treated literally * (without this, `"claude-telegram"` would parse as `claude NOT telegram`). * * v3.7.16 P3-28 — reserved keywords (`AND`, `OR`, `NOT`, `NEAR`) are * QUOTED as literals instead of stripped. Pre-3.7.16 the strip-path * silently dropped real query terms ("operating systems AND databases" * lost the connective AND user couldn't search for the literal word * "AND"). Quoting makes both cases work: FTS5 treats `"AND"` as the * literal token rather than the boolean operator. * * @param q - User query string. * @returns Sanitized query ready to pass to FTS5's `MATCH` operator. * Empty string when input is empty / whitespace-only. */ export declare function safeFts5Query(q: string): string; interface ContentChunk { text: string; lineStart: number; lineEnd: number; /** v2.1.0: heading breadcrumb (e.g. "## Setup > ### Install") in effect at * chunk start. Empty if chunk is in the preamble (before first heading). * Callers concerned with retrieval quality can prepend this to chunk.text * before embedding/indexing — Chroma 2024 + NAACL 2025 both show * structural breadcrumbs lift NDCG@10 by 2-5 points at near-zero cost. */ breadcrumb: string; } /** * Paragraph-first chunker with `\n\n → \n → hardcut` fallback. Each chunk * carries 1-based line offsets so callers can quote precise locations. * * v2.1.0: also attaches a heading breadcrumb to each chunk (the H1>H2>H3 * path in effect at chunk start). Preserves Obsidian markdown structure * for downstream retrievers without a custom parser. ATX headings only — * fenced code blocks (where `#` is shell prompt, not heading) are skipped. */ export declare function chunkContent(content: string, maxChars?: number): ContentChunk[]; /** * v2.1.0: walk content line-by-line, tracking the H1>H2>H3 stack at each * point. Returns a per-line breadcrumb (joined with " > ") in effect AT * that line — i.e., the heading the line lives under. * * Skips heading-style chars inside fenced code blocks (``` and ~~~). * * Exported for the v3.11.5-rc.2 inline-span regression test (the fence-toggle * sibling of the rc.1 write-path MED). */ export declare function computeBreadcrumbsByLine(content: string): string[]; /** * Default location for the FTS5 index file — `~/.cache/enquire/.fts5.db` * (or `$XDG_CACHE_HOME` on Linux). The hash is the first 12 chars of * sha1(vaultRoot) so each vault gets its own database. * * @param vaultRoot - Absolute path to the vault root. * @returns Absolute path to the index file. */ export declare function defaultIndexFile(vaultRoot: string): string; /** * Plan a cache prune: given the filenames present in enquire's cache directory * and the 12-hex hash of the vault to KEEP, return the subset safe to delete — * enquire-owned artifacts belonging to OTHER vaults. Pure and side-effect-free, * so the destructive `prune` CLI can preview before touching disk and the * safety invariant (never selects a non-enquire file, never the kept vault) is * unit-testable. * * @param entries Filenames (basenames) present in the cache directory. * @param keepHash The 12-hex vault hash to preserve (from `defaultIndexFile`). * @returns Basenames safe to remove — strictly enquire artifacts, never `keepHash`. * @example planCachePrune(["aaaaaaaaaaaa.fts5.db", "bbbbbbbbbbbb.fts5.db", "notes.md"], "aaaaaaaaaaaa") * // → ["bbbbbbbbbbbb.fts5.db"] (keeps aaaa…, ignores notes.md) */ export declare function planCachePrune(entries: readonly string[], keepHash: string): string[]; /** * v3.6.2 K-1b — non-destructive peek at an existing fts5 index's meta row. * * Mirror of `peekEmbedDbMeta()` in `src/embed-db.ts`. Reads `tokenize_mode`, * `vault_root`, `schema_version` from a SQLite file WITHOUT opening it via * `FtsIndex` (which would trigger `bootstrapSchema()` and DROP TABLE on any * tokenize-mode mismatch with the caller's declared mode). * * **Why this exists (audit class K-1b):** the original v3.6.1 CRIT-1 fix * (peek-before-open) was applied ONLY to the `serve --use-hnsw` embed-db * path. The SAME bootstrap-schema-DROP class affects FtsIndex on * `tokenize_mode` mismatch. * * **Class-closure timeline (retroactive correction batch — see also * v3.7.2 audit response for the 4th drift instance: this TSDoc itself * previously mis-attributed the closure to v3.6.3):** * - v3.6.1 fixed 1 callsite (`server.ts` HNSW path), claimed "CRIT-1 * closed". External audit caught 9 residual. * - v3.6.2 fixed `server.ts:174` (serve start) + `doctor.ts:328` + * `src/tools/search.ts:917` (3 callsites total). The v3.6.2 CHANGELOG * TL;DR + this TSDoc previously claimed "all 10 callsites" — that * was an overclaim. cli.ts had 5 residual sites. * - v3.6.3 was deferred to a marketing-only patch ("memory for AI * agents" positioning); K-1 work was pushed to v3.6.4. * - v3.6.4 closes the cli.ts class: `cli.ts:638` (eval, diagnostic class * like doctor), `cli.ts:514,554` (setup, idempotent class), and * `cli.ts:311,398` (index, build-embeddings — peek-and-honor when * user did NOT explicitly pass `--tokenize` / `--embedding-model`). * `clear-index` and `clear-embeddings` call only `.clearOnDisk()` and * never trigger bootstrapSchema — marked `// SAFE BY DESIGN`. Added * `tests/k1-class-invariant.test.ts` (grep gate, 40-line window). * - v3.7.0 added `tests/k1-ast-invariant.test.ts` (TypeScript compiler * API def-use trace) catching the "peek called but result discarded" * bypass that grep would miss. * * **K-1 class is structurally enforced at v3.6.4 (grep) + v3.7.0 (AST).** * `tests/k1-class-invariant.test.ts` enforces the grep rule: every * `new EmbedDb(...)` / `new FtsIndex(...)` must be preceded by a * `peek*Meta` call OR an explicit `// SAFE BY DESIGN` comment within * 40 lines. `tests/k1-ast-invariant.test.ts` enforces the deeper rule: * the peek result must trace to one of the constructor's K-1-relevant * args (modelAlias / dim / tokenize / quantization). * * Returns null if the file doesn't exist OR doesn't have a `meta` table * yet. v3.11.0-rc.9 (audit re-verify) — TSDoc corrected: this NEVER throws * (rc.33 wrapped `new Database()` + the meta queries in a catch that maps ANY * failure — corrupt / unreadable / not-a-DB / directory / missing dep — to null); * it is the pre-open peek on the serve boot path, so a throw would crash serve. * * @param file - Absolute path to a `.fts5.db` file. * @returns Meta dict if the file is a populated fts5 index, null otherwise. * @example * ```ts * const meta = await peekFtsMetaSafe(indexFile); * if (meta?.tokenize_mode) { * const idx = new FtsIndex({ file: indexFile, vaultRoot, tokenize: meta.tokenize_mode }); * } * ``` */ export declare function peekFtsMetaSafe(file: string): Promise<{ schema_version?: string; vault_root?: string; tokenize_mode?: TokenizeMode; } | null>; export {}; //# sourceMappingURL=fts5.d.ts.map